java - 在方法之间传递信息

标签 java android android-studio android-intent

我想在另一种方法中使用我在 onCreate() 中获得的数据。我知道这是基本的 Java,但我无法让这个特定的东西发挥作用。 场景:用户通过他的图库将图像分享到我的应用程序。我通过 Intent 接收 uri,并想做一个显示 uri 的 toast 。到目前为止,一切都很好。这就是我得到的:

@Override
 protected void onCreate(Bundle savedInstanceState) {
 ...
    // Handle incoming shared image
    // Get intent, action and MIME type
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            handleWrongContent(intent); // Handle text being sent
        } else if (type.startsWith("image/")) {
            handleSendImage(intent); // Handle single image being sent
        }
    } else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
        if (type.startsWith("image/")) {
            handleWrongContent(intent); // Handle multiple images being sent
        }
    }
 ...
}

private void handleSendImage(Intent intent) {
    String str = intent.getParcelableExtra("imageUri").toString();
    Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}

如果我现在尝试这个,我会得到这个 NPE:

Attempt to invoke virtual method 'java.lang.String     
java.lang.Object.toString()' on a null object reference

感谢您的帮助!

最佳答案

intent.getParcelableExtra 返回 null。 Intent 中可能没有名为 imageUri 的键。您可以在获取之前使用 hasExtras() 进行检查以防止 NPE。

此外,尝试使用 Intent.EXTRA_STREAM 而不是 imageUri。检查Handle the Incoming ContentReceiving Simple Data from Other Apps 。引用它,尝试使用:

void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
        // Update UI to reflect image being shared
    }
}

关于java - 在方法之间传递信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859125/

相关文章:

java - 从 Java 中的列表数组填充字符串数组

java - 在 Android 中处理命令而不启动 MainActivity

android - 如何使用默认浏览器在谷歌上搜索字符串

android - 防止按钮根据 TextView 中的文本移动

android - 安装失败,并显示消息“未找到设备 '(device number)'”

java - 为什么我添加依赖项时android studio会给出错误?

java - 如何在redis中使用where条件更新json的多个值?

java - 使用 java 流从列表创建 map 列表

java - HTML WebView 上使用键盘时如何隐藏 ImageView

android - Android Studio 中的 Gradle 无法解析 JCenter 中的库