简体   繁体   English

在Activity.onCreate()中,为什么Intent.getExtras()有时会返回null?

[英]In Activity.onCreate(), why does Intent.getExtras() sometimes return null?

This was probably a false alarm, see my own answer . 这可能是一个误报,请参阅我自己的答案 Original question below: 原始问题如下:

An activity has a button that takes the user to another activity. 活动有一个按钮,可以将用户带到另一个活动。 To launch the new activity, we populate our Intent with extras, and onCreate(), the new activity reads from those extras via Intent.getExtras(). 要启动新活动,我们使用extras填充我们的Intent,而onCreate(),新活动通过Intent.getExtras()从这些额外内容中读取。 We assumed the returned bundle would be non-null, but as customer crash reports discovered, getExtras() sometimes returns null. 我们假设返回的包是非空的,但是当发现客户崩溃报告时,getExtras()有时会返回null。

Null-guarding the extras, as this answer shows , is perfectly fine, but if you populate the intent's extras, then why would it ever return null later? 正如这个答案所示 ,无法保护额外内容是完全正常的,但是如果你填充了intent的附加内容,那么为什么它会在以后返回null呢? Is there a better place (like onResume()) to read the extras? 是否有更好的地方(如onResume())来阅读额外内容?

EDIT: It may be because we are not following the name convention required for the keys: 编辑:可能是因为我们没有遵循密钥所需的名称约定:

The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll". 名称必须包含包前缀,例如app com.android.contacts将使用“com.android.contacts.ShowAll”之类的名称。

This is from the Intent.putExtras javadoc . 这是来自Intent.putExtras的javadoc What happens if you don't follow this name convention; 如果您不遵循此名称惯例会发生什么; is the behavior even defined? 是甚至定义的行为?

Here's the relevant code: 这是相关的代码:

class FromActivity extends Activity {

    ImageButton button;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.from_view);

        button = (ImageButton)findViewById(R.id.button);
        button.setVisibility(View.VISIBLE);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(FromActivity.this, ToActivity.class);
                i.putExtra(ToActivity.SERVER_PARAM, ...);
                i.putExtra(ToActivity.UUID_PARAM, ...);
                i.putExtra(ToActivity.TEMPLATE_PARAM, ...);
                startActivityForResult(i, 0); 
                overrideTransition(R.anim.slide_left_in, R.anim.slide_left_out);
            }
        });
    }

}

class ToActivity extends Activity {

    public static final String SERVER_PARAM = "server";
    public static final String UUID_PARAM = "uuid";
    public static final String TEMPLATE_PARAM = "template";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            finish();
            return;
        }

        // do stuff with extras
    }
}

Here is a sample stack trace of this problem: 以下是此问题的示例堆栈跟踪:

java.lang.RuntimeException: Unable to start activity ComponentInfo{ToActivity}: java.lang.NullPointerException
    at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
    at  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
    at  android.app.ActivityThread.access$600(ActivityThread.java:151)
    at  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
    at  android.os.Handler.dispatchMessage(Handler.java:99)
    at  android.os.Looper.loop(Looper.java:155)
    at  android.app.ActivityThread.main(ActivityThread.java:5493)
    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:1028)
    at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
    at  dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
    at  ToActivity.onCreate(SourceFile:49)
    at  android.app.Activity.performCreate(Activity.java:5066)
    at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
    at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
     ... 11 more
     java.lang.NullPointerException
    at  ToActivity.onCreate(SourceFile:49)
    at  android.app.Activity.performCreate(Activity.java:5066)
    at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
    at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
    at  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
    at  android.app.ActivityThread.access$600(ActivityThread.java:151)
    at  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
    at  android.os.Handler.dispatchMessage(Handler.java:99)
    at  android.os.Looper.loop(Looper.java:155)
    at  android.app.ActivityThread.main(ActivityThread.java:5493)
    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:1028)
    at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795)
    at  dalvik.system.NativeStart.main(Native Method)

You can get it like this: 你可以这样得到它:

getIntent().getStringExtra(key);

Or: 要么:

getIntent().getExtras().getString(key)

And set it like this in "FromActivity": 并在“FromActivity”中将其设置为:

Bundle extras = new Bundle();
extras.putString(key, value);
intent.putExtras(extras);
//And start your activity...

Or: 要么:

intent.putExtra(key, string);
//And start your activity...

Either way should work, Hope this helps... 无论哪种方式都应该工作,希望这有助于......

Regards! 问候!

This was probably a false alarm; 这可能是一个误报; it's more likely due to our own instance variable being null: 它更可能是由于我们自己的实例变量为null:

class ToActivity extends Activity {

    public static final String SERVER_PARAM = "server";
    public static final String UUID_PARAM = "uuid";
    public static final String TEMPLATE_PARAM = "template";

    private State state;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        state = initializeState();
        // MISSING NULL CHECK HERE!

        Bundle extras = getIntent().getExtras();
        if (extras == null) {
            finish();
            return;
        }

        // do stuff with state and extras
    }
}

从理论上讲,开始你的活动的意图可以来自任何地方,例如另一个程序

You got a null pointer error, did you miss some initialization? 你有一个空指针错误,你错过了一些初始化? And can you tell us which line of your code has this error. 你能告诉我们你的代码哪一行有这个错误。 BTW, if you have many activities to handle, set a flag for your intent is a good idea. 顺便说一句,如果你有很多活动要处理,为你的意图设置一个标志是个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Intent 中的 getExtras() 有时是 null - getExtras() in Intent is sometimes null Intent.getExtras无法正常工作 - Intent.getExtras not working Android:intent.getExtras()。getSerializable(Constants.codiceMainActivity)为null - Android: intent.getExtras().getSerializable(Constants.codiceMainActivity) is null 在Activity.onCreate()上具有Robolectric的NullPointerExcepcion - NullPointerExcepcion with Robolectric on Activity.onCreate() ``intent.getExtras()。getString''应用在重新打开时崩溃 - ''intent.getExtras().getString'' app crashes when reopen (活动(上下文))。getIntent()。getExtras()返回null - (Activity(context)).getIntent().getExtras() return null App在Activity.onCreate()Java android之前发生异常崩溃 - App crashes with exception before Activity.onCreate() Java android 为什么 intent.resolveActivity(getPackageManager()) 返回 null 即使有 Activity 来处理它? - Why does intent.resolveActivity(getPackageManager()) return null even though there is Activity to handle it? 将参数从Activity.onCreate传递到其他方法 - Passing parameters from Activity.onCreate into other methods 为什么 Cassandra 查询有时返回一行,有时返回 null? - Why does a Cassandra query sometimes return one row and sometimes null?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM