tbremer19 tbremer19 - 1 year ago 73
Android Question

Pass info between methods

I want to use data which I got in my onCreate() in another method. I know that this is basic Java but I can't get this specific thing to work.
The scenario: A user shares an image via his gallery to my app. I receive the uri via intent and want to make a toast showing the uri. So far so good. This is what I got:

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

If I try this out now, I get this NPE:

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

Thank you for your help!

Answer Source

intent.getParcelableExtra is returning null. There is no key called imageUri in intent probably. You can check using hasExtras() before getting it to prevent NPE.

Also instead of imageUri, try to use Intent.EXTRA_STREAM. Check Handle the Incoming Content at Receiving Simple Data from Other Apps. Quoting it, try to use:

void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
    if (imageUri != null) {
        // Update UI to reflect image being shared
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download