如果定义了SaveOnInstanceState,则无法启动Activity

时间:2013-05-30 09:51:35

标签: android

我有一个MainActivity,其中TabHost个标签之一是CardHolderActivity,其中还包含一个带有两个标签的TabHost(它们也是Activities )。一切顺利,直到我设置了最新的一个 - MyCardsActivity - SaveOnInstanceState,我将我的数据列表放到outState捆绑包中。我正在启动很多其他应用程序,所以我的应用程序正在被杀死。从最近打开的应用程序列表中再次启动它后,我得到NullPointerException,这是日志:

05-30 12:35:06.032: I/CrashLogger(28147): java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.activities.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.activities.CardsHolderActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.activities.MyCardsActivity}: java.lang.NullPointerException
05-30 12:35:06.032: I/CrashLogger(28147): --------- Stack trace ---------
05-30 12:35:06.032: I/CrashLogger(28147):     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-30 12:35:06.032: I/CrashLogger(28147):     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-30 12:35:06.032: I/CrashLogger(28147):     android.app.ActivityThread.access$600(ActivityThread.java:141)
05-30 12:35:06.032: I/CrashLogger(28147):     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-30 12:35:06.032: I/CrashLogger(28147):     android.os.Handler.dispatchMessage(Handler.java:99)
05-30 12:35:06.032: I/CrashLogger(28147):     android.os.Looper.loop(Looper.java:137)
05-30 12:35:06.032: I/CrashLogger(28147):     android.app.ActivityThread.main(ActivityThread.java:5041)
05-30 12:35:06.032: I/CrashLogger(28147):     java.lang.reflect.Method.invokeNative(Native Method)
05-30 12:35:06.032: I/CrashLogger(28147):     java.lang.reflect.Method.invoke(Method.java:511)
05-30 12:35:06.032: I/CrashLogger(28147):     com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-30 12:35:06.032: I/CrashLogger(28147):     com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-30 12:35:06.032: I/CrashLogger(28147):     dalvik.system.NativeStart.main(Native Method)

以下是我拥有此代码的代码:

@Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (cards != null)
            outState.putSerializable(EXTRA_MY_CARDS, cards);
    }

cardsstatic类型的TreeSet<Card>变量,Card类实现Serializable

你们能告诉我为什么会这样吗? 此外,我很惊讶在恢复已杀死状态的应用程序后发生这种情况,onSaveInstanceState()上根本没有任何问题。而且我也没有检索日期,也没有检索onRestoreInstanceState()onCreate()

1 个答案:

答案 0 :(得分:0)

如果卡片是static,为什么需要在onSavedInstanceState中写一下?作为静态,它将绑定到Class对象,而不是Activity实例。

但是在活动中使用静态时要非常小心,因为这会导致内存泄漏。