Julian A.
Julian A.

Reputation: 11460

Safe for inner AsyncTask to access outer Activity class private member fields?

Is it safe for an Android AsyncTask that's an inner class of an Activity to read the Activity's private member fields while in AsyncTask.doInBackground()? Thanks in advance.

Upvotes: 5

Views: 1220

Answers (2)

user173488
user173488

Reputation: 947

when an inner classes access private members (fields or functions) of the enclosing class, the compiler will generate accessor functions to those members. this will be breaking of encapsulation, some argue if it is a Good Thing or a Bad Thing.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007218

Generally, no. If the activity is undergoing a configuration change and is being destroyed and recreated, your background thread will be talking to the wrong instance, which may cause problems for you.

Ideally, the doInBackground() of an AsyncTask should be able to run independently of its launching component (activity, service, etc.). I suggest that you create a constructor on your AsyncTask and pass in whatever is needed. Or, have the AsyncTask be managed by a dynamic fragment that uses setRetainInstance(), in which case (AFAIK) it should be safe for the task to access private data members of the fragment, since the fragment is not going anywhere.

Upvotes: 8

Related Questions