我如何使用AsyncTask' s onPostExecute方法来强化Android中的变量

时间:2018-03-27 14:07:04

标签: android android-asynctask background-task background-thread

我在使用AsyncTask运行后台任务后尝试更新变量到后台任务的结果。变量更新,但显然不及时。我用来显示服务器响应的toast首先显示一个空的toast,然后第二次显示一个非空的toast(这会使我的代码中的所有内容混乱,因为按时收到的响应就是它所需要的)。

在发布代码之前,我需要指出,如果我在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");

1 个答案:

答案 0 :(得分:0)

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