Issue
How to return value to main activity after run another AsyncTask in onPostExecute()?
I have written function in 2nd Asynctask to return ArrayList back to 1st Asynctask. However, I don't know how to return the ArrayList from 1st Asynctask back to main activity.
//Main Activity:
DownloaderGet downloaderGet = new DownloaderGet(getActivity(), "http://xxxxx.php");
downloaderGet.execute();
//1st AsyncTask(DownloaderGet)
@Override
protected void onPostExecute(String jsonData) {
super.onPostExecute(jsonData);
new DataParserGet(c, jsonData).execute();
}
//2nd Asynctask(DataParserGet)
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pd.dismiss();
if(result)
{
myNewArrayList = spacecrafts;
passToClass();
}
}
Solution
Problem: You want to pass the array list from the second AsyncTask back to MainActivity.
Solution: Passing activity instance to the first AsyncTask, then forward the instance to the second AsyncTask.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Pass `this` as activity instance to the first AsyncTask.
DownloaderGet downloaderGet = new DownloaderGet(this, "http://xxxxx.php");
downloaderGet.execute();
}
public void onDataAvailable(List<String> arrauList) {
// Process array list here.
}
}
// The first AsyncTask.
class DownloaderGet extends AsyncTask<Void, Void, String> {
private WeakReference<MainActivity> activity;
private String url;
DownloaderGet(MainActivity activity, String url) {
this.activity = new WeakReference<>(activity);
this.url = url;
}
@Override
protected String doInBackground(Void... voids) {
// Your code here
// ...
return null;
}
@Override
protected void onPostExecute(String jsonData) {
// Forward the instance to the second AsyncTask.
new DataParserGet(activity.get(), jsonData).execute();
}
}
class DataParserGet extends AsyncTask<Void, Void, Boolean> {
private WeakReference<MainActivity> activity;
private String jsonData;
DataParserGet(MainActivity activity, String jsonData) {
this.activity = new WeakReference<>(activity);
this.jsonData = jsonData;
}
@Override
protected Boolean doInBackground(Void... voids) {
// Your code here
// ...
return null;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
myNewArrayList = spacecrafts;
if (activity.get() != null) {
// Pass the array list back to main activity.
activity.get().onDataAvailable(myNewArrayList);
}
}
}
}
Answered By - Son Truong
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.