简体   繁体   中英

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. I am checking the result in the class called 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 .

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 .

if result is an int try this:

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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