简体   繁体   中英

Bitmap from gallery cause crash - Android

I'm using a code to get Bitmap from gallery and use it for my purposes. this is the code:

protected void onActivityResult(int requestCode, int resultCode,Intent data) {                  
             if (resultCode == RESULT_OK) {
             Uri targetUri = data.getData();
             Bitmap bitmap = null;
             bitmap = BitmapFactory.decodeFile(getRealPathFromURI(targetUri));
                 //bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
            addMarker(bitmap);
            }
}

public String getRealPathFromURI(Uri contentUri) {
    // can post image
    String [] proj={MediaStore.Images.Media.DATA};
    Cursor cursor = managedQuery( contentUri,
    proj, // Which columns to return
    null, // WHERE clause; which rows to return (all rows)
    null, // WHERE clause selection arguments (none)
    null); // Order-by clause (ascending by name)
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
    }

for some reason the app crashing when doing it. the problem is not with the addMarker method, cause it's working fine with other bitmaps tested with. only with bitmaps from gallery it won't work and crush.

That's the error i get:

09-29 21:28:35.960: E/AndroidRuntime(4746): 
java.lang.RuntimeException: Failure delivering result ResultInfo
{who=null, request=1, result=-1, data=Intent 
{ dat=content://media/external/images/media/3 }} to activity
{com.sit.augmented_reality/com.sit.augmented_reality.activity.Demo}: 
java.lang.NullPointerException

Lot's of problems with that -- and a stack trace is required to answer the question properly.

However, the obvious problems are:

  1. (Most likely) The cursor you are using inside getRealPathFromURI is not closed. You need to close it before returning from the method. Save the value of cursor.getString() then close the cursor and return the saved value.

  2. (Less Likely) Bitmap loading/Out of Memory exception. You need to properly clean the Bitmaps you load. Android does a very bad job of managing Bitmaps. Having spent 2 years fighting the OS on this issue, I am now under the assumption that the underlying code to manage them is broken. There are countless examples for how to do this on StackOverflow and in the Android manuals...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM