So i am using retrofit to upload images to our server, and am using gallery chooser to choose the image. I am trying to get the path of the image, because uri.getPath() returns file not found exception. I have literally seen almost every stackoverflow article on this subject, and still have no answer. The following code that I have is similar to everything I have seen online, and it ALWAYS returns null, and I have no idea why. PLEASE HELP
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
try {
android.net.Uri selectedImage = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
// Log.d(TAG, String.valueOf(bitmap));
ImageView imageView = (ImageView) findViewById(R.id.expandedProfilePic);
imageView.setImageBitmap(bitmap);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
android.database.Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor == null)
return;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
// is always null
System.out.println("FILE PATH " + filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am trying to get the path of the image, because uri.getPath() returns file not found exception
Assuming that by "gallery chooser", you mean ACTION_GET_CONTENT
or possibly ACTION_PICK
, there is no path, because a Uri
is not a file.
I have literally seen almost every stackoverflow article on this subject
No, you have not. Specifically, you have not read any of the dozens that I have contributed to, such as this one or this one or this one or this one or this one or this one or this one or this one or this one or this one or this one or this one or this one. And those are just from 2017.
The following code that I have is similar to everything I have seen online
And that code will not work for most Uri
values.
Use a ContentResolver
and openInputStream()
to get an InputStream
on the content identified by the Uri
. Ideally, you would just use the InputStream
. In the case of Retrofit, while I have not tried uploading content with it, my guess is that it insists upon a file. In that case, use the InputStream
and a FileOutputStream
on some file that you control to make a copy of the content. Then, upload the copy, deleting it when you are done.