1. 程式人生 > >android 解決小米手機上選擇照片路徑為null情況

android 解決小米手機上選擇照片路徑為null情況

getc value 選擇 () copyto for contains clas ins

昨天測試帥哥說他手機選擇圖庫崩潰了,這是一個上傳頭像的功能,相信很多應用都有這個功能,於是我就把手機拿過來打log看了下返回的路徑 為null,在網上搜索了下解決方案,現在把解決方案記錄下:

這是在onActivityResult方法中執行的,

[html] view plain copy
  1. if (data == null) {
  2. return;
  3. }
  4. uri = data.getData();
  5. uri = geturi(data);//解決方案
  6. String[] proj = { MediaStore.Images.Media.DATA };
  7. Cursor cursor = managedQuery(uri, proj, null, null, null);
  8. if(cursor!=null){
  9. int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  10. cursor.moveToFirst();
  11. String path = cursor.getString(column_index);// 圖片在的路徑
  12. Intent intent3 = new Intent(this, SYClipActivity.class);
  13. intent3.putExtra("path", path);
  14. startActivityForResult(intent3, IMAGE_COMPLETE);
  15. }

[html]
view plain copy
  1. /**
  2. * 解決小米手機上獲取圖片路徑為null的情況
  3. * @param intent
  4. * @return
  5. */
  6. public Uri geturi(android.content.Intent intent) {
  7. Uri uri = intent.getData();
  8. String type = intent.getType();
  9. if (uri.getScheme().equals("file") && (type.contains("image/"))) {
  10. String path = uri.getEncodedPath();
  11. if (path != null) {
  12. path = Uri.decode(path);
  13. ContentResolver cr = this.getContentResolver();
  14. StringBuffer buff = new StringBuffer();
  15. buff.append("(").append(Images.ImageColumns.DATA).append("=")
  16. .append("‘" + path + "‘").append(")");
  17. Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,
  18. new String[] { Images.ImageColumns._ID },
  19. buff.toString(), null, null);
  20. int index = 0;
  21. for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
  22. index = cur.getColumnIndex(Images.ImageColumns._ID);
  23. // set _id value
  24. index = cur.getInt(index);
  25. }
  26. if (index == 0) {
  27. // do nothing
  28. } else {
  29. Uri uri_temp = Uri
  30. .parse("content://media/external/images/media/"
  31. + index);
  32. if (uri_temp != null) {
  33. uri = uri_temp;
  34. }
  35. }
  36. }
  37. }
  38. return uri;
  39. }


在此記錄下,

android 解決小米手機上選擇照片路徑為null情況