mianlaoshu
mianlaoshu

Reputation: 2582

Android application instance is cleared as null

I saved the Application instance as the static member in my Application, like below:

public class MyApplication extends MultiDexApplication {
    private static MyApplication sInstance;

    public void onCreate() {
        super.onCreate();
        sInstance = this;
        // other code
    }

    public static MyApplication get(){
        return sInstance;
    }
}

There is no set-like method in the MyApplication. So in my assumption, the sInstance should never be null where refered in the entire lifecycle of my app.

But in fact, I found a few NPE crashes caused by MyApplication.get() returning null, even it's called in the Activity onCreate/onDestroy.

I just don't understand why the sInstance is null. In my opinion, the application should be initilized before any other Activities when the process is launched. Does anyone know why?

Upvotes: 0

Views: 849

Answers (2)

Yves Delerm
Yves Delerm

Reputation: 1035

I have had a similar crash in my application logs, NPE crash on MyApplication.get() method. After long search, I discovered that this crash was caused by the app restoration from the cloud.

If you have android:allowBackup="true" if the application tag of your manifest file, it could be your case too.

When the app data is restored, the app is killed in an unusual way, and when the user starts the app again, MyApplication.onCreate method is never called.

Easy steps to reproduce this crash are :

1) enable the app data saving on cloud in the device settings.

2) force a cloud saving for the app from the command line by launching : adb shell bmgr backupnow my.package.name

3) launch the app

4) trigger cloud backup from the command line : adb shell bmgr restore my.package.name => the app will stop

5) launch the app again by clicking on its icon => the app crashes with a NPE

You can trigger the crash again by repeating steps 4 and 5.

There are differents ways to solve this crash :

  • disable backup : android:allowBackup="false"

  • get an app instance from the activity getApplication method (caution : I am not sure it will be a MyApplication object)

  • force killing and restarting the app when application instance is null

  • use a custom BackupAgent to avoid the issue

Upvotes: 1

Vishal Pawar
Vishal Pawar

Reputation: 4340

Do you have multidex enabled in your gradle file like this

   android {
        defaultConfig {
            ...
            minSdkVersion 15 
            targetSdkVersion 28
            multiDexEnabled true
     }
   }

Upvotes: 0

Related Questions