【发布时间】:2016-08-09 19:39:43
【问题描述】:
我想在另一种方法中使用我在 onCreate() 中获得的数据。我知道这是基本的 Java,但我无法让这个特定的东西工作。 场景:用户通过他的图库将图像共享到我的应用程序。我通过意图接收 uri,并想举杯展示 uri。到目前为止,一切都很好。这是我得到的:
@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返回空值。意图中可能没有名为imageUri的键。您可以在获取之前使用hasExtras()进行检查以防止NPE。 -
我也是这么想的,但是如何检查我需要的正确的额外密钥?
标签: java android android-studio android-intent