Jon O
Jon O

Reputation: 6591

Android gallery "share via" and Intent.EXTRA_STREAM

I have some code in my app that works well for opening the gallery (from within my app), selecting a photo, and uploading it.

I have made a fair attempt at integrating handling for intents with EXTRA_STREAMs attached, such as those generated by the "share" button in the gallery.

This works on my Droid X and it works on the emulator.

Today, I got an error report from a user; the cursor I used to pull the photo out of the MediaStore returned null when I asked it to return me the resource referred to in the EXTRA_STREAM parameter. The code had already passed through the point where it had verified that the Intent had an EXTRA_STREAM attached, and the user told me that they were using the "share" option from the gallery.

Their device was:

OS version: 2.3.3(10 / GRI40) Device: HTC PG86100

What gives?

Why would the HTC gallery send me an Intent with an EXTRA_STREAM that I can't access?

Are there any other reasons that a cursor would return null?

String[] filePathColumn = {MediaColumns.DATA};

Uri selectedImageUri;

//Selected image returned from another activity
if(fromData){
    selectedImageUri = imageReturnedIntent.getData();
} else {
    //Selected image returned from SEND intent

    // This is the case that I'm having a problem with.
    // fromData is set in the code that calls this; 
    // false if we've been called from an Intent that has an
    // EXTRA_STREAM
    selectedImageUri = (Uri)getIntent().getExtras().get(Intent.EXTRA_STREAM);
}

Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();  // <-- NPE on this line

Upvotes: 1

Views: 2852

Answers (1)

Jon O
Jon O

Reputation: 6591

It turns out that many apps will send EXTRA_STREAMs with the image/* mime type, but not all of them use the gallery's content provider.

The ones that were generating a null pointer exception (as above) were cases in which I was trying to read from the content provider when I was given a file:// EXTRA_STREAM.

The code that works is as follows:

String filePath;
String scheme = selectedImageUri.getScheme(); 

if(scheme.equals("content")){
    Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
    cursor.moveToFirst(); // <--no more NPE

    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

    filePath = cursor.getString(columnIndex);

    cursor.close();

} else if(scheme.equals("file")){
    filePath = selectedImageUri.getPath();
    Log.d(App.TAG,"Loading file " + filePath);
} else {
    Log.d(App.TAG,"Failed to load URI " + selectedImageUri.toString());
    return false;
}

Upvotes: 3

Related Questions