AsyncTask returns a list for activity

How to return the list generated in AsyncTask to Activity?

My class is LoadStringsAsync:

public class LoadStringsAsync extends AsyncTask<Void, Void, List<String> > { List<String> str; @Override protected void onPreExecute() { super.onPreExecute(); ... } @Override protected List<String> doInBackground(Void... arg0) { ... get content from the internet and fill the list ... } @Override protected void onPostExecute(List<String> str) { super.onPostExecute(events); ... } } 

and I need a List in my work to work with it. (No, not to show this in ListView: P)

Any suggestions on how to do this ?:-)

Thanks!

+6
source share
5 answers

Your Activity :

 public class YourActivity extends Activity { private List<String> list = new ArrayList<String>(); public void onCreate(Bundle state) { //... } public void setList(List<String> list) { this.list = list; } private void fireYourAsyncTask() { new LoadStringsAsync(this).execute(); } } 

AsyncTask

 public class LoadStringsAsync extends AsyncTask<Void, Void, List<String>> { List<String> str; private YourAcitivity activity; public LoadStringsAsync(YourAcitivity activity) { this.activity = activity; } @Override protected List<String> doInBackground(Void... arg0) { } @Override protected void onPostExecute(List<String> str) { super.onPostExecute(events); activity.setList(str); } } 
+8
source

If you make your AsyncTask an inner class in your activity, then onPostExecute will be in the same context as the Activity, and you can use the List, as anywhere in the Activity.

If you are not making your AsyncTask an inner class in your activity, you need to set up a listener to return to your activity when AsyncTask ends. If you prefer to follow this route, check out this post .

There is also this post that is similar to your question.

+2
source

Put the code that uses the list, or sets it to a variable inside onPostExecute() .

Better start your task from parent activity, for example:

 public class MyActivity extends Activity{ private List<String> mData = new ArrayList<String>(); private void runTask(){ new LoadStringsAsync(){ @Override protected void onPostExecute(List<String> str) { super.onPostExecute(events); mData.clear(); mData.addAll(str); } }.execute(); } } 
0
source

You can send your list to the handler inside the message:

 Message msg = Message.obtain(); msg.obj = myList; handler.sendMessage(msg); 

Additional information: http://developer.android.com/reference/android/os/Message.html

0
source

According to the documentation on the android link, you can use the get method to return the calculation results. Since your AsyncTask shows that you are returning a list, you can try the following code in the class that you call the asynchronous class

 List<String> returnedlist=new LoadStringAsync().execute().get(); 

We hope this option helps.

0
source

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


All Articles