Reputation: 4063
I have a few async tasks that get data from JSON services. In the onPreExecute of the outside task I want to show a progressDialog. I want to dismiss it in onPostExecute and start another activity.
The problem is that there is still data loading when my onPostExecute is called, so the next activity is executed without the needed data.
Is this normal behavior? Is there a workaround?
class GetDataAsync extends AsyncTask<Integer, Integer, Integer> {
@Override
protected void onPreExecute() {
Log.d("startupflow","GetDataAsync onPreExecute");
progress = new ProgressDialog(Login.this);
progress.setMessage("Loading...");
progress.show();
super.onPreExecute();
}
@Override
protected Integer doInBackground(Integer... params) {
Log.d("startupflow","GetDataAsync doInBackground");
GetData getData = new GetData();
getData.LoadAllData(getApplicationContext(), token, client);
return null;
}
@Override
protected void onPostExecute(Integer integer) {
Log.d("startupflow","GetDataAsync onPostExecute");
if (progress.isShowing()) {
progress.dismiss();
}
Intent intent = new Intent(Login.this, Admin.class);
startActivity(intent);
super.onPostExecute(integer);
}
In the GetData class:
public void LoadAllData(Context context, Token token, OAuth2Client client) {
this.context = context;
this.token = token;
this.client = client;
new AllDataAsync().execute();
}
class AllDataAsync extends AsyncTask<Integer, Integer, Integer> {
@Override
protected Integer doInBackground(Integer... params) {
try {
Log.d("GetData", "In AllDataAsyc, do in background");
GetClientandToken(token, client);
Log.d("GetData", "getcompanyanddatatapstask");
new GetCompanyAndDataTapsTask().execute();
Log.d("GetData", "getslidestask");
new GetSlidesTask().execute();
} catch (Exception e) {
e.printStackTrace();
errorOccurred = true;
}
return null;
}
}
The Log:
08-12 11:27:37.515 D/startupflow﹕ GetDataAsync onPreExecute
08-12 11:27:37.562 D/startupflow﹕ GetDataAsync doInBackground
08-12 11:27:37.601 D/startupflow﹕ GetDataAsync onPostExecute
08-12 11:27:40.132 D/startupflow﹕ all data saved
Upvotes: 0
Views: 336
Reputation: 10177
The reason your first async is starting the activity early is because it is only starting the second data-loading async. AsyncTasks work on different threads (hence asynchronous), meaning they don't wait for each other.
What you can do is call a function in the postExecute of the data-loading async to notify your activity that it's done. E.g. add an onFinishedLoadingData function, and call that in your postExecute. You can start your new activity there.
Upvotes: 2