Sometimes don't get onCreateLoader callback after calling initLoader

casimps1 picture casimps1 · Oct 18, 2011 · Viewed 7.8k times · Source

I have an activity that calls initLoader when it is created in order to load the data that the activity will display. Normally, this works fine. I have breakpoints set to see the order that everything happens. First I call initLoader, then I get the OnCreateLoader callback, then the OnLoadFinished callback, then everything is great.

However, I noticed that if I changed the orientation on my Android that I don't get the OnCreateLoader callback or the OnLoadFinished callback, resulting in no data displayed on the page. I still get my breakpoint on the initLoader call so I know that is happening, but I don't get an error and I can't find any documentation explaining why I wouldn't get a callback after calling initLoader.

Interestingly, I do get the callbacks if I return to the original orientation.

So, to summarize:

I start the activity in portrait orientation

  • I call initLoader
  • I get onCreateLoader and onLoadFinished callbacks

I then change to landscape

  • I call initLoader
  • no onCreateLoader or onLoadFinished callbacks

I change back to portrait

  • I call initLoader
  • I get onCreateLoader and onLoadFinished callbacks

Similarly, if I start the activity in landscape mode I get the callbacks. Then, if I switch to portrait, I don't. Then, if I switch back to landscape I get the callbacks again.

Does anyone have any idea what's going on?

Answer

jsmith picture jsmith · Nov 13, 2012

We've seen this same problem with Fragments in a ViewPager. It appears that the loaders are not properly activated again when a fragment is resumed. In fact, when the fragment is paused, our CursorLoader no longer gets ContentObserver callbacks as I would expect.

Our workaround has been to call restartLoader() which dumps the previous contents and reloads the data. This would have the same net affect as destroyLoader(); initLoader(), but it will be more efficient.