4

I'm trying to load data during onCreate (also tried during onStart) via AsyncTask from a Room database. The thing is, I'm passing the context to the AsyncTask via a WeakReference and, sometimes (one out of four times) the context becomes null on the onPostExecute, even though the task finishes almost instantly (it's a small database).

I don't know which is the correct approach to load data via AsyncTask on the onCreate method without risking the context to become null so quick - I know it has to be done via WeakReference in order to avoid memory leaks, but I think the activity gets recreated for some reason sometimes so quickly that the task can't post the results to the original context and the data doesn't show up in the Activity.

Any ideas what is the correct way to handle this, given the fact the task finishes almost instantly, but it's a requirement of the Room library to do it via another thread (an also improves performance and responsiveness)?

So just for the sake of clearness, I'm trying to access the context this way:

public MyTask(ActivityListener listener) {
    mWeakContext = new WeakReference(listener);
}

protected void onPostExecute(Boolean result) {
    AcitivtyListener aListener = mWeakContext.get();
    if (aListener != null) aListener.refresh(data);
}

The ActivityListener interface is implemented anonymously on the call to new MyTask(new ActivityListener() { ... });

Thanks

Azurlake
  • 612
  • 1
  • 6
  • 29

1 Answers1

0

Yeah I think context becoming null means activity was re-created, but it seems unlikely to happen as I imagine its so fast you couldn't rotate the phone faster than the database operation

Indirect answer to this question would simply be: do not use AsyncTask at all, use ViewModel and LiveData - they are part of the architecture thing from google as well as Room that you are using

To put it short these two components will solve issues with lifecycle management/context leaking and also sending results to correct Activity instance

See documentation on LiveData and ViewModel: livedata viewmodel

estn
  • 1,203
  • 1
  • 12
  • 25
  • Thanks for the answer. I will check if this solves the issue (it's not trivial) and consider validating the answer tomorrow! Cheers – Azurlake Aug 19 '18 at 22:29
  • Yeah its not trivial but if you invest your time I think youll see that this approach is better and maybe also if you look into lets say RxJava you will leave AsyncTasks completely, love to hear on your progress – estn Aug 20 '18 at 18:07