Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attempted to access a cursor after it has been closed

Tags:

android

I'm using the following code to delete an image. It works the first time, but when I try to capture an image and delete it I get a StaleDataException:

08-07 14:57:24.156: E/AndroidRuntime(789): java.lang.RuntimeException: Unable to               
       resume activity {com.example.cap_im/com.example.cap_im.MainActivity}:  
       android.database.StaleDataException: Attempted to access a cursor after it has been closed.

public void deleteImageFromGallery(String captureimageid) {
    Uri u = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

    getContentResolver().delete(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            BaseColumns._ID + "=?", new String[] { captureimageid });

    String[] projection = { MediaStore.Images.ImageColumns.SIZE,
            MediaStore.Images.ImageColumns.DISPLAY_NAME,
            MediaStore.Images.ImageColumns.DATA, BaseColumns._ID, };

    Log.i("InfoLog", "on activityresult Uri u " + u.toString());

    try {
        if (u != null) {
            cursor = managedQuery(u, projection, null, null, null);
        }
        if ((cursor != null) && (cursor.moveToLast())) {

            int i = getContentResolver().delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    BaseColumns._ID + "=" + cursor.getString(3),   null);
            Log.v(TAG, "Number of column deleted : " + i);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}
like image 249
Dilshi Avatar asked Aug 07 '13 15:08

Dilshi


2 Answers

Function, managedQuery() is deprecated.

Please use getContentResolver().query().

The parameters is the same.

like image 70
Tom Lin Avatar answered Sep 30 '22 18:09

Tom Lin


In your finally block, you close the cursor, but you do not set it to null. Thus, the next time your method is called, cursor.getString(3) fails, since the cursor has been closed.

Workaround: Set cursor to null in your finally block.

Correct solution: Don't use an instance variable for your cursor, use a local variable in your method instead.

like image 33
Heinzi Avatar answered Sep 30 '22 17:09

Heinzi