I tried to use a singleton like this. init()
must be called with a context. I called it in the onCreate()
of the MainActivity. But there was a problematic situation.
Let's say there is another activity, Activity2
. In the MainAcvitiy, I started Activity2. Then, I pressed the home button and used other apps. Now, I came back to my application, and it crashed. I read the log. It seemed that my app had restarted, but MainAcivity was skipped and it started directly from Activity2
. This was not something I expected. Since the singleton class was only initialized in the MainActivity, if the app starts from Activity2
, it is not initialized.
I could put the initialization code to the onCreate()
of all activities, but that seems to be a bad thing. I think I could subclassing Application
and do the initialization there. But is that the right place? The documentation says there normally is no need to subclass Application.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.loser, PID: 32117
java.lang.RuntimeException: Unable to resume activity {com.loser/com.loser.Activity2}: java.lang.RuntimeException: Call init() first.
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3454)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3494)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2757)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: java.lang.RuntimeException: Call init() first.
at com.loser.MySingleton$Companion.getInstance(MySingleton.kt:44)
at com.loser.Activity2.onResume(Activity2.kt:93)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1270)
at android.app.Activity.performResume(Activity.java:6788)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3431)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3494)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2757)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1496)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)