AlanSTACK
AlanSTACK

Reputation: 6065

LoaderManager's loaders surviving orientation change, but not activity destruction

I need to make network calls to a backend JSON API in order to make changes server side when a user updates their profile.

Unfortunately, these asynchronous tasks might get disrupted by Android's inherent lifecycle events. So I opted to use AsyncTaskLoader with getSupportLoaderManager

However, I have again run into another problem. Although the loaders contained inside LoaderManager survives orientation changes - they do not survive the destruction of an activity (which is strange because Bundle savedInstanceState does)

// everything is good so far
LoaderManager.initLoader -> orientation change -> LoaderManager.getLoader(...)      = <Some Loader>
outState.putString(...)  -> orientation change -> savedInstanceState.getString(...) = <Some String>

// I am having problems now...
LoaderManager.initLoader -> activity destroyed by OS -> LoaderManager.getLoader(...)      = null
outState.putString(...)  -> activity destroyed by OS -> savedInstanceState.getString(...) = <Some String>

How do I make it so that my LoaderManager (and more importantly the contained loaders) survives along side savedInstanceState

The following is a small Android app that illustrates the current issue. Please note that the issue is only prevalent when the developer option (DONT KEEP ACTIVITIES is enabled)

https://anonfile.com/kfTft8d1b0/Android_async_loader_04.rar

  1. First click the INIT loader button in the app
  2. Second click the overview button
  3. Third re-enter the app
  4. Fourth click the GET loader button in the app
  5. Observe the return value is NULL

enter image description here

Upvotes: 2

Views: 101

Answers (1)

dazza5000
dazza5000

Reputation: 7618

This is due to the android framework persisting a bundle during activity destruction, but not keeping other member variables.

onSaveInstanceState persists what you put in it and stores it on the device and then retrieves that bundle to give it to you in onCreate() if it exists.

Loader classes do not behave in this manner.

You will need to re-create the loader if the activity is destroyed.

This is the source code for loadermanager - it looks like we can enable debug logging to provide some additional insight:

http://grepcode.com/file/repo1.maven.org/maven2/com.google.android/support-v4/r7/android/support/v4/app/LoaderManager.java#LoaderManager.enableDebugLogging%28boolean%29

Upvotes: 1

Related Questions