Reputation: 5486
I have a problem with converting Uri path to URI(to create a file).
My code is:
private void uploadImageToServer(Uri path){
String[] filePathColumn = {MediaStore.Images.Media.DATA};
android.database.Cursor cursor = getContentResolver().query(path, filePathColumn, null, null, null);
if (cursor == null)
return;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File file = new File(filePath);
}
However my cursor is null.
My "Uri path" parameter from function is:
file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg
I was following this tutorial: https://medium.com/@adinugroho/upload-image-from-android-app-using-retrofit-2-ae6f922b184c
Upvotes: 0
Views: 7537
Reputation: 318
try this and and I highly recommend not using
content://
just use it as
content:
String imagePath = "";
Uri targetUri = data.getData();
if (data.toString().contains("content:")) {
imagePath = getRealPathFromURI(targetUri);
} else if (data.toString().contains("file:")) {
imagePath = targetUri.getPath();
} else {
imagePath = null;
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = getContentResolver().query(contentUri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Upvotes: 3
Reputation: 11214
My "Uri path" parameter from function is:
file:///storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg
Then the path you are after is
/storage/emulated/0/Pictures/MyApp/IMG_20170411_170952.jpg
Code
private void uploadImageToServer(Uri uri){
String filePath = uri.toString().replace("file://", "" );
File file = new File(filePath);
}
Maybe you could even use uri.getPath() directly. Please check.
Upvotes: 0