android 解决小米手机上选择照片路径为null情况
昨天测试帅哥说他手机选择图库崩溃了,这是一个上传头像的功能,相信很多应用都有这个功能,于是我就把手机拿过来打log看了下返回的路径 为null,在网上搜索了下解决方案,现在把解决方案记录下:
这是在onActivityResult方法中执行的,
- 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);
- }
- /**
- * 解决小米手机上获取图片路径为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;
- }
在此记录下,