android 4.0 以上平台选择图片报错Attempted to access a cursor after it has been closed.

android.database.StaleDataException: Attempted to access a cursor after it has been closed.
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1173)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.

选择图片后 onActivityResult中的代码如下:

 Uri uri = data.getData();
                if (uri != null)
                {
                    mFilePath = new URIUtils().getPathFromUri(uri);
                }

解决办法如注释中的所示。 4.0以上平台会自动关闭cursor

protected String getPath(Uri uri)
    {
        String filePath = "";

        String[] projection = {MediaColumns.DATA };
        Cursor cursor = managedQuery(uri,
            projection,
            null,
            null,
            null);

        if (cursor != null)
        {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            cursor.moveToFirst();
            filePath = cursor.getString(columnIndex);
            try
            {
                //4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
                if(Integer.parseInt(Build.VERSION.SDK) < 14)
                {
                    cursor.close();
                }
            }catch(Exception e)
            {
                Log.error(TAG, "error:" + e);
            }
        }

        return filePath;
    }


你可能感兴趣的:(exception,android,String,null,Access,平台)