1. 程式人生 > >android 獲取本地圖片路徑失敗,cursor.getString(column_index);返回null

android 獲取本地圖片路徑失敗,cursor.getString(column_index);返回null

今天有個需求就是獲取手機本地圖片,然後二維碼解析結果,跳轉網頁! 之前我獲取圖片的程式碼是這麼寫的 /* * 獲取帶二維碼的相片進行掃描 */public void pickPictureFromAblum(View v) { // 開啟手機中的相簿 Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); innerIntent.setType("image/*"); Intent wrapperIntent = Intent.createChooser(innerIntent, "選擇二維碼圖片"); this.startActivityForResult
(wrapperIntent, 1);} 而獲取路勁的程式碼 Uri uri = data.getData();if (!TextUtils.isEmpty(uri.getAuthority())) { Cursor cursor = getContentResolver().query(uri, new String[] { MediaStore.Images.Media.DATA }, null, null, null); if (null == cursor) { Toast.makeText(this, "圖片沒找到", Toast.LENGTH_SHORT).show(); return
; } cursor.moveToFirst(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); photo_path = cursor.getString(column_index); cursor.close();} else { photo_path = data.getData().getPath();} 之前我在測試機上執行後是能拿到路勁的,但是後來發現在4.4版本後就一直拿不到圖片的路徑,後來上網查詢資料發現 這種方法呼叫相簿並獲取圖片在android4.4版本之前是可行的,但是之後就不可行了,。根本原因是前者和後者返回的URI已經不是同一個了,前者URI中包含了檔案的絕對路徑,是有_data的,但是後者URI就沒有了。所以你拿不到!
<4.4 URI:content://media/external/images/media/164 含有檔案的絕對路徑 》4.4URI :content://com.android.providers.media.documents/document/image:3951,只有檔案的相對編號 兩者返回的內容也有所不同 最終的解決方法其實很簡單,就是Intent.ACTION_GET_CONTENT換成Intent.ACTION_PICK Intent innerIntent = new Intent(Intent.ACTION_PICK); // "android.intent.action.GET_CONTENT"innerIntent.setType("image/*");Intent wrapperIntent = Intent.createChooser(innerIntent, "選擇二維碼圖片");this.startActivityForResult(wrapperIntent, 1); 雖然是個簡單的bug,但是也留下點什麼 防止後面會有兄弟同樣的問題出現。