priya
priya

Reputation: 163

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 UI. I just wish to pass data. The class that e![enter image description here][1]xtends async task is not a part of the class that extends activity

My activity has 2 buttons. When the button is clicked, async task is called and corresponding changes should be made to rest of the activity.

Upvotes: 0

Views: 5420

Answers (7)

AlQode
AlQode

Reputation: 95

I would create a inner class in the MainActivity that extends the AsyncTask and voila all data is there already by getters.

Upvotes: 0

Then regarding your answer, in actually you have a 2 possibilities... The first one is the answer from @Rodolfoo Perottoni and the other possibility are correctly, read this post please!

I prefer the second way because I can update when I need it.

Upvotes: 0

Amol Patil
Amol Patil

Reputation: 491

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

 }

Upvotes: 0

K.Hui
K.Hui

Reputation: 153

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

Upvotes: 0

Umesh Singh Kushwaha
Umesh Singh Kushwaha

Reputation: 5741

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

Upvotes: 0

Umang Kothari
Umang Kothari

Reputation: 3694

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

Upvotes: 1

VulfCompressor
VulfCompressor

Reputation: 1410

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

}

Upvotes: 1

Related Questions