执行cursor.getcount()时崩溃(android)

n7taea2i  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(326)

这种情况并不总是发生,因此我无法正确理解发生了什么:我的应用程序拍摄并修改一张图片,然后将其保存在外部存储器中。如果我试图在应用程序中打开一个新保存的图片从一个文件管理器而不是从画廊,它崩溃时执行cursor.getcount(),在ddms我读到错误:“cursor not closed before finally”这是一段代码的问题所在,我可以张贴更多如果必要的,谢谢!ps此代码取自stackoverflow中的其他答案,因为您可以预期我不是Maven,所以请耐心等待我,谢谢pps保存后我无法立即在gallery中看到图像,当它们出现在gallery中时此错误消失。

public static int getOrientation(Context context, Uri photoUri) {
        /* it's on the external media. */
        Cursor cursor = context.getContentResolver().query(photoUri,
                new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null);

        if (cursor.getCount() != 1) { //HERE IS THE PROBLEM
            return -1;
        }

        cursor.moveToFirst();
        return cursor.getInt(0);
    }
cunj1qz1

cunj1qz11#

使用此语句而不是return语句。光标正在泄漏,因为您没有关闭它

try{

    if (cursor.getCount() != 1) { //HERE IS THE PROBLEM
        return -1;
    }

    int i = 0;
    i++;
    cursor.moveToFirst();
   return cursor.getInt(0);

}finally{
if(cursor != null)
   cursor.close();
}

编辑:
从文件管理器打开文件时,uri的格式为file:///sdcard/filename,但mediastore只能理解该格式的uricontent://media/audio/1. 这就是将游标设为null的原因。
一种方法是查询整个mediastore并获取mediastore.images.media.data列,并与从uri获取的路径进行比较

jc3wubiy

jc3wubiy2#

你可以用

if(cursor.moveToFirst()) 
{
    //Your code here
}

而不是关闭

cursor.getCount()

如果游标大小大于0,它将返回true,否则它将返回false……。所以您可以这样写。。。。。。。。。

if (!cursor.moveToFirst())
   return -1;

else 
   return 1;

相关问题