如何使用 AsyncTask 的 onPostExecute 方法更新 Android 中的变量

Posted

技术标签:

【中文标题】如何使用 AsyncTask 的 onPostExecute 方法更新 Android 中的变量【英文标题】:How do I use AsyncTask' s onPostExecute method to uptate a variable in Android 【发布时间】:2018-03-27 14:07:04 【问题描述】:

在使用AsyncTask 运行后台任务后,我尝试将变量更新为后台任务的结果。变量更新,但显然不准时。我用来显示服务器响应的吐司首先显示一个空吐司,然后第二次显示一个非空吐司(这会弄乱我的代码中的所有内容,因为按时收到的响应是它所需要的)。 在发布代码之前,我需要指出,如果我在 UI 线程上运行代码的替代版本(同时在 UI 线程上强制连接),我没有任何问题。该变量将使用该变量进行更新。

String databaseCheckResult = "";

private class AsyncCheckIfExists  extends AsyncTask<String, Integer, String> 
    String result = null;
    @Override
    protected void onPreExecute()

    

    @Override
    protected String doInBackground(String... formValues) 
        try 
            URL url = new URL(formValues[1]);
            try 
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches (false);
                String urlParameters  = "date=" + formValues[0];
                byte[] postData = urlParameters.getBytes("UTF-8");
                OutputStream os = conn.getOutputStream();
                os.write(postData);
                os.flush();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) 
                    // success, get result from server
                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) 
                        response.append(inputLine);
                    
                    in.close();
                    conn.disconnect();
                    result = response.toString();
                    return result;
                 else 
                    // error
                    //TODO: let the user know that something is wrong with the network
                
             catch (java.io.IOException e) 
                //TODO: prevent app from crashing
            
         catch (java.net.MalformedURLException e)
            //TODO: prevent app from crashing
        
        return null;
    

    @Override
    protected void onProgressUpdate(Integer... progress)

    

    @Override
    protected void onPostExecute(String message)
        databaseCheckResult = message;
    



我称之为:

    AsyncCheckIfExists check = new AsyncCheckIfExists();
    check.execute(date, "http://www.webaddress.com/script.php");

【问题讨论】:

我没有看到任何Toast。对于您的问题,一旦doInbackground() 完成,它将返回到onPostExcceute(),其中包含在 UI 线程上调用的数据。您可以在任何地方更新实例变量。阅读AsyncTask 调用周期。如果问题仍然存在,请澄清您的问题。 Toast 是由我活动中的另一种方法启动的。 【参考方案1】:

@ADM,我已经使用我在您提供的链接中找到的方法修复了它(我真的应该阅读更多内容)。 databaseCheckResult = check.execute(date, "http://www.webaddress.com/script.php").get(); 解决了这个问题(try,catch ommitted)。谢谢。

【讨论】:

这就是精神。在使用 API 类之前先明确概念。适当地解释答案。 我现在有新问题。我不能使用ProgressDialog,因为get() 方法(正如我研究过的那样)将任务从AsyncTask 转换为在ui 线程上运行的“NonAyncTask”(刚才创造的)。有没有办法解决?当活动从服务器请求数据时,我真的需要显示进度对话框。 您可以在onPreExecute() 中进行操作。或者您可以在 Activity 中显示 ProgressDialog 并通知 Activity 到 dismiss() 它。 我已经尝试了两种方法,但对话框仅在整个过程(连接到服务器并获取数据)完成后才会显示。

以上是关于如何使用 AsyncTask 的 onPostExecute 方法更新 Android 中的变量的主要内容,如果未能解决你的问题,请参考以下文章

如何在修改之前在 AsyncTask 中使用变量?

如何正确使用 AsyncTask? [关闭]

如何使用AsyncTask

如何使用 AsyncTask 更新全局变量

AsyncTask - 如何在AsyncTask中使用带有postDelayed(Runnable,int)的Handler?

如何使用 DialogFragment 显示 AsyncTask 的进度 - 不使用 ProgressDialog