How to get a File from a URI? - android

I select an image from the image gallery in my app. In the onActivityResult it returns an Intent object and I execute the getData() method on it. I get the image URI back. I am now trying to convert that in to a File so I can send it to AWS S3.
This is what I have been trying but it just returns null:
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
I also try
File file = new File(imageURI.getPath())
also null. Is this impossible or can somebody help?

supposing your onActivityResult checks in with the Intent object being ReturnedIntent you can do
File f = new File(ReturnedIntent.getData());
or get an inputstream and use it
getContentResolver().openInputStream(ReturnedIntent.getData())
//returns inputstream
what is the essence of this String object String filePath ?

Related

Unable to load image into imageview from GoogleStorageURI (Google Drive image uri) using Gallery Intent

I have downloaded an image from Google Drive storage. I want to set this image to imageview in my app using Gallery Intent.
Uri of image received in onActivityResult: content://com.google.android.apps.docs.storage/document/acc%3D2%3Bdoc%3Dencoded%3DWe%2BdXDcNgTeulVk1Ntu3YfRYkm9wk7uTdTG6LFVyck1BxY4g7xAxyPAgtMtz4A%3D%3S
I am using this code get the real-path from the url:
if ("com.google.android.apps.docs.storage".equals(uri
.getAuthority())) {
//content://com.google.android.apps.docs.storage/document/acc%3D2%3Bdoc%3Dencoded%3DWe%2BdXDcNbYeulVk1Ntu3YfRYkm9wk7uTdTG6LE6yck1BxY4g7xAxyPAgtMtz4A%3D%3D
final String docId = DocumentsContract.getDocumentId(uri);
final String id = docId.split(";")[1];
final String[] selectionArgs = new String[]{id};
//String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String selection = MediaStore.Images.Media._ID + "=?";
Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
//..
Cursor cursor = null;
String filePath = null;
try {
String[] column = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri,
column, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(column[0]);
filePath = cursor.getString(columnIndex);
}
} finally {
if (cursor != null)
cursor.close();
return filePath;
}
}
.....
But I am getting NULL cursor. Thus, filepath is always empty/null.
Anyone, could please suggest what I am doing wrong?
I am using this code get the real-path from the url
Delete it.
Anyone, could please suggest what I am doing wrong?
You are using that code.
Pass the Uri to your favorite image-loading library (Glide, Picasso, etc.). It will do all the work for you, populating your ImageView, in just a few lines of code.
Or, if you insist on doing it yourself:
Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri
Use BitmapFactory.decodeStream() to get a Bitmap based on that InputStream
Do those two steps on a background thread, as you should not do disk I/O and image decoding on the main application thread
On the main application thread, put the Bitmap in your ImageView,

cursor.getString() returning null

I am new to android (started this week) and am currently writing a photo album app for a class. I am currently trying to get an image selected by the user, however, after selecting the image I am using cursor to get the path but the getString() method is returning null. Here is the code segment in onActivityResult:
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow(filePathColumn[0]);
final String picturePath = cursor.getString(columnIndex);
cursor.close();
//create photo object
I used the debugger tool to step through the code. data.getData() does not return null.filePathColumn[0] contains "_data", crusor.moveToFirst() returns true and columnIndex = 0. Then the cursore.getString(columnIndex) returns null. Can anybody help me figure out what is going wrong ?

How to handle image path for an image comming from external sources like Dropbox

I've developed image cropper so that user can crop selected image from gallery. When user has taken a picture with camera or has selected it from gallery, image uri is queried for image metadata and image file path is passed to various bitmap methods for bitmap creation.
But now I've expanded users selection option to Dropbox also and uri that I receive from intent is in the form of:
01-08 09:11:21.051: I/DROPBOX(2761): file:///storage/emulated/0/Android/data/com.dropbox.android/files/u98667695/scratch/Capture.PNG
Query on this uri returns null for cursor, so I tried to convert uri to string, remove first 7 characters and pass that string as image file path. This works fine if I select image from root directory on Dropbox...
So, my question how image request from external sources like Dropbox for instance in order to get image file path when intent returns uri for requested image?
This is method where I'm retrieving file path:
private void getImageData(Uri selectedImage){
String[] filePathColumn = { MediaStore.Images.Media.DATA };
String[] fileOrientationColumn = { MediaStore.Images.Media.ORIENTATION };
Cursor cursor = context.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
/* if(cursor == null){
imageFilePath = selectedImage.toString().substring(6);
return;
}
*/ cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageFilePath = cursor.getString(columnIndex);
Log.i("CURSOR path", imageFilePath);
cursor = context.getContentResolver().query(selectedImage,
fileOrientationColumn, null, null, null);
cursor.moveToFirst();
columnIndex = cursor.getColumnIndex(fileOrientationColumn[0]);
String fileOrientation = cursor.getString(columnIndex);
// Izmena
if(fileOrientation == null)fileOrientation = "0";
imageOrientation = Integer.parseInt(fileOrientation);
cursor.close();
Log.i("CURSOR orientation", fileOrientation);
}
In above case you can do the following.
String filePath="I/DROPBOX(2761): file:///storage/emulated/0/Android/data/com.dropbox.android/files/u98667695/scratch/Capture.PNG";
int firstIndex=filePath.indexOf("file");
String actualPath=filePath.subString(firstIndex);
So the actualPath contains required path as follows, irrespective of root directory or file location.
actualPath="file:///storage/emulated/0/Android/data/com.dropbox.android/files/u98667695/scratch/Capture.PNG"

Open a Google Drive File Content URI after using KitKat Storage Access Framework

I am using the Storage Access Framework for android 4.4 and opening the file picker.
Everything works except when choosing a file from Google Drive, I can only figure out how to open it as an input stream, but I would like to get a java File object.
The content uri that's being returned looks something like this: content://com.google.android.apps.docs.storage/document/acc%3D4%3Bdoc%3D2279
Other questions that are similar but do not have a working solution which allows me to get the filename, filesize and contents:
Get real path from URI, Android KitKat new storage access framework
Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT
I've also looked into Paul Burke's FileChooser ( https://github.com/iPaulPro/aFileChooser) and this is the most common question on the issue's list.
How can I get a file from that content uri?
My current workaround is to write out a temporary file from an inputstream.
Thanks!
Ok. I found that the right way is to use the input stream from the other posts in conjunction with some data from the contentresolver.
For reference here are the hard to find android docs: https://developer.android.com/training/secure-file-sharing/retrieve-info.html
The relevant code to get mimetype, filename, and filesize:
Uri returnUri = returnIntent.getData();
String mimeType = getContentResolver().getType(returnUri);
Cursor returnCursor =
getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
TextView nameView = (TextView) findViewById(R.id.filename_text);
TextView sizeView = (TextView) findViewById(R.id.filesize_text);
nameView.setText(returnCursor.getString(nameIndex));
sizeView.setText(Long.toString(returnCursor.getLong(sizeIndex)));
And to get the file contents:
getContentResolver().openInputStream(uri)
Hope this helps someone else.
Adding to #Keith Entzeroth answer , after getting fileName, fileSize and Input Stream , this is way to get the file
public static File getFile(final Context context, final Uri uri) {
Log.e(TAG,"inside getFile==");
ContentResolver contentResolver = context.getContentResolver();
try {
String mimeType = contentResolver.getType(uri);
Cursor returnCursor =
contentResolver.query(uri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String fileName = returnCursor.getString(nameIndex);
String fileSize = Long.toString(returnCursor.getLong(sizeIndex));
InputStream inputStream = contentResolver.openInputStream(uri);
File tempFile = File.createTempFile(fileName, "");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copyStream(inputStream,out);
return tempFile;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
this code solved my problem, when i tried to select image from google drive ,app get crashed ,
private void setImagePath(Intent data) throws Exception {
String wholeID="";
Uri selectedImage = data.getData();
if(Build.VERSION.SDK_INT<=Build.VERSION_CODES.JELLY_BEAN_MR2){
wholeID=getUriPreKitkat(selectedImage);
}else {
wholeID = DocumentsContract.getDocumentId(selectedImage);
}
// Split at colon, use second item in the array
Log.i("debug","uri google drive "+wholeID);
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}

Android working with MediaStore

How can I open a file that I stored in gallery? I used this method to put my file there:
MediaStore.Images.Media.insertImage()
According to documentation it returns String url to the newly created file. However when I trying to open this file it fails. Getting file not found exception.
What am I missing? Any ideas?
It returns the String url or the content uri string back. To get the actual file path from the uri you need to use something like
protected String convertMediaUriToPath(Uri uri) {
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
You can convert the string url that you get to the Uri using Uri.parse(url);

Categories

Resources