Button的onRestoreInstanceState(Bundle)中的java.lang.NullPointerException

时间:2013-06-12 06:59:59

标签: android nullpointerexception

我在Activity的onCreate()方法中创建了一个按钮,并尝试更改按钮的状态 onRestoreInstanceState(Bundle)方法。 我在这种方法中只有一行。

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
savedButton.setSelected(true);
super.onRestoreInstanceState(savedInstanceState);
}

但是有些时候java.lang.NullPointerException异常发生在我更改按钮状态的这一行,有时候它工作正常。

我哪里错了?

日志:

java.lang.NullPointerException
    at com.test.MainActivity.onRestoreInstanceState(MainActivity.java:35)
    at android.app.Activity.performRestoreInstanceState(Activity.java:934)
    at android.app.Instrumentation.callActivityOnRestoreInstanceState(Instrumentation.java:1145)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2088)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
    at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3576)
    at android.app.ActivityThread.access$800(ActivityThread.java:143)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4950)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

把这个

if(savedInstanceState != null) {
    savedButton.setSelected(true);
}
在您定义按钮后,

进入onCreate(Bundle savedInstanceState)