简体   繁体   中英

Crash when executing cursor.getCount() (Android)

this doesn't always happen so i can't understand properly what's going on: my application take and modify a picture, then save it in external storage. If i try to open in the application a new saved pictures FROM A FILE MANAGER AND NOT FROM GALLERY, it crashes when executing cursor.getCount(), in DDMS i read the error:"cursor not closed before finally" this is the piece of code where the problem is, i can post more if necessary, thank you! ps this code is taken from other answers here in stackoverflow, as you could expect i'm not an expert so please be patient with me, thanks pps i can't see immediatly images in gallery after saving it, when they appear in gallery this error desappear.

public static int getOrientation(Context context, Uri photoUri) {
        /* it's on the external media. */
        Cursor cursor = context.getContentResolver().query(photoUri,
                new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);


        if (cursor.getCount() != 1) { //HERE IS THE PROBLEM
            return -1;
        }

        cursor.moveToFirst();
        return cursor.getInt(0);
    }

You can use the

if(cursor.moveToFirst()) 
{
    //Your code here
}

instead off

cursor.getCount() 

it will return true if cursor size is greater then 0 else it will return false........so you can write like this.........

if (!cursor.moveToFirst())
   return -1;

else 
   return 1;

Use this instead of the return statement. The cursor is getting leaked since you are not closing it

try{

    if (cursor.getCount() != 1) { //HERE IS THE PROBLEM
        return -1;
    }

    int i = 0;
    i++;
    cursor.moveToFirst();
   return cursor.getInt(0);

}finally{
if(cursor != null)
   cursor.close();
}

Edit:
When you open a file from File manager, the uri will be of the form file:///sdcard/filename but the Mediastore can only understand uri of the format content://media/audio/1. This is the reason you are getting cursor as null.

one way is to query the whole Mediastore and get the MediaStore.Images.Media.DATA column and compare with the path that you get from uri

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