android 解決小米手機上選擇照片路徑為null情況
阿新 • • 發佈:2018-02-05
getc value 選擇 () copyto for contains clas ins view plain copy
昨天測試帥哥說他手機選擇圖庫崩潰了,這是一個上傳頭像的功能,相信很多應用都有這個功能,於是我就把手機拿過來打log看了下返回的路徑 為null,在網上搜索了下解決方案,現在把解決方案記錄下:
這是在onActivityResult方法中執行的,
[html] view plain copy
- if (data == null) {
- return;
- }
- uri = data.getData();
- uri = geturi(data);//解決方案
- String[] proj = { MediaStore.Images.Media.DATA };
- Cursor cursor = managedQuery(uri, proj, null, null, null);
- if(cursor!=null){
- int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
- cursor.moveToFirst();
- String path = cursor.getString(column_index);// 圖片在的路徑
- Intent intent3 = new Intent(this, SYClipActivity.class);
- intent3.putExtra("path", path);
- startActivityForResult(intent3, IMAGE_COMPLETE);
- }
[html]
- /**
- * 解決小米手機上獲取圖片路徑為null的情況
- * @param intent
- * @return
- */
- public Uri geturi(android.content.Intent intent) {
- Uri uri = intent.getData();
- String type = intent.getType();
- if (uri.getScheme().equals("file") && (type.contains("image/"))) {
- String path = uri.getEncodedPath();
- if (path != null) {
- path = Uri.decode(path);
- ContentResolver cr = this.getContentResolver();
- StringBuffer buff = new StringBuffer();
- buff.append("(").append(Images.ImageColumns.DATA).append("=")
- .append("‘" + path + "‘").append(")");
- Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,
- new String[] { Images.ImageColumns._ID },
- buff.toString(), null, null);
- int index = 0;
- for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
- index = cur.getColumnIndex(Images.ImageColumns._ID);
- // set _id value
- index = cur.getInt(index);
- }
- if (index == 0) {
- // do nothing
- } else {
- Uri uri_temp = Uri
- .parse("content://media/external/images/media/"
- + index);
- if (uri_temp != null) {
- uri = uri_temp;
- }
- }
- }
- }
- return uri;
- }
在此記錄下,
android 解決小米手機上選擇照片路徑為null情況