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:

classYourActivityextendsActivity {
   privatestatic final int DIALOG_LOADING = 1;

   publicvoidonCreate(Bundle savedState) {
     setContentView(R.layout.yourlayout);
     newLongRunningTask1().execute(1,2,3);

   } 

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

   privateclassLongRunningTaskextendsAsyncTask<Long, Integer, List<String>> {
        @OverrideprotectedvoidonPreExecute() {
          //do pre execute stuff
        }

        @OverrideprotectedList<String> doInBackground(Long... params) {
            List<String> myData = newArrayList<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;
        }

        @OverrideprotectedvoidonPostExecute(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,

@OverrideprotectedvoidonPostExecute(Object result) {
    super.onPostExecute(result);
        Messagemessage=newMessage();
        Bundlebundle=newBundle();
        bundle.putString("file", pdfPath);
        message.setData(bundle);
        handler.sendMessage(message); // pass handler object from activity
}

put following code into Activity class

Handlerhandler=newandroid.os.Handler() {
    @OverridepublicvoidhandleMessage(Message msg) {
          StringfilePath= 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

publicclassSocket {
     privateActivity activity;
     //create interfacepublicinterfaceOnAyscronusCallCompleteListener{
            publicvoidonComplete(/*your data as parameter*/);
    }
    privatevoidsetAsyncListener(Activity activity){
        this.activity = activity;
     }
    //rest of your code// send back data to activity
    activity.onComplete(/* your data */)
    }
//Now your activityclassYourActivityextendsActivityimplementsSocket.OnAyscronusCallCompleteListener {

// rest of your activity life cycle methodsonCreate(Bundle onSaved)
{Socket socket = newSocket();
socket.setAsyncListener(this);
}
publicvoidonComplete(/*your data*/){
// perform action on data
}
}

Solution 4:

In your Activity Class

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

Your AsyncTask AsyncTask<Params, Progress, Result>

privateclassYourAsyncTaskextendsAsyncTask<String, Void, Void > {
     protectedLongdoInBackground(String... s) {
         String s1 = s[0]; //="String1";String s2 = s[1]; //="String2";
         int s1 = Integer.parseInt(s[2]); //=3;
     }

     protectedvoidonProgressUpdate(Void... values) {

     }

     protectedvoidonPostExecute() {

     }
 }

A great explanation is here

Solution 5:

Example to implement callback method using interface.

Define the interface, NewInterface.java.

package javaapplication1;

publicinterfaceNewInterface {
   voidcallback();
  }

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

package javaapplication1;

 publicclassNewClass {

private NewInterface mainClass;

publicNewClass(NewInterface mClass){
    mainClass = mClass;
}

publicvoidcalledFromMain(){
    //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;

publicstaticvoidmain(String[] args) {

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

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

}

privatevoiddoSomething(){
    newClass = newNewClass(this);
    newClass.calledFromMain();
}

@Overridepublicvoidcallback() {
    System.out.println("callback");
}

 }

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