I am selecting an image of the gallery from my app,
using
ACTION_GET_CONTENT
Now I want the path of this image:
But i get it like this:
content://com.android.providers.media.documents/document/image%3A5793
How can i get the path?
I tried this to get path:
Uri uri = data.getData();
Log.e("Path is: "+uri);
The answer is don't try and get the path because in Android 10 and later you won't be able to get it or use it.
You can get a FileDescriptor or input/output Stream that can be used in most methods that need to access the file contents.
See https://developer.android.com/training/data-storage/ for more details, since it is a picture then using Media store is probably best.
Try this :
Uri uri = data.getData();
String picturePath = getPath( getActivity( ).getApplicationContext( ), uri);
Log.e("Picture Path", picturePath);
public static String getPath( Context context, Uri uri ) {
String result = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
if(cursor != null){
if ( cursor.moveToFirst( ) ) {
int column_index = cursor.getColumnIndexOrThrow( proj[0] );
result = cursor.getString( column_index );
}
cursor.close( );
}
if(result == null) {
result = "Not found";
}
return result;
}
Related
In my app, the user can choose where the created files (text files) are created.
This part is working fine.
But now, I want to open an external "file explorer" app, pointing directly to the chosen folder.
The "file explorer " apps I know accept an absolute path as input (like /storage/emulated/0/Documents/test_folder)
When the user chooses a folder (with Intent.ACTION_OPEN_DOCUMENT_TREE), I get a content uri (like content://com.android.externalstorage.documents/tree/home%3Atest_folder)
Another example with an external sd card:
uri: content://com.android.externalstorage.documents/tree/3877-DB74%3ADocuments%2Ftest_folder
expected path: /storage/3877-DB74/Documents/test_folder
The uri points to a folder, not a file, so I can't use something like openInputStream
I have tried :
File f = new File(uri.getPath());
String path = f.getAbsolutePath();
but it gives: /tree/home:test_folder or /tree/3877-DB74:Documents/test_folder if on sd card
How can I get the real absolute path?
The code I use to call a file explorer:
Intent intent = new Intent(Intent.ACTION_VIEW);
String path = getExternalFilesDir(null).getAbsolutePath();
intent.setDataAndType(Uri.parse(path), "resource/folder");
if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
startActivity(intent);
}
so basically you want to get file path from uri
you give try with this code
https://gist.github.com/pratikbutani/eb56f6f9f7013e31d8bfea9effbd4251
I have tried the suggested code (see above).
Unfortunately, I got an exception:
Caused by: java.lang.UnsupportedOperationException: Unsupported Uri content://com.android.externalstorage.documents/tree/home%3Atest_folder
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:418)
at android.content.ContentResolver.query(ContentResolver.java:760)
at android.content.ContentResolver.query(ContentResolver.java:710)
at android.content.ContentResolver.query(ContentResolver.java:668)
at ....UriUtils.getDataColumn(UriUtils.java:278)
Here is a copy of the code:
private static String getDataColumn(Context context, Uri uri)
{
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection,
null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
I finally wrote my own method to get the absolute path for a folder from a Uri.
It is surely not fully generic, but it meets my need.
if it can help someone, here is my code:
Note: VOLUME_MAP is a map containing all mounted external volumes
/**************************************************************************/
public static String getRealPathFromContentUri(final Uri uri)
{
if (!isExternalStorageDocument(uri))
{
return null;
}
List<String> segs = uri.getPathSegments();
if (!"tree".equalsIgnoreCase(segs.get(0)))
{
return null;
}
String path = uri.getLastPathSegment();
final String[] split = path.split(":");
final String volumeId = split[0];
String userPath = "";
if (split.length > 1)
{
userPath = "/" + split[1];
}
if ("primary".equalsIgnoreCase(volumeId))
{
return Environment.getExternalStorageDirectory().getAbsolutePath() + userPath;
}
if ("home".equalsIgnoreCase(volumeId))
{
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath() + userPath;
}
// look for real volumeId
final String volumeName = VOLUME_MAP.get(volumeId);
if (volumeName == null)
{
return null;
}
path = "/storage";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R)
{
path = Environment.getStorageDirectory().getAbsolutePath();
}
return path + "/" + volumeId + userPath;
}
Thanks to all contributors on this topic.
I'm using the Android's DownloadManager class. It returns Uri with content:// scheme after clicking on the "downloaded file" notification. I have a method which is now only able to open files using file Uris (with "file" scheme). What is the easiest way to get the File file from the content Uri. Any examples are welcome.
public PlsReader(URI path) {
File file = new File(path);
}
Use Context#getContentResolver().openInputStream(uri) to get an InputStream from a Uri.
Or use Context#getContentResolver().openFileDescriptor() to get a ParcelFileDescriptor. Then use ParcelFileDescriptor#getFileDescriptor() to get a FileDescriptor.
try this
1st method to get is below
Uri.getPath();
this will give u whole absolute path of any file
and 2nd method is below
Strinf absolutepath = getRealPathFromURI(this,URI);
and method getRealPathFromURI is here
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();
}
}
}
then pass this absolutepath string to your file like this
public PlsReader(String absolutepath ) {
File file = new File(absolutepath );
}
best of luck dude :)
When I select an image from the gallery, I grab the intent Uri via the parameter that is passed by the onActivityResult. When doing: new File(String_Uri_given_to_me) and do File.Exists(), gives me null...
What I can do?
It seems you may try:
new File(Uri_given_to_you.getpath())
It may be okay.
If answer above doesn't solve your problem use this code
private final synchronized String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, proj,
null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
I was having a hard time with this issue. I was not able to get some images Path (Even using Maxim Efivmov code) and finally decided to use Google's documentation on this topic. https://developer.android.com/guide/topics/providers/document-provider.html
This piece of code worked to get the bitmap
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
You can use this bitmap to display it in an Image View.
I have registered my app to receive files (of any type, not just images) from other apps following this post.
I have implemented the solution that was answered but I cannot find a way to retrieve the "file name" of the data stream.
As an example from an Uri like:
content://downloads/all_downloads/5
I can get the stream out but I don't know anything about the name of the original file generating it.
Is there a way to retrieve it?
In MOST cases this will solve your problem:
Uri intentData = intent.getData();
if (intentData != null) {
String filePath;
if("content".equals(intent.getScheme()))
{
filePath = getFilePathFromContentUri(intentData);
}
else
{
filePath = intentData.getPath();
}
}
private String getFilePathFromContentUri(Uri selectedUri) {
String filePath;
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = getContentResolver().query(selectedUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
Is there a way to retrieve it?
Generally, no, because there may not be a name, in part because there may not be a file. You may be able to get an InputStream on the contents, but that does not mean that there is a file behind the InputStream.
There may be some specific hacks for some specific providers (e.g., MediaStore) to try to determine the file name associated with some data Uri, though such hacks may not be reliable.
onCreate()
Intent intent1 = getIntent();
String action = intent1.getAction();
String type = intent1.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
this.handleSend(intent1);
}
void handleSend(Intent intent) {
try {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
imageShare.setImageURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
I'm using the follow code to take a picture using the native camera:
private File mImageFile;
private String mTempImagePath;
public static Uri imageUri;
public void imageFromCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
Log.d("fototemp", "No SDCARD");
} else {
mImageFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder", "Pic"+System.currentTimeMillis()+".jpg");
imageUri = Uri.fromFile(mImageFile);
DataClass dc = (DataClass) getApplicationContext();
File tempFile = new File(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
Uri tempUri = Uri.fromFile(tempFile);
dc.setString(DataClass.IMAGE_PATH, tempUri.toString());
Log.d("fototemp", "ImagePath: " + tempUri.toString());
mTempImagePath = mImageFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
startActivityForResult(intent, 0);
}
}
The ImagePath I print out in the imageFromCamera() method is: 4file:///file%3A/mnt/sdcard/testFolder
Now when I try to access these foto's by using managedQuery I get a different directory.
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI.toString() gives content://media/external/images/thumbnails
What is the difference between these 2 paths? And how can I get the managedQuery to go to the testFolder map to look for pictures?
edit:
I'm trying to connect:
Uri phoneUriII = Uri.parse(Environment.getExternalStorageDirectory()+File.separator+"testFolder");
imagecursor = managedQuery(phoneUriII, img, null,null, MediaStore.Images.Thumbnails.IMAGE_ID + "");
but this code crashes
Sorry don't really understand your question.
Just send this as the URI path.
Environment.getExternalStorageDirectory()+File.separator+"testFolder"
Also
Check if you have the permissions to write to the sd card.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
I'm using this function in a couple of projects and it works fine.
/**
* Retrieves physical path to the image from content Uri
* #param contentUri
* #return
*/
private String getRealImagePathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}