getIntent()返回null并导致NPE

时间:2013-09-20 17:23:11

标签: android android-intent android-activity

ActivityCat有一个带有相应方法的按钮

myButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, ActivityDog.class);
                intent.putExtra(ActivityDog.MY_TIMESTAMP, timestamp);
                startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
            }
        });

但是当单击该按钮时,我收到以下错误,这显然意味着getIntent()返回null。有谁知道如何解决这个问题?

FATAL EXCEPTION: main
  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.myapp/com.mycompany.myapp.activity.ActivityDog}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2247)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2297)
    at android.app.ActivityThread.access$700(ActivityThread.java:152)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5328)
    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:1102)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
    at dalvik.system.NativeStart.main(Native Method)
  Caused by: java.lang.NullPointerException
    at com.mycompany.myapp.activity.ActivityDog.onCreate(ActivityDog.java:152)
    at android.app.Activity.performCreate(Activity.java:5250)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
    ... 11 more

第151和152行是

Intent intent = getIntent();
Long myTimestamp = intent.getLongExtra(MY_TIMESTAMP, (Long) null);

2 个答案:

答案 0 :(得分:2)

更改

Long myTimestamp = intent.getLongExtra(MY_TIMESTAMP, (Long) null);

Long myTimestamp = intent.getLongExtra(MY_TIMESTAMP, -1);

...如果没有找到多余的额外值,则假设-1是您的默认值。您不能拥有null长值。

答案 1 :(得分:0)

我发现了以下修复但我不喜欢它。它揭示了这个问题。但是有更优雅的解决方案吗?

Long myTimestamp = intent.getLongExtra(MY_TIMESTAMP, -1);
myTimestamp = -1 == myTimestamp ? null : myTimestamp;