How to pass the result of asynctask onpostexecute method to android parent activity

I am developing an application in which I need to send the asynctask onPostExecute value to the result of a previous operation, that is, the activity in which the aync task is called. pls put some codes. Anyhelp rated

+4
source share
5 answers

Two ways:

  • Declare a class extending AsyncTask as a private class in parent activity
  • Skip handler or activity itself as a class parameter extending AsyncTask

If I were you, I would complete the first option.
Check out the DOCS :

class MyActivitySubclass extends Activity { function runOnPostExecute(){ // whatever } private class MyTask extends AsyncTask<Void, Void, Void> { void doInBackground(Void... params){ // do your background stuff } void onPostExecute(Void... result){ runOnPostExecute(); } } } 

Note 1

The code placed in the body of the onPostExecute function is already running in the Activity thread, you just have to mention that this keywords result in MyTask.this and not MyActivitySubclass.this

+8
source

Well, if your AsyncTask is an inner class, you can simply call the method in your activity from onPostExecute() :

 public class MyActivity extends Activity { public void someMethod(String someParam) { // do something with string here } public class InnerTask extends AsyncTask<...> { protected void onPostExecute(result) { someMethod(Send parameters); } } } 
+2
source

The onPostExecute method runs in the main user interface thread, so everything that is done there is already in the AsyncTasks caller.

http://developer.android.com/reference/android/os/AsyncTask.html

+1
source

Fire an event in OnPostExecute.

+1
source

His addition to Marek Seber’s answer, he indicated the use of a handler. To make the code simple and intuitive, use the interface. This is not an alien concept, we constantly use it for callback functions (for example, OnClickListner, etc.). The code will look something like this.

  public class InnerTask extends AsyncTask<...> { interface ResultHandler { void gotResult(<> result); } private ResultHandler myResult; //constructor public InnerTask(....params...,ResultHandler callback) { ... this.myResult = callback; } protected void onPostExecute(<>result) { ... myResult.gotResult(result); } } public class MyActivity extends Activity implements InnerTask.ResultHandler { @Override protected void onCreate(Bundle savedInstanceState) { //do something //if you want the InnerTask to execute here InnerTask i = new InnerTask(....params...,this); //send 'this' as parameter i.execute(); } @Override public void gotResult(<> result) { //from onPostExecute } } 

If we want to use the same AsynTask class on multiple sites, we can use this type of implementation instead of using nested classes.

0
source

Source: https://habr.com/ru/post/949239/


All Articles