Note that there are some explanatory texts on larger screens.

plurals
  1. POObject scope and aggressive cleanup on paused Activity instances
    text
    copied!<p>I have an Activity that contains an AsyncTask as an inner class (as I have seen in most examples). If I fire the AsyncTask and then pause the Activity by navigating away from it, the AsyncTask continues to execute. As I understand it, this is normal and expected behavior.</p> <p>There is a member variable in the Activity that is being accessed by a method call from the AsyncTask. I just got a NullPointerException on it while the AsyncTask was executing in the background while its Activity was paused, which seems to me that it was collected by the GC when the Activity was paused. It would seem to me that the object should not be considered out of scope. There is code still running in the Activity, so why would the Activity's member variables start getting cleaned up already?</p> <p>What is the recommended usage of Activity member variables being accessed via AsyncTasks that are inner classes of the Activity?</p> <p>Here is a sample of the kind of relationships my objects have</p> <pre><code>public class MyActivity { MyCustomService myCustomService; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.some_layout); myCustomService = ServiceLocator.getInstance(MyCustomService.class); } private class FetchDataTask extends AsyncTask&lt;Void, Void, String&gt; { @Override protected String doInBackground(Void... arg0) { String data = someOtherService.fetchSomeData(); return data; } @Override protected void onPostExecute(String result) { refreshControls(result); } } private void refreshControls(String result) { // this is where the object is null after aggressive cleanup myCustomService.someMethod(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload