【问题标题】:Pass info between methods在方法之间传递信息
【发布时间】: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


【解决方案1】:

intent.getParcelableExtra 返回空值。意图中可能没有名为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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2018-01-25
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多