最近开发时遇见小米4,手机选择图库发送图片时崩溃的情况,查看logcat发现cusor查询时为null,查找资料解决此问题,在此记录下:
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 = getContext().getContentResolver();StringBuffer buff = new StringBuffer();buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=").append("'" + path + "'").append(")");Cursor cur = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,new String[] { MediaStore.Images.ImageColumns._ID },buff.toString(), null, null);int index = 0;for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID);// set _id valueindex = 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;}