Snake
Snake

Reputation: 14658

Shared variable in asyncTask

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

Upvotes: 1

Views: 1253

Answers (2)

Ted Hopp
Ted Hopp

Reputation: 234847

As far as sharing a variable between an AsyncTask and the UI thread, the only concern is synchronization. If it is possible that the UI thread (or any other thread) might be updating your Person object while it is being accessed in doInBackground, then you need to synchronize or otherwise coordinate access. If during the time the AsyncTask executes you are guaranteed that the only accesses to the shared Person object will not modify the object, then you can dispense with the synchronization.

However, you should be aware of a general problem with using AsyncTask as an inner class of an Activity. If your activity is restarted for any reason (for example, a configuration change such as the user rotating the phone), then the activity that the AsyncTask updates 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 AsyncTask across activity restarts.

Upvotes: 1

digitaljoel
digitaljoel

Reputation: 26574

You should use the types available in the AsyncTask. Instead of <Void, Void, Void> use <Person, Void, Person> Then your doInBackground will take a person as a parameter and will return type Person. onPostExecute will also take the Person as a parameter.

Upvotes: 1

Related Questions