变量没有在AsyncTask的doInBackground方法中更新

时间:2012-01-19 00:32:38

标签: java android android-asynctask

我正在尝试使用以下代码来获取result值,但它似乎永远不会更新。我正在检查名为startPosting()的课程中的结果:

public class PostDataThread extends AsyncTask<Void, Void, Void> {

  String [] data;
  Context context;
  int result = 0;

  public int startPosting(int type,String data[], Context c) {
    this.data = data;
    this.context = c;
    this.execute();
    return result;
  }

  @Override
  protected Void doInBackground(Void... params) {
    Connect c = new Connect();
    c.start(Constant.RECEIVED_MESSAGE, data, context);
    result = 444;
    return null;
  }

  protected void onPostExecute(Integer result) {
    //          
  }

}

2 个答案:

答案 0 :(得分:2)

result未获得更新的原因是因为您在致电AsyncTask后尝试立即 进行检查。

以下是您重新构建它的方法:

public class PostDataThread extends AsyncTask<Void, Void, Integer> {

  String [] data;
  Context context;
  int res = 0;

  public PostDataThread(int type, String data[], Context c) {
    this.data = data;
    this.context = c;
  }

  @Override
  protected Void doInBackground(Void... params) {
    Connect c = new Connect();
    c.start(Constant.RECEIVED_MESSAGE, data, context);
    res = 444;
    return res;
  }

  @Override
  protected void onPostExecute(Integer result) {
    Log.d(TAG, "Result is: " +result);
  }

}

并称之为:

PostDataThread p = new PostDataThread(type, data, context);
p.execute();

然后修改onPostExecute以使用result执行您需要的任何操作。

答案 1 :(得分:2)

如果结果为int,请尝试:

public class MyActivity extends Activity{
    private int result = 0

    private class MyTask extends AsyncTask<Integer, Void, Integer>{
         public Integer doInBackground(Integer... arg){
             //Conncet c = new Connect();
             //result=c.start(Constant.RECEIVED_MESSAGE, data, context);
             //commented out for debug purposes
             return 23774
         }

         public void onPostExcecute(Integer res){
             result = res
         }
    }

    public void onResume(){
         super.onResume();
         MyTask mt = new MyTask();
         mt.execute(0);
         Handler h = new Handler(new Handler.Callback(){
              public void handleMessage(Message m){
                  //check result here
                  Log.i("RESULT", result);
              }
         });
         //takes 5 seks to wait
         h.sendEmptyMessageDelayed(0, 5000);
    }

}