繁体   English   中英

如何判断Android中是否存在Intent附加功能?

[英]How do I tell if Intent extras exist in Android?

我有这个代码,检查从我的应用程序中的许多地方调用的活动上的Intent中的额外值:

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

如果未设置isNewItem,我的代码会崩溃吗? 在我打电话之前,有没有办法判断它是否已经设定?

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

正如其他人所说, 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")因为如果额外不存在,则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);

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

你可以这样做:

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

问候。

如果没有IntentgetIntent()将返回null ,所以使用...

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 :))

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM