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();
}
}
}
Function, managedQuery() is deprecated.
Please use getContentResolver().query().
The parameters is the same.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With