55

我有这段代码可以检查从我的应用程序中的许多地方调用的 Activity 的 Intent 中的额外值:

getIntent().getExtras().getBoolean("isNewItem")

如果 isNewItem 没有设置,我的代码会崩溃吗?在我调用它之前,有什么方法可以判断它是否已设置?

处理这个问题的正确方法是什么?

4

5 回答 5

118

正如其他人所说,两者都getIntent()可能getExtras()返回null。因此,您不想将调用链接在一起,否则您最终可能会调用null.getBoolean("isNewItem");这将引发 aNullPointerException并导致您的应用程序崩溃。

以下是我将如何完成此任务。我认为它的格式最好,并且可能正在阅读您的代码的其他人很容易理解。

// You can be pretty confident that the intent will not be null here.
Intent intent = getIntent();

// Get the extras (if there are any)
Bundle extras = intent.getExtras();
if (extras != null) {
    if (extras.containsKey("isNewItem")) {
        boolean isNew = extras.getBoolean("isNewItem", false);

        // TODO: Do something with the value of isNew.
    }
}

如果额外不存在,您实际上不需要调用containsKey("isNewItem")as将返回 false 。getBoolean("isNewItem", false)您可以将上述内容浓缩为以下内容:

Bundle extras = getIntent().getExtras();
if (extras != null) {
    boolean isNew = extras.getBoolean("isNewItem", false);
    if (isNew) {
        // Do something
    } else {
        // Do something else
    }
}

您还可以使用这些Intent方法直接访问您的附加功能。这可能是最干净的方法:

boolean isNew = getIntent().getBooleanExtra("isNewItem", false);

实际上这里的任何方法都是可以接受的。选择一个对你有意义的,然后这样做。

于 2012-11-16T00:39:29.853 回答
11

你可以这样做:

Intent intent = getIntent();
if(intent.hasExtra("isNewItem")) {
   intent.getExtras().getBoolean("isNewItem");
}
于 2016-11-10T09:47:53.723 回答
8

问题不在于getBoolean()getIntent().getExtras()

以这种方式测试:

if(getIntent() != null && getIntent().getExtras() != null)
  myBoolean = getIntent().getExtras().getBoolean("isNewItem");

顺便说一句,如果isNewItem不存在,它会返回 de default vaule false

问候。

于 2012-11-16T00:15:26.143 回答
1

getIntent()null如果没有那么用会返回Intent...

boolean isNewItem = false;
Intent i = getIntent();
if (i != null)
    isNewItem = i.getBooleanExtra("isNewItem", false);
于 2012-11-16T00:15:54.070 回答
0

除非您使用它,否则它不会崩溃!如果它存在,您不必获取它,但如果您出于某种原因尝试使用不存在的“额外”,您的系统将崩溃。

所以,尝试做类似的事情:

final Bundle bundle = getIntent().getExtras();

boolean myBool=false;

if(bundle != null) {
    myBool = bundle.getBoolean("isNewItem");
}

这样您就可以确保您的应用程序不会崩溃。(并确保你有一个有效的Intent:))

于 2012-11-16T00:17:04.117 回答