正如其他人所说,Intent和getBoolean("isNewItem", false)都可能返回null。 因此,您不想将调用链接在一起,否则可能最终会调用null.getBoolean("isNewItem");,这将抛出NullPointerException,并导致您的应用程序崩溃。
这就是我要完成的方法。 我认为它以最好的方式格式化,并且可能被正在阅读您的代码的其他人轻易理解。
// 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.
}
}
您实际上不需要呼叫Intent,因为如果不存在多余的内容,则getBoolean("isNewItem", false)将返回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);
实际上,这里的任何方法都是可以接受的。 选择一个对您有意义的方式,然后按照这种方式进行。