正如其他人所说,两者
getIntent()和都
getExtras()可能返回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. }}实际上,您实际上不需要调用
containsKey("isNewItem")as,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);实际上,这里的任何方法都是可以接受的。选择一个对您有意义的方式,然后按照这种方式进行。



