Singleton object becomes null after app is resumed

You’re getting crashes because you initialize those variables in one Activity, and expect it to be set always, in the other Activity.

But Android doesn’t work like that, you can easily end up crashing because after low memory condition happens, only the current Activity gets recreated at first, previous Activity is recreated on back navigation, and all static variables are nulled out (because the process is technically restarted).

Try it out:

  • put your application in background with HOME button

  • click the TERMINATE button on Logcat tab

terminate button

  • then re-launch the app from the launcher.

You’ll experience this phenomenon.

In Android Studio 4.0, after you use Run from Android Studio instead of starting the app from launcher, the Terminate button SOMETIMES works a bit differently and MIGHT force-stop your app making it forget your task state on your attempt. In that case, just try again, launching the app from launcher. It will work on your second try.

You can also trigger the “Terminate Application” behavior from the terminal, as per https://codelabs.developers.google.com/codelabs/android-lifecycles/#6, it looks like this:

$ adb shell am kill your.app.package.name

Solution: check for nulls and re-initialize things in a base activity (or in LiveData.onActive), or use onSaveInstanceState.

Leave a Comment