无法恢复活动的错误错误

2023-09-05 11:17:44 作者:逗比惹人爱

我的活动包含此code,以获得SD卡上的所有图片:

My Activity contains this code to get all images on the SD card:

String[] projection = {MediaStore.Images.Media._ID,
                       MediaStore.Images.Media.DATA,
                       MediaStore.Images.ImageColumns.DATA};  
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                             projection, null, null,
                             MediaStore.Images.Media._ID); 
int count = cursor.getCount();
int image_path_index = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
int i;
for(i = 0; i < count; i++) {
    cursor.moveToPosition(i);
    String p = cursor.getString(image_path_index);
    fd.addToPhonePhoto(p);
}
cursor.close();

而活动中恢复的发生:

The occurred while the Activity was resuming:

03-14 14:06:48.380:E / AndroidRuntime(20793):java.lang.RuntimeException的:无法恢复活动{}:java.lang.RuntimeException的:无法恢复活动{}:android.database.StaleDataException :试图访问一个游标已经关闭后

03-14 14:06:48.380: E/AndroidRuntime(20793): java.lang.RuntimeException: Unable to resume activity {}: java.lang.RuntimeException: Unable to resume activity {}: android.database.StaleDataException: Attempted to access a cursor after it has been closed.

这仅发生在Android 4.0。如果在Android 2.x或3.x中,它工作正常。但是,如果我改变它选择在开发人员选项中的不保留活动选项的系统设置。 该错误不显示。

It only occurs on Android 4.0. If on Android 2.x or 3.x, it works normally. But if I change the system setting which selects the "don't keep Activities" option in "Developer options". The error does not show.

我想修改我的code,以避免该错误不改变系统设置。我应该怎么办呢?

I want to modify my code to avoid this error without changing the system setting. How should I do it?

推荐答案

我想这是因为 managedQuery 通话+您关闭游标。从的managedQuery()方法:

I think this is because of the managedQuery call + you closing the cursor. From the docs of the managedQuery() method:

警告:不要调用close()使用此方法得到的光标,   由于活动会替你在适当的时候。   但是,如果调用stopManagingCursor(光标)从一个游标   管理查询时,系统将不会自动关闭游标和,   在这种情况下,你必须调用close()。

Warning: Do not call close() on a cursor obtained using this method, because the activity will do that for you at the appropriate time. However, if you call stopManagingCursor(Cursor) on a cursor from a managed query, the system will not automatically close the cursor and, in that case, you must call close().

将光标为Android系统来管理,不叫 cursor.close();

Leave the cursor for the Android system to manage and don't call cursor.close();.

注: managedQuery 法德precated和应避免,实施CursorLoaders代替。关于 CursorLoaders 更多信息可以在developer.android.com.

Note: The managedQuery method is deprecated and it should be avoided, implement CursorLoaders instead. More info about CursorLoaders can be found at developer.android.com.