Search code examples
javaandroidasynctaskloader

Android exchange data between running asynctasks


What i am trying to achieve is share data between running asynctask (doInBackground). So whats happening is that i have separate class (extends Asynctask) that loads data and activity with its own Async class which i use to update info in the activity. Basicly what i am trying to achieve is the thread in the activity (monitoring thread) to work alongside with the loader and providing some data from the loader class and when the loader is ready both the "monitoring" and the "loader" should die.

I tried having a volatile variable which I set using interfaces, but no success i cant seem to be able to share information between the threads(asynctasks).. Any suggestions? Maybe an Exchanger class is needed?


Solution

  • Any reason you can't use the onProgressUpdate functionality? I may be confused by your use case... but an example might be the following:

    class MyActivity extends Activity {
    
      private AsyncTask<Uri,MyDataObject, MyResult> = new AsyncTask<Uri,MyDataObject, MyResult>() {
        private MyResult mResult;
    
        protected MyResult doInBackground(Uri... uris) {           
          int count = urls.length;
          mResult = new MyResult()
    
          for (int i = 0; i < count; i++) {
            MyDataObject anObject = mDataLoader.getObject(uris[i]);
            publishProgress(anObject);
    
            mResult.add(anObject);
            // Escape early if cancel() is called
            if (isCancelled()) break;
          }
          return totalSize;
        }
    
        protected void onProgressUpdate(MyDataObject... data) {
          addDataToUI(data[0]);
        }
    
        protected void onPostExecute(MyResult result) {
          Toast.makeText("All Done!", Toast.LENGTH_LONG).show();
        }
      }
    }