Again, another question about ayncTask. Is the what I am doing below correct?
Class UpdatePersonActivity{
Person person;
.
.
.
.
.
private class UpdatePersonAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
private DBHandler dbHandler;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(UpdatePersonActivity.this, "Please wait..", "working..", true);
dbHandler = new DBHandler(UpdatePersonActivity.this);
}
@Override
protected Void doInBackground(Void... params) {
dbHandler.open();
long id = dbHandler.updatePerson(person);
person.setId(id);
dbHandler.close();
return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
Toast.makeText(UpdatePersonActivity.this, "Tenant "+person.getName()+" has been updated successfully!", Toast.LENGTH_SHORT).show();
finish();
}
}
Basically I have “person” variable which is in the activity class and the same variable is used to insert into DB and updating its ID in the DoInBackground, and the same variable is used for GUI purpose
Can I do that? I tried it and it works but is it something I shouldnt do?
Thanks
As far as sharing a variable between an
AsyncTaskand the UI thread, the only concern is synchronization. If it is possible that the UI thread (or any other thread) might be updating yourPersonobject while it is being accessed indoInBackground, then you need to synchronize or otherwise coordinate access. If during the time theAsyncTaskexecutes you are guaranteed that the only accesses to the sharedPersonobject will not modify the object, then you can dispense with the synchronization.However, you should be aware of a general problem with using
AsyncTaskas an inner class of anActivity. If your activity is restarted for any reason (for example, a configuration change such as the user rotating the phone), then the activity that theAsyncTaskupdates will no longer be valid. A description of the problem and some suggestions for what to do about it are described here.See here for even more discussion on this issue, including an approach for maintaining a progress dialog for an
AsyncTaskacross activity restarts.