今天在开发选择图片时发现有时候会报错:
Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.
手机是android版本是4.2.1
网上查找了一下发现是由于android版本的问题,4.0以上会自动关闭游标,不需要手动关闭,故再进行手动关闭的时候就报出了以上异常
修改前的代码:
<span style="font-size:18px;"> String[] pojo = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(photoUri, pojo, null, null,null);
String picPath=null;
if(cursor != null )
{
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
cursor.close();
} </span>
<span style="font-size:18px;"> String[] pojo = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(photoUri, pojo, null, null,null);
String picPath=null;
if(cursor != null )
{
int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
cursor.moveToFirst();
picPath = cursor.getString(columnIndex);
try
{
//4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
if(Integer.parseInt(Build.VERSION.SDK) < 14)
{
//只有4.0以下才需要手动关闭
cursor.close();
}
}catch(Exception e)
{
CommonHelper.log(TAG+":addPhoto",e.getMessage());
}
}
</span>
这样上述问题就解决了,有时候版本不同确实会带来很多问题,开发过程中还是要小心为妙