我有这段代码可以检查从我的应用程序中的许多地方调用的 Activity 的 Intent 中的额外值:
getIntent().getExtras().getBoolean("isNewItem")
如果 isNewItem 没有设置,我的代码会崩溃吗?在我调用它之前,有什么方法可以判断它是否已设置?
处理这个问题的正确方法是什么?
我有这段代码可以检查从我的应用程序中的许多地方调用的 Activity 的 Intent 中的额外值:
getIntent().getExtras().getBoolean("isNewItem")
如果 isNewItem 没有设置,我的代码会崩溃吗?在我调用它之前,有什么方法可以判断它是否已设置?
处理这个问题的正确方法是什么?
正如其他人所说,两者都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);
实际上这里的任何方法都是可以接受的。选择一个对你有意义的,然后这样做。
你可以这样做:
Intent intent = getIntent();
if(intent.hasExtra("isNewItem")) {
intent.getExtras().getBoolean("isNewItem");
}
问题不在于getBoolean()
但getIntent().getExtras()
以这种方式测试:
if(getIntent() != null && getIntent().getExtras() != null)
myBoolean = getIntent().getExtras().getBoolean("isNewItem");
顺便说一句,如果isNewItem
不存在,它会返回 de default vaule false
。
问候。
getIntent()
null
如果没有那么用会返回Intent
...
boolean isNewItem = false;
Intent i = getIntent();
if (i != null)
isNewItem = i.getBooleanExtra("isNewItem", false);
除非您使用它,否则它不会崩溃!如果它存在,您不必获取它,但如果您出于某种原因尝试使用不存在的“额外”,您的系统将崩溃。
所以,尝试做类似的事情:
final Bundle bundle = getIntent().getExtras();
boolean myBool=false;
if(bundle != null) {
myBool = bundle.getBoolean("isNewItem");
}
这样您就可以确保您的应用程序不会崩溃。(并确保你有一个有效的Intent
:))