android 4 0 以上平臺選擇圖片報錯Attempted to access a cursor after it
阿新 • • 發佈:2018-11-15
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
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; }