java

您所在的位置:网站首页 getintent()有什么用 java

java

2024-07-16 23:01| 来源: 网络整理| 查看: 265

我有这段代码可以检查从我的应用程序的许多地方调用的 Activity 的 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);

真的,这里的任何方法都是可以接受的。选择一个对你有意义的事情,然后照着做。

关于java - 如何判断 Android 中是否存在 Intent extras?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13408419/



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3