I'm trying to figure out how to convert an Android Uri to a Java URI. What I'm trying to do is get a File, but as far as I can tell, I need to pass it a Java URI.
Here's my Uri that I'm attempting to convert:
content://media/external/images/media/100
And what I'm attempting to get at:
File mediaFile = new File(new URI("android.net.Uri"));
Where "android.net.Uri" is my Uri object
If there is a different/better way to get a java.io.File object from this content Uri, I'm open to suggestions as I've searched far and wide with no luck so far.
Got it figured out, I was able to get the real filepath of the Uri and then create the File:
Uri uri = Uri.parse("content://media/external/images/media/47");
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cur = managedQuery(uri, projection, null, null, null);
cur.moveToFirst();
String path = cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA));
mediaFile = new File(path);
Related
I am testing app on nexus 5 which has marshmallow version of android. I am looked into several method to get file path from uri but all the time it returns null. This method works for me on jelly bean and also on kitkat but not on marshmallow.
public String getPath(Uri uri) {
Log.d(TAG,"Uri GET PATH "+uri);
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
Log.d(TAG,"Cursor value "+cursor);
int Column_Index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Log.d(TAG,"Column Index "+Column_Index);
cursor.moveToFirst();
String ImagePath = cursor.getString(Column_Index);
Log.d(TAG,"ImagePath of "+ImagePath);
cursor.close();
return ImagePath;
}
I also tried this this and also so many others but getting file path from uri is always null.
Uri return from Intent:content://com.android.providers.media.documents/document/image%3A2304`
I am looked into several method to get file path from uri but all the time it returns null
There is no file path. A Uri is not a file.
Use a ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri. Either use that InputStream directly, or use it and a FileOutputStream on some file that you control (e.g., in getCacheDir()) to copy the content to the file, then use the resulting file.
I have a method below:
private String getRealPathFromUriForVideos(Uri selectedVideoUri) {
String wholeID = DocumentsContract.getDocumentId(selectedVideoUri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Video.Media.DATA };
String sel = MediaStore.Video.Media._ID + "=?";
Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
This works just fine getting the file for videos that hte user selects. However, I want to allow users to also create new videos (from my app) and then get the URI and the file from there. The URI for newly created videos is: content://media/external/video/media/41. For selected videos is like content://com.android.providers.media.documents/document/video%3A42.
It works with the second one but not the first one. First one I get IllegalArgumentException because its not a document URI. How can I get the file from the first URI?
This works just fine getting the file for videos that hte user selects
It may work in a few situations. It will not work in general. A Uri that you get from something like ACTION_OPEN_DOCUMENT does not have to represent a file, let alone one that you can access via the filesystem, let alone one that this script-kiddie algorithm will let you access.
The URI for newly created videos is: content://media/external/video/media/41
Not necessarily. I suppose that there is a way that you get a Uri like that for a recorded video, though off the top of my head I cannot think of a recommended way that would give you such a Uri. If you are using MediaRecorder or ACTION_VIDEO_CAPTURE, you create your own file (and, for ACTION_VIDEO_CAPTURE, your own Uri for that file). And, if you are creating your own file, you know where that file is.
Need to be able to upload to my server
For the video, record to a file that you control, then use that file.
Use some library that lets you upload from a Uri or InputStream. Otherwise:
Use ContentResolver and openFileInput() to get an InputStream on the content represented by the Uri
Create a FileOutputStream on some file that you control (e.g., in getCacheDir())
Copy the content from the InputStream to the OutputStream
Use your copy for the upload
Delete your copy when the work is done
You treat a foreign Uri as if it were a URL to a Web server: stream the content.
Seems to get it from the second URI I need this:
private String getRealPathFromUriForImagesAndVideo(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);
} catch (Exception e) {
return contentUri.getPath();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
I have two type of Uris.
type one :
content://media/external/images/media/465
content://media/external/images/media/466
type two :
file:///storage/emulated/0/DCIM/Camera/20151112_185009.jpg
file:///storage/emulated/0/testFolder/20151112_185010.jpg
What is difference and how to convert file uri to content uri?
Because, file uri is just causing error. When I call method :
ContentResolver contentResolver = getContentResolver();
fis = (FileInputStream) contentResolver.openInputStream(fileTypeUri);
how do I fix this?
Try It :)
public static Uri getImageContentUri(Context context, File file) {
String filePath = file.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (file.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
If you're trying to share data that is stored as part of your app with another app you'll need to use a content:// scheme and not a file:// scheme. This can be accomplished using the FileProvider class found here: https://developer.android.com/reference/android/support/v4/content/FileProvider.html.
By using the FileProvider class you can more precisely and more securely define what files your app can share.
Though be aware that external-cache-path and external-files-path don't work despite what the documentation says. See: how to set FileProvider for file in External Cache dir for more info.
i am implementing the functionality to save file in my app which is being sent by some exteral application.
i have provided support for single and mulitple files. Provided handling for all kind of files.
But i am not able to handle the following scenario.
I view a file from an email client -> View it in QuickOffice -> Click on send -> Choose my app->Then click on save in my app.
In that i get the path in following wrapped in the exception
java.io.FileNotFoundException: /file:/data/data/com.qo.android.sp.oem/files/temp/Error.log: open failed: ENOENT (No such file or directory)
I have seen this post which is quite useful for handling uri which has content scheme
Get filename and path from URI from mediastore
Below is my code
Uri uri = (Uri) iterator.next();
if ("content".equals(uri.getScheme())) {
filePath = getFilePathFromContentUri(uri, hostAcitvity.getContentResolver());
}
else {
filePath = uri.getPath();
}
fileName = uri.getLastPathSegment();
fileSize = hostAcitvity.getContentResolver().openInputStream(uri).available();
Code for getFilePathFromContentUri
private String getFilePathFromContentUri(Uri selectedVideoUri, ContentResolver contentResolver)
{
String filePath;
String[] filePathColumn = { MediaColumns.DATA };
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
Then i wrap the path in a FileInputStream which is throwing the above exception
Not able to resolve the file path properly. Is this the correct way of finding the path ?
cheers,
Saurav
I have seen this post which is quite useful for handling uri which has content scheme
That never worked reliably and will work even less reliably in the future.
Is this the correct way of finding the path ?
No, because there is no requirement that every Uri map to a path on a filesystem that you can access.
Use getInputStream() on ContentResolver to get an InputStream on the Uri, and consume the data that way.
I am desperately trying to send a captured video to a server. The problem is that the URI that is given by the built-in camera application is not the real file path. It looks like this - /content:/media/external/video/media/19.
How can I access the real path or the data directly from this kind of URIs?
After reading the android documentation I saw that it looks like a content provider's notation, but I still don't have a clue how to reach the data that I need. Please help!!!
thanks in advance
How can I access the real path or the data directly from this kind of URIs?
You don't. It might not exist as a file. Or, it might not exist as a file that you can read except via the ContentProvider.
Instead, use a ContentResolver to open an InputStream on that Uri, and use that InputStream to transfer the data to a server.
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.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();
}
}
}
see following post for
Get filename and path from URI from mediastore