栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何判断Android是否存在Intent Extras?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何判断Android是否存在Intent Extras?

正如其他人所说,两者

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

实际上,这里的任何方法都是可以接受的。选择一个对您有意义的方式,然后按照这种方式进行。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609846.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号