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

来源:互联网 发布:淘宝上被骗了怎么投诉 编辑:程序博客网 时间:2024/05/20 03:46
[html] view plaincopy
  1. android.database.StaleDataException: Attempted to access a cursor after it has been closed.  
  2. at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2444)  
  3. at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2472)  
  4. at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1173)  
  5. at android.os.Handler.dispatchMessage(Handler.java:99)  
  6. at android.os.Looper.loop(Looper.java:137)  
  7. at android.app.ActivityThread.main(ActivityThread.java:4424)  
  8. at java.lang.reflect.Method.invokeNative(Native Method)  
  9. at java.lang.reflect.Method.invoke(Method.java:511)  
  10. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)  
  11. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)  
  12. at dalvik.system.NativeStart.main(Native Method)  
  13. Caused by: android.database.StaleDataException: Attempted to access a cursor after it has been closed.  

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

[java] view plaincopy
  1. Uri uri = data.getData();  
  2.                if (uri != null)  
  3.                {  
  4.                    mFilePath = new URIUtils().getPathFromUri(uri);  
  5.                }  

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

[java] view plaincopy
  1. protected String getPath(Uri uri)  
  2.     {  
  3.         String filePath = "";  
  4.   
  5.         String[] projection = {MediaColumns.DATA };  
  6.         Cursor cursor = managedQuery(uri,  
  7.             projection,  
  8.             null,  
  9.             null,  
  10.             null);  
  11.   
  12.         if (cursor != null)  
  13.         {  
  14.             int columnIndex = cursor.getColumnIndexOrThrow(MediaColumns.DATA);  
  15.             cursor.moveToFirst();  
  16.             filePath = cursor.getString(columnIndex);  
  17.             try  
  18.             {  
  19.                 //4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)  
  20.                 if(Integer.parseInt(Build.VERSION.SDK) < 14)  
  21.                 {  
  22.                     cursor.close();  
  23.                 }  
  24.             }catch(Exception e)  
  25.             {  
  26.                 Log.error(TAG, "error:" + e);  
  27.             }  
  28.         }  
  29.   
  30.         return filePath;  
  31.     }  
0 0
原创粉丝点击