简体   繁体   English

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

[英]variable not getting updated in doInBackground method of AsyncTask

I am trying to use the following code to obtain the result value, but the it never seems to update. 我试图使用以下代码来获取result值,但它似乎永远不会更新。 I am checking the result in the class called startPosting() : 我正在检查名为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) {
    //          
  }

}

The reason result is not getting updated is because you're attempting to check it immediately after you call the AsyncTask . result未更新的原因是因为您在调用AsyncTask后尝试立即检查它。

Here's how you could re-structure it: 以下是您重新构建它的方法:

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);
  }

}

And to call it: 并称之为:

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

Then modify onPostExecute to do whatever you need to with result . 然后修改onPostExecute以执行result所需的任何操作。

if result is an int try this: 如果结果是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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM