Context.managedQuery()和context.getContentResolver()获取Cursor关闭注意事项
在获取图片缩略图时,获取游标并进行相关的操作。
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, THUMBNAIL_STORE_IMAGE, MediaStore.Images.Thumbnails.IMAGE_ID + " = ?", new String[]{id + ""}, null);
出现如下异常:
07-06 09:40:14.945 26649-26671/com.xxx.xxx E/ContentResolver: Cursor leak detected, query params: uri=content://media/external/images/thumbnails, projection=[Ljava.lang.String;@4214bca8, selection=image_id = ?, selectionArgs=[Ljava.lang.String;@421d05f8, sortOrder=null 07-06 09:40:14.945 26649-26671/com.xxx.xxx E/AndroidRuntime: FATAL EXCEPTION: Thread-1075 java.lang.IllegalStateException: Process 26649 exceeded cursor quota 100, will kill it at android.os.Parcel.readException(Parcel.java:1433) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:140) at android.content.ContentProviderProxy.query(ContentProviderNative.java:366) at android.content.ContentResolver.query(ContentResolver.java:411) at android.content.ContentResolver.query(ContentResolver.java:354) at com.xxx.xxx.utils.localalbum.common.LocalImageHelper.getThumbnail(LocalImageHelper.java:179) at com.xxx.xxx.utils.localalbum.common.LocalImageHelper.initImage(LocalImageHelper.java:139) at com.xxx.xxx.utils.localalbum.common.LocalImageHelper$1.run(LocalImageHelper.java:92) at java.lang.Thread.run(Thread.java:856)
这是由于游标没有关闭导致的问题。在finnally里面对cursor进行关闭即可。
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, THUMBNAIL_STORE_IMAGE, MediaStore.Images.Thumbnails.IMAGE_ID + " = ?", new String[]{id + ""}, null); try{ ... }finally { if(null != cursor){ cursor.close(); } }
然而,如果使用Context.managedQuery(),如果在android4.0以上,如果使用了Cursor.close()方法;则会报如下异常:
E/AndroidRuntime(31184): Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
在android 4.0及其以上的版本中,Cursor会自动关闭,不需要用户自己关闭。
解决办法:
if(VERSION.SDK_INT < 14) { cursor.close(); }
扫描公众号,关注更多信息
---------------------------------------------------------------------------------我是分割线--------------------------------------------------------------------------to be a better me, talk is cheap show me the code
版权所有,转载请注明原文链接。
文中有不妥或者错误的地方还望指出,以免误人子弟。如果觉得本文对你有所帮助不妨【推荐】一下!如果你有更好的建议,可以给我留言讨论,共同进步!
再次感谢您耐心的读完本篇文章。
----------------------------------------------------------------------------------------------------------------------------------------------------------------------