简体   繁体   中英

Getting the return of an AsyncTask and work with it?

I have an AsyncTask which returns a map with 2 elements. I did it like this:

        Map<String, ArrayList<String>> result = new HashMap<String, ArrayList<String>>();
        result.put("usernames", usernames);
        result.put("messages", messages);

    return result;

Now I call this Async in another Activity:

new ReadChat().execute(response);

How can I get the returned data in this other Activity from the Async Task (from the doInBackground() )?

You need to save the ReadChat instance somewhere. Then, set values inside ReadChat , wait until it finishes, then read those values back.

How can I get the returned data in this other Activity from the AsyncTask?

At first i think that your question is not very clear. It depends on "what you want to do with these data" . AsyncTask is designated with three we can say "main" methods:

  • onPreExecute() - is called before task started
  • doInBackground() - for doing some work "in silence" in the background
  • onPostExecute() - is called after doInBackground() is done

So if your doInBackground() method returns Map<String, ArrayList<String>> you can use it in onPostExecute() that takes it as parameter eq:

@Override
public void onPostExecute(Map<String, ArrayList<String>> result) {
   // do some stuff
}

Here you can do whatever you want with result for example update your UI with these data, persist data with SharedPreferences or SQLite , make some next calculation, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM