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