On Google Play I receive a NullPointerException
when trying to access a static Application
instance. It appears on different Android OS versions: Android 9, 8, and 6.
From code it seems that Application.onCreate()
hasn't been called or is called after Activity.onCreate()
.
I saw similar questions but without any useful response:
Application onCreate called(not called) after Activity onCreate
Android Activity::onCreate called before Application.onCreate
As a side solution, I'm going to create a separate singleton class depending on Context
and get it with the Context
. But, I'm not sure how it will work with Dagger.
My questions are:
- Is it an Android bug?
- Am I doing something wrong?
- How have other developers solved it?
public class App extends androidx.multidex.MultiDexApplication implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 { private static App instance; public static App getInstance() { return instance; } @Override public void onCreate() { super.onCreate(); instance = this; // init singletone } private Singletone singletone; public Singletone getSingletone() {}}public class MainActivity extends androidx.appcompat.app.AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // On Google Play it produces NullPointerException Singletone singletone = App.getInstance().getSingletone(); }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.package.name"><application android:name=".app.App" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme.NoActionBar" android:largeHeap="true"><activity android:name=".activities.MainActivity" android:screenOrientation="portrait" android:launchMode="singleTask" android:windowSoftInputMode="adjustPan" android:theme="@style/AppTheme.NoActionBar.Launcher"></activity></application></manifest>