Can your fragments handle low memory recreates?

Brent Kelly
In The Hudl
Published in
2 min readMar 15, 2018

Did you know that the Android OS can destroy your activities and fragments when it deems fit, usually when device memory is running low? Is your code equipped to handle the scenario where an activity containing a fragment gets destroyed and recreated from saved instance state?

The system may also destroy the process containing your activity to recover memory if the activity is in the Stopped state and hasn’t been used in a long time, or if the foreground activity requires more resources.

(potential) Problem

The problem I see a lot when fragments are initialised is the use of setter methods to set fields (member variables) and how they are favoured over passing parameters through a bundle because lets face it, its easier.

The above is fine if you remember to save your state, but if you don’t it can lead to things like NullPointerExceptions and unexpected behaviour, if (and when) the destroy/recreate scenario occurs.

Solution 1 — Pass data through a Bundle

I like this option because you don’t have to worry about saving state during destroy, you just get the data back for free because you passed it through the fragments’ arguments bundle.

Solution 2 — Make use of onSaveInstanceState

If you still want (or need) to go down the setter route then you will probably need to save your state during a destroy so that you can recover during the recreate stage.

Solution 3 — Null checks (i.e. the bare minimum)

If you’re setting a field in a fragment through a setter method or something other than the arguments bundle you can’t assume it will always be present. As noted above, the Android system can claw memory back by destroying pieces of your app and recreating them with saved state, and when this happens your fields are going to be null.

I’d recommend you always assume the worst and treat your fragment fields as nullable (or just use Kotlin’s amazing null safety features!!).

Testing

Thankfully this scenario is really easy to test:

  1. On your device go to Settings > Developer options and enable the ‘Don’t keep activities’ option.
  2. Open your app and navigate to the place you want to test
  3. Press the home button to minimise your app (this will destroy your activity and fragments)
  4. Press the overview button and reopen your app
  5. See what happens (probably a crash or an empty looking view)

In conclusion, you probably already knew about the low memory destroy scenario, but I’m betting you’ve never (or hardly ever) tested that your app can cope with it!

Disclaimer: Although I’ve provided some solutions, it isn’t a definitive list and there are other ways to recover from this scenario. The important thing is that you are aware of it and that your App can recover gracefully and seamlessly.

--

--