如何判断是否在Android中存在的意图演员? [英] How do I tell if Intent extras exist in Android?

查看:125
本文介绍了如何判断是否在Android中存在的意图演员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code,检查一个额外的一项活动的意图值,从许多地方调用我的应用程序:

I have this code that checks for a value of an extra in an Intent on an Activity that is called from many places in my app:

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

如果isNewItem没有设置,将我的code崩溃?有没有办法告诉如果它被设置与否之前,我打电话吗?

If isNewItem isn't set, will my code crash? Is there any way to tell if it's been set or not before I call it?

什么是正确的方式来处理呢?

What is the proper way to handle this?

推荐答案

正如其他人所说,无论 getIntent() getExtras()可能返回null。正因为如此,你不想链的通话在一起,否则你可能最终会调用 null.getBoolean(isNewItem); 这将抛出一个 NullPointerException异常,并导致应用程序崩溃。

As others have said, both getIntent() and getExtras() may return null. Because of this, you don't want to chain the calls together, otherwise you might end up calling null.getBoolean("isNewItem"); which will throw a NullPointerException and cause your application to crash.

下面就是我会做到这一点。我认为这是格式化的最好的方式是很容易被别人谁可能是读你的code理解。

Here's how I would accomplish this. I think it's formatted in the nicest way and is very easily understood by someone else who might be reading your code.

// 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.
    }
}

您实际上并不需要调用 hasExtra(isNewItem) getBoolean(isNewItem,FALSE)将返回false,如果额外的不存在。你可以凝结上面是这样的:

You don't actually need the call to hasExtra("isNewItem") as getBoolean("isNewItem", false) will return false if the extra does not exist. You could condense the above to something like this:

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

编辑:作为@Squonk指出的那样,你也可以使用意图的方法来直接访问你的临时演员。这可能是这样做的最彻底的方法:

As @Squonk pointed out, you can also use the Intent methods to access your extras directly. This is probably the cleanest way to do so:

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

真任何这里的方法是可接受的。选择一个对你有意义并且这样做的。

Really any of the methods here are acceptable. Pick one that makes sense to you and do it that way.

这篇关于如何判断是否在Android中存在的意图演员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆