Question

I want to try Loaders. But when i call initLoader() like it's done in the documentation, the UI-Thread is getting blocked with the code from onCreateLoader. Isn't that the whole point of Loaders? Why is that, and what should i do to prevent the UI-Thread from beeing blocked here? I am using debugging in Android Studio on the Nexus 5.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_content_provider_test);
    getLoaderManager().initLoader(0, null, this);
}

@Override
public Loader onCreateLoader(int loaderID, Bundle args) {
    //Do nothing 100000000 times
    for(int i=0; i< 100000000; i++)
        ;
    return null;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    //nothing to display
}

@Override
public void onLoaderReset(Loader loader) {
    //nothing to reset
}
Was it helpful?

Solution

But when i call initLoader() like it's done in the documentation, the UI-Thread is getting blocked with the code from onCreateLoader.

As Luksprog notes, onCreateLoader() is called on the same thread that initLoader() is called on, and usually that is the main application thread. The job of onCreateLoader() to create the Loader, as you might have guessed by the name.

Isn't that the whole point of Loaders?

The point of a Loader is to load data. The point of an AsyncTaskLoader is to load data asynchronously. You are welcome to create some other Loader that does not inherit from AsyncTaskLoader, in which case doing the loading asynchronously is your job.

what should i do to prevent the UI-Thread from beeing blocked here?

Write a correct implementation of onCreateLoader(), one that creates a Loader instance and returns it, rather than looping 100000000 times and then returning null.

This is covered in the documentation on the Loader framework.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top