Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onLoadFinished not called after coming back from a HOME button press

When using a custom AsyncTaskLoader to download data from a web service, if I press the HOME button in the middle of the loading process and then enter the app again, the onLoadFinished() method is not called. My fragment is calling setRetainInstance(true) in onActivityCreated() and it also calls getLoaderManager.initLoader(0, null, this) in the same method (as is recommended).

While testing, I see that when coming back to the fragment onActivityCreated() is not called so this may be why onLoadFinished() is not called. But where else to put the initLoader() method? I've read in several places that it should not be called in onResume().

So, any ideas? I have a lot of loaders in various screens in my app and I need to solve this issue in an elegant way.

like image 356
Catalin Morosan Avatar asked Sep 19 '11 17:09

Catalin Morosan


1 Answers

After looking at Issue 14944 (http://code.google.com/p/android/issues/detail?id=14944), I solved the issue by overriding onStartLoading() in my custom AsyncTaskLoader and call forceLoad().

An even better solution is to create a custom parent AsyncTaskLoader that looks like this (taken from a suggestion by alexvem from the link above):

public abstract class AsyncLoader<D> extends AsyncTaskLoader<D> {

    private D data;

    public AsyncLoader(Context context) {
        super(context);
    }

    @Override
    public void deliverResult(D data) {
        if (isReset()) {
            // An async query came in while the loader is stopped
            return;
        }

        this.data = data;

        super.deliverResult(data);
    }


    @Override
    protected void onStartLoading() {
        if (data != null) {
            deliverResult(data);
        }

        if (takeContentChanged() || data == null) {
            forceLoad();
        }
    }

    @Override
    protected void onStopLoading() {
         // Attempt to cancel the current load task if possible.
        cancelLoad();
    }

    @Override
    protected void onReset() {
        super.onReset();

        // Ensure the loader is stopped
        onStopLoading();

        data = null;
    }
}
like image 65
Catalin Morosan Avatar answered Nov 02 '22 22:11

Catalin Morosan