java – Android KitKat图像选择不返回任何内容
作者:互联网
我一直试图获得在KitKat画廊中选择的图像的绝对图像路径,但它似乎没有成功.无论我做什么,我的变量IMAGE_FILEPATH总是“”.这是我的onActivityResult()的代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
if (null == data) return;
Uri originalUri = null;
if (requestCode == 1) {
//JB!!!
Uri uri = data.getData();
if (uri != null) {
try {
// User had pick an image.
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver()
.query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
IMAGE_FILEPATH = cursor.getString(0);
cursor.close();
} catch (Exception e) {
Crouton.makeText(this, "Failed to get image", Style.ALERT).show();
}
}
} else if (requestCode == 2) {
//KK!!!
Uri uri = data.getData();
if (uri != null) {
try {
if( uri == null ) {
IMAGE_FILEPATH = uri.getPath();
} else {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
IMAGE_FILEPATH = cursor.getString(column_index);
} else {
IMAGE_FILEPATH = uri.getPath();
}
}
} catch (Exception e) {
Crouton.makeText(this, "Failed to get image", Style.ALERT).show();
}
}
}
Resource.toast(IMAGE_FILEPATH);
super.onActivityResult(requestCode, resultCode, data);
}
出了什么问题?我尝试了多种解决方案,但似乎没有任何效果.
解决方法:
在KitKat中,Gallery返回如下URI:content://com.android.providers.media.documents/document/image:1
代替 :
content://media/external/images/media/1
那么,这里是您可以在KK下编写的内容,使其有效:
if (uri != null) {
try {
if( uri == null ) {
IMAGE_FILEPATH = uri.getPath();
} else {
// get the id of the image selected by the user
String wholeID = DocumentsContract.getDocumentId(data.getData());
String id = wholeID.split(":")[1];
String[] projection = { MediaStore.Images.Media.DATA };
String whereClause = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(getUri(), projection, whereClause, new String[]{id}, null);
if( cursor != null ){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
IMAGE_FILEPATH = cursor.getString(column_index);
}
cursor.close();
} else {
IMAGE_FILEPATH = uri.getPath();
}
}
} catch (Exception e) {
Crouton.makeText(this, "Failed to get image", Style.ALERT).show();
}
}
我使用的功能:
private Uri getUri() {
String state = Environment.getExternalStorageState();
if(!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
return MediaStore.Images.Media.INTERNAL_CONTENT_URI;
}
return MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
这些帖子帮助了我:retrieve absolute path when select image from gallery kitkat android和Get real path from URI, Android KitKat new storage access framework
标签:android,java,return,android-4-4-kitkat,android-image 来源: https://codeday.me/bug/20190722/1507289.html