Skip to content Skip to sidebar Skip to footer

How To Pass Data From An Asynchronous Task To An Activity That Called It?

I am new to Android. I am using Sockets in an asynchronous task and I wish to pass data back to the activity that called it. But I do not want the asynchronous task to handle the U

Solution 1:

From How do I send data back from OnPostExecute in an AsyncTask:

class YourActivity extends Activity {
   private static final int DIALOG_LOADING = 1;

   public void onCreate(Bundle savedState) {
     setContentView(R.layout.yourlayout);
     new LongRunningTask1().execute(1,2,3);

   } 

   private void onBackgroundTaskDataObtained(List<String> results) {
     //do stuff with the results here..
   }

   private class LongRunningTask extends AsyncTask<Long, Integer, List<String>> {
        @Override
        protected void onPreExecute() {
          //do pre execute stuff
        }

        @Override
        protected List<String> doInBackground(Long... params) {
            List<String> myData = new ArrayList<String>(); 
            for (int i = 0; i < params.length; i++) {
                try {
                    Thread.sleep(params[i] * 1000);
                    myData.add("Some Data" + i);
                } catch(InterruptedException ex) { }                
            }

            return myData;
        }

        @Override
        protected void onPostExecute(List<String> result) {
            YourActivity.this.onBackgroundTaskDataObtained(result);
        }    
    }

}

Solution 2:

Yes you can use handler to communicate between AsyncTask and Activity, see following example, it will help,

@Override
protected void onPostExecute(Object result) {
    super.onPostExecute(result);
        Message message = new Message();
        Bundle bundle = new Bundle();
        bundle.putString("file", pdfPath);
        message.setData(bundle);
        handler.sendMessage(message); // pass handler object from activity
}

put following code into Activity class

Handler handler = new android.os.Handler() {
    @Override
    public void handleMessage(Message msg) {
          String filePath = msg.getData().getString("file"); // You can change this according to your requirement.

    }
};

If you dont't aware of Handler class then first read following link, it will help you

https://developer.android.com/training/multiple-threads/communicate-ui.html


Solution 3:

There are different way to pass data back to activity. As explained below

Suppose u have one class

    public class Socket {
     private Activity activity;
     //create interface
    public interface OnAyscronusCallCompleteListener{
            public void onComplete(/*your data as parameter*/);
    }
    private void setAsyncListener(Activity activity){
        this.activity = activity;
     }
    //rest of your code
    // send back data to activity
    activity.onComplete(/* your data */)
    }
//Now your activity

class YourActivity extends Activity implements  Socket.OnAyscronusCallCompleteListener {

// rest of your activity life cycle methods
onCreate(Bundle onSaved)
{Socket socket = new Socket();
socket.setAsyncListener(this);
}
public void onComplete(/*your data*/){
// perform action on data
}
}

Solution 4:

In your Activity Class

new YourAsyncTask().execute("String1","String2","12");

Your AsyncTask
AsyncTask<Params, Progress, Result>

 private class YourAsyncTask extends AsyncTask<String, Void, Void > {
     protected Long doInBackground(String... s) {
         String s1 = s[0]; //="String1";
         String s2 = s[1]; //="String2";
         int s1 = Integer.parseInt(s[2]); //=3;
     }

     protected void onProgressUpdate(Void... values) {

     }

     protected void onPostExecute() {

     }
 }

A great explanation is here


Solution 5:

Example to implement callback method using interface.

Define the interface, NewInterface.java.

package javaapplication1;

public interface NewInterface {
   void callback();
  }

Create a new class, NewClass.java. It will call the callback method in main class.

package javaapplication1;

 public class NewClass {

private NewInterface mainClass;

public NewClass(NewInterface mClass){
    mainClass = mClass;
}

public void calledFromMain(){
    //Do somthing...

    //call back main
    mainClass.callback();
}
 }

The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1; public class JavaApplication1 implements NewInterface{

NewClass newClass;

public static void main(String[] args) {

    System.out.println("test...");

    JavaApplication1 myApplication = new JavaApplication1();
    myApplication.doSomething();

}

private void doSomething(){
    newClass = new NewClass(this);
    newClass.calledFromMain();
}

@Override
public void callback() {
    System.out.println("callback");
}

 }

Post a Comment for "How To Pass Data From An Asynchronous Task To An Activity That Called It?"