I have an onActivityResult
returning from an mediastore image selection which I can get a URI for an image using the following:
我有一个从mediastore图像选择返回的onActivityResult,我可以使用以下方法获得图像的URI:
Uri selectedImage = data.getData();
Converting this to a string gives this:
将其转换为字符串,就得到:
content://media/external/images/media/47
Or to a path gives:
或者给一条路:
/external/images/media/47
However I can't seem to find a way to convert this into an absolute path, as I want to load the image into a bitmap without having to copy it somewhere. I know this can be done using the URI and content resolver, but this seems to break on rebooting of the phone, I guess MediaStore
doesn't keep its numbering the same between reboots.
然而,我似乎无法找到一种方法将它转换成绝对路径,因为我想在不需要复制的情况下将图像加载到位图中。我知道这可以使用URI和内容解析器来完成,但是这似乎在重新引导电话时发生了故障,我想MediaStore在重新引导之间的编号并不相同。
19 个解决方案
#1
573
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();
}
}
}
#2
116
Just a simple update on the first answer: mActivity.managedQuery()
is now deprecated. I've updated the code with the new method.
对于第一个答案:mActivity.managedQuery()的简单更新现在已经过时了。我用新方法更新了代码。
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
android开发源
#3
90
Don't try to find a uri in the filesystem, that's slow to go look things up in the database.
不要试图在文件系统中找到uri,在数据库中查找内容是很慢的。
You can get a bitmap from a uri by giving an input stream to the factory like you give a file to the factory:
您可以从uri中获得位图,方法是向工厂提供输入流,就像向工厂提供文件一样:
InputStream is = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
#4
70
For All version I have made this method which get real path from uri
对于所有版本,我都创建了这个方法,它从uri获取真正的路径
@SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
uri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
#5
39
Here it is my example of getting file name, from URI like file://... and content://... . It's works for me not only with Android MediaStore but also with third part application like EzExplorer.
这里是我从URI(比如file:/…)获取文件名的示例。和内容:/ /……它不仅适用于Android MediaStore,也适用于第三部分应用,比如EzExplorer。
public static String getFileNameByUri(Context context, Uri uri)
{
String fileName="unknown";//default fileName
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
filePathUri = Uri.parse(cursor.getString(column_index));
fileName = filePathUri.getLastPathSegment().toString();
}
}
else if (uri.getScheme().compareTo("file")==0)
{
fileName = filePathUri.getLastPathSegment().toString();
}
else
{
fileName = fileName+"_"+filePathUri.getLastPathSegment();
}
return fileName;
}
#6
15
Good existing answers, some of which I used to come up with my own:
好的现有答案,其中一些我以前也有自己的答案:
I have to get the path from URIs and get the URI from paths, and Google has a hard time telling the difference so for anyone who has the same issue (e.g., to get the thumbnail from the MediaStore
of a video whose physical location you already have). The former:
我必须从URI获取路径并从路径获取URI,谷歌很难区分两者的区别,因此对于任何有相同问题的人(例如,从已经有物理位置的视频的MediaStore获取缩略图)。前:
/**
* Gets the corresponding path to a file from the given content:// URI
* @param selectedVideoUri The content:// URI to find the file path from
* @param contentResolver The content resolver to use to perform the query.
* @return the file path as a string
*/
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;
}
The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video):
后者(我用于视频,但也可以用于音频或文件或其他类型的存储内容,通过替换MediaStore。音频(MediaStore.Video等)):
/**
* Gets the MediaStore video ID of a given file on external storage
* @param filePath The path (on external storage) of the file to resolve the ID of
* @param contentResolver The content resolver to use to perform the query.
* @return the video ID as a long
*/
private long getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
Basically, the DATA
column of MediaStore
(or whichever sub-section of it you're querying) stores the file path, so you either use what you know to look up that DATA
field, or use the field to look up whatever else you want.
基本上,MediaStore的数据列(或您正在查询的它的任何子部分)存储文件路径,所以您要么使用您知道的内容来查找数据字段,要么使用字段来查找您想要的其他内容。
I then further use the Scheme
as above to figure out what to do with my data:
然后,我进一步使用上述方案,找出如何处理我的资料:
private boolean getSelectedVideo(Intent imageReturnedIntent, boolean fromData) {
Uri selectedVideoUri;
//Selected image returned from another activity
// A parameter I pass myself to know whether or not I'm being "shared via" or
// whether I'm working internally to my app (fromData = working internally)
if(fromData){
selectedVideoUri = imageReturnedIntent.getData();
} else {
//Selected image returned from SEND intent
// which I register to receive in my manifest
// (so people can "share via" my app)
selectedVideoUri = (Uri)getIntent().getExtras().get(Intent.EXTRA_STREAM);
}
Log.d(TAG,"SelectedVideoUri = " + selectedVideoUri);
String filePath;
String scheme = selectedVideoUri.getScheme();
ContentResolver contentResolver = getContentResolver();
long videoId;
// If we are sent file://something or content://org.openintents.filemanager/mimetype/something...
if(scheme.equals("file") || (scheme.equals("content") && selectedVideoUri.getEncodedAuthority().equals("org.openintents.filemanager"))){
// Get the path
filePath = selectedVideoUri.getPath();
// Trim the path if necessary
// openintents filemanager returns content://org.openintents.filemanager/mimetype//mnt/sdcard/xxxx.mp4
if(filePath.startsWith("/mimetype/")){
String trimmedFilePath = filePath.substring("/mimetype/".length());
filePath = trimmedFilePath.substring(trimmedFilePath.indexOf("/"));
}
// Get the video ID from the path
videoId = getVideoIdFromFilePath(filePath, contentResolver);
} else if(scheme.equals("content")){
// If we are given another content:// URI, look it up in the media provider
videoId = Long.valueOf(selectedVideoUri.getLastPathSegment());
filePath = getFilePathFromContentUri(selectedVideoUri, contentResolver);
} else {
Log.d(TAG,"Failed to load URI " + selectedVideoUri.toString());
return false;
}
return true;
}
#7
9
None of these answers worked for me in all cases. I had to go directly to Google's Documentation https://developer.android.com/guide/topics/providers/document-provider.html on this topic and found this useful method:
所有这些答案对我都不起作用。我不得不直接查阅谷歌的文档https://developer.android.com/guide/topics/providers/document-provider.html,找到了这个有用的方法:
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.
您可以使用这个位图在图像视图中显示它。
#8
3
Solution for those, who have problem after moving to KitKat:
对于那些搬到KitKat后出现问题的人,解决方案是:
"This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method" https://*.com/a/20559175/690777
这将从MediaProvider、DownloadsProvider和ExternalStorageProvider获取文件路径,同时返回到非官方的ContentProvider方法“https://*.com/a/20559175/690777”
#9
3
Since managedQuery has been deprecated, you could try:
既然managedQuery已被弃用,您可以尝试:
CursorLoader cursorLoader = new CursorLoader(context, uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
#10
2
Here I am going to show you that how to create a BROWSE button, which when you will click, it will open up the SD card, you will select a File and as a result you will get the file name and file path of the selected one:
在这里,我将向您展示如何创建一个BROWSE按钮,当您点击该按钮时,它将打开SD卡,您将选择一个文件,因此您将获得所选文件的文件名和文件路径:
A button which you will hit
browse.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
startActivityForResult(intent, PICK_REQUEST_CODE);
}
});
The function which will get the Resulted File Name and File Path
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
Uri uri = intent.getData();
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor =getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
Uri filePathUri = Uri.parse(cursor.getString(column_index));
String file_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Toast.makeText(this,"File Name & PATH are:"+file_name+"\n"+file_path, Toast.LENGTH_LONG).show();
}
}
}
}
}
#11
2
After getting an image from the gallery, just pass the URI in the below method only for Android 4.4 (KitKat):
从图库中获取图像后,只需将以下方法中的URI传递给Android 4.4 (KitKat):
public String getPath(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// Where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(
MediaStore.Images.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;
}
#12
2
This solution works for every case:
这个解决方案适用于所有情况:
It is too hard in some cases get the path from the URL. Then why do you need the path? To copy the file in other place? You don't need the path.
在某些情况下,很难从URL获取路径。那你为什么需要这条路呢?将文件复制到其他地方?你不需要路径。
public void SavePhotoUri (Uri imageuri, String Filename){
File FilePath = context.getDir(Environment.DIRECTORY_PICTURES,Context.MODE_PRIVATE);
try {
Bitmap selectedImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageuri);
String destinationImagePath = FilePath + "/" + Filename;
FileOutputStream destination = new FileOutputStream(destinationImagePath);
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, destination);
destination.close();
}
catch (Exception e) {
Log.e("error", e.toString());
}
}
#13
1
Here you get the name of the file
这里是文件的名称
String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
Uri uri = data.getData();
String fileName = null;
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor metaCursor = cr.query(uri,
projection, null, null, null);
if (metaCursor != null) {
try {
if (metaCursor.moveToFirst()) {
fileName = metaCursor.getString(0);
}
} finally {
metaCursor.close();
}
}
#14
1
Simple and easy. You can do this from the URI just like below!
简单和容易。您可以从URI中这样做,如下所示!
public void getContents(Uri uri)
{
Cursor vidCursor = getActivity.getContentResolver().query(uri, null, null,
null, null);
if (vidCursor.moveToFirst())
{
int column_index =
vidCursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Uri filePathUri = Uri.parse(vidCursor .getString(column_index));
String video_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Log.i("TAG", video_name + "\b" file_path);
}
}
#15
0
Slightly modified version of @PercyPercy - it doesn't throw and just returns null if anything goes wrong:
稍微修改过的@PercyPercy版本—它不会抛出,如果出现任何错误,它只返回null:
public String getPathFromMediaUri(Context context, Uri uri) {
String result = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
int col = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (col >= 0 && cursor.moveToFirst())
result = cursor.getString(col);
cursor.close();
return result;
}
#16
0
try this get image file path from Uri
public void getImageFilePath(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String image_id = cursor.getString(0);
image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
cursor.close();
cursor = context.getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
upLoadImageOrLogo(path);
}
#17
-1
Try This
Still, if you are getting the problem to get the real path, you can try my answers. Above answers didn't help me.
不过,如果你想找到问题的真正路径,你可以试试我的答案。以上的回答对我没有帮助。
Explanation:- This method gets the URI and then check the API level of your Android device after that according to API level it will generate the Real path. Code for generating real path method is different according to API levels.
说明:-该方法获取URI,然后根据API级别检查您的Android设备的API级别,然后生成真正的路径。生成真实路径方法的代码根据API级别不同而不同。
-
method to get the Real path from URI
方法从URI获取实际路径
@SuppressLint("ObsoleteSdkInt") public String getPathFromURI(Uri uri){ String realPath=""; // SDK < API11 if (Build.VERSION.SDK_INT < 11) { String[] proj = { MediaStore.Images.Media.DATA }; @SuppressLint("Recycle") Cursor cursor = getContentResolver().query(uri, proj, null, null, null); int column_index = 0; String result=""; if (cursor != null) { column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); realPath=cursor.getString(column_index); } } // SDK >= 11 && SDK < 19 else if (Build.VERSION.SDK_INT < 19){ String[] proj = { MediaStore.Images.Media.DATA }; CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); if(cursor != null){ int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); realPath = cursor.getString(column_index); } } // SDK > 19 (Android 4.4) else{ String wholeID = DocumentsContract.getDocumentId(uri); // Split at colon, use second item in the array String id = wholeID.split(":")[1]; String[] column = { MediaStore.Images.Media.DATA }; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null); int columnIndex = 0; if (cursor != null) { columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { realPath = cursor.getString(columnIndex); } cursor.close(); } } return realPath; }
-
Use this method like this
使用这种方法
Log.e(TAG, "getRealPathFromURI: "+getPathFromURI(your_selected_uri) );
Output:-
输出:
04-06 12:39:46.993 6138-6138/com.app.qtm E/tag: getRealPathFromURI: /storage/emulated/0/Video/avengers_infinity_war_4k_8k-7680x4320.jpg
04-06 12:39:46.993 6138 - 6138 / com.app。qtm E /标签:getRealPathFromURI:/存储/模拟/ 0 /视频/ avengers_infinity_war_4k_8k - 7680 x4320.jpg
#18
-1
Perfectly working for me fixed code from this post:
完美地为我工作固定代码从这篇文章:
public static String getRealPathImageFromUri(Uri uri) {
String fileName =null;
if (uri.getScheme().equals("content")) {
try (Cursor cursor = MyApplication.getInstance().getContentResolver().query(uri, null, null, null, null)) {
if (cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndexOrThrow(ediaStore.Images.Media.DATA));
}
} catch (IllegalArgumentException e) {
Log.e(mTag, "Get path failed", e);
}
}
return fileName;
}
#19
-2
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
位图位图= mediastore . image . media.getbitmap (getContentResolver(), uri));
#1
573
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();
}
}
}
#2
116
Just a simple update on the first answer: mActivity.managedQuery()
is now deprecated. I've updated the code with the new method.
对于第一个答案:mActivity.managedQuery()的简单更新现在已经过时了。我用新方法更新了代码。
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
android开发源
#3
90
Don't try to find a uri in the filesystem, that's slow to go look things up in the database.
不要试图在文件系统中找到uri,在数据库中查找内容是很慢的。
You can get a bitmap from a uri by giving an input stream to the factory like you give a file to the factory:
您可以从uri中获得位图,方法是向工厂提供输入流,就像向工厂提供文件一样:
InputStream is = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
#4
70
For All version I have made this method which get real path from uri
对于所有版本,我都创建了这个方法,它从uri获取真正的路径
@SuppressLint("NewApi")
public static String getFilePath(Context context, Uri uri) throws URISyntaxException {
String selection = null;
String[] selectionArgs = null;
// Uri is different in versions after KITKAT (Android 4.4), we need to
if (Build.VERSION.SDK_INT >= 19 && DocumentsContract.isDocumentUri(context.getApplicationContext(), uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
uri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("image".equals(type)) {
uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{
split[1]
};
}
}
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {
MediaStore.Images.Media.DATA
};
Cursor cursor = null;
try {
cursor = context.getContentResolver()
.query(uri, projection, selection, selectionArgs, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
#5
39
Here it is my example of getting file name, from URI like file://... and content://... . It's works for me not only with Android MediaStore but also with third part application like EzExplorer.
这里是我从URI(比如file:/…)获取文件名的示例。和内容:/ /……它不仅适用于Android MediaStore,也适用于第三部分应用,比如EzExplorer。
public static String getFileNameByUri(Context context, Uri uri)
{
String fileName="unknown";//default fileName
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
filePathUri = Uri.parse(cursor.getString(column_index));
fileName = filePathUri.getLastPathSegment().toString();
}
}
else if (uri.getScheme().compareTo("file")==0)
{
fileName = filePathUri.getLastPathSegment().toString();
}
else
{
fileName = fileName+"_"+filePathUri.getLastPathSegment();
}
return fileName;
}
#6
15
Good existing answers, some of which I used to come up with my own:
好的现有答案,其中一些我以前也有自己的答案:
I have to get the path from URIs and get the URI from paths, and Google has a hard time telling the difference so for anyone who has the same issue (e.g., to get the thumbnail from the MediaStore
of a video whose physical location you already have). The former:
我必须从URI获取路径并从路径获取URI,谷歌很难区分两者的区别,因此对于任何有相同问题的人(例如,从已经有物理位置的视频的MediaStore获取缩略图)。前:
/**
* Gets the corresponding path to a file from the given content:// URI
* @param selectedVideoUri The content:// URI to find the file path from
* @param contentResolver The content resolver to use to perform the query.
* @return the file path as a string
*/
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;
}
The latter (which I do for videos, but can also be used for Audio or Files or other types of stored content by substituting MediaStore.Audio (etc) for MediaStore.Video):
后者(我用于视频,但也可以用于音频或文件或其他类型的存储内容,通过替换MediaStore。音频(MediaStore.Video等)):
/**
* Gets the MediaStore video ID of a given file on external storage
* @param filePath The path (on external storage) of the file to resolve the ID of
* @param contentResolver The content resolver to use to perform the query.
* @return the video ID as a long
*/
private long getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/media (or something like that)
// I pass in "external" because that's the MediaStore's name for the external
// storage on my device (the other possibility is "internal")
Uri videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
Basically, the DATA
column of MediaStore
(or whichever sub-section of it you're querying) stores the file path, so you either use what you know to look up that DATA
field, or use the field to look up whatever else you want.
基本上,MediaStore的数据列(或您正在查询的它的任何子部分)存储文件路径,所以您要么使用您知道的内容来查找数据字段,要么使用字段来查找您想要的其他内容。
I then further use the Scheme
as above to figure out what to do with my data:
然后,我进一步使用上述方案,找出如何处理我的资料:
private boolean getSelectedVideo(Intent imageReturnedIntent, boolean fromData) {
Uri selectedVideoUri;
//Selected image returned from another activity
// A parameter I pass myself to know whether or not I'm being "shared via" or
// whether I'm working internally to my app (fromData = working internally)
if(fromData){
selectedVideoUri = imageReturnedIntent.getData();
} else {
//Selected image returned from SEND intent
// which I register to receive in my manifest
// (so people can "share via" my app)
selectedVideoUri = (Uri)getIntent().getExtras().get(Intent.EXTRA_STREAM);
}
Log.d(TAG,"SelectedVideoUri = " + selectedVideoUri);
String filePath;
String scheme = selectedVideoUri.getScheme();
ContentResolver contentResolver = getContentResolver();
long videoId;
// If we are sent file://something or content://org.openintents.filemanager/mimetype/something...
if(scheme.equals("file") || (scheme.equals("content") && selectedVideoUri.getEncodedAuthority().equals("org.openintents.filemanager"))){
// Get the path
filePath = selectedVideoUri.getPath();
// Trim the path if necessary
// openintents filemanager returns content://org.openintents.filemanager/mimetype//mnt/sdcard/xxxx.mp4
if(filePath.startsWith("/mimetype/")){
String trimmedFilePath = filePath.substring("/mimetype/".length());
filePath = trimmedFilePath.substring(trimmedFilePath.indexOf("/"));
}
// Get the video ID from the path
videoId = getVideoIdFromFilePath(filePath, contentResolver);
} else if(scheme.equals("content")){
// If we are given another content:// URI, look it up in the media provider
videoId = Long.valueOf(selectedVideoUri.getLastPathSegment());
filePath = getFilePathFromContentUri(selectedVideoUri, contentResolver);
} else {
Log.d(TAG,"Failed to load URI " + selectedVideoUri.toString());
return false;
}
return true;
}
#7
9
None of these answers worked for me in all cases. I had to go directly to Google's Documentation https://developer.android.com/guide/topics/providers/document-provider.html on this topic and found this useful method:
所有这些答案对我都不起作用。我不得不直接查阅谷歌的文档https://developer.android.com/guide/topics/providers/document-provider.html,找到了这个有用的方法:
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.
您可以使用这个位图在图像视图中显示它。
#8
3
Solution for those, who have problem after moving to KitKat:
对于那些搬到KitKat后出现问题的人,解决方案是:
"This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method" https://*.com/a/20559175/690777
这将从MediaProvider、DownloadsProvider和ExternalStorageProvider获取文件路径,同时返回到非官方的ContentProvider方法“https://*.com/a/20559175/690777”
#9
3
Since managedQuery has been deprecated, you could try:
既然managedQuery已被弃用,您可以尝试:
CursorLoader cursorLoader = new CursorLoader(context, uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
#10
2
Here I am going to show you that how to create a BROWSE button, which when you will click, it will open up the SD card, you will select a File and as a result you will get the file name and file path of the selected one:
在这里,我将向您展示如何创建一个BROWSE按钮,当您点击该按钮时,它将打开SD卡,您将选择一个文件,因此您将获得所选文件的文件名和文件路径:
A button which you will hit
browse.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
startActivityForResult(intent, PICK_REQUEST_CODE);
}
});
The function which will get the Resulted File Name and File Path
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == PICK_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
Uri uri = intent.getData();
if (uri.getScheme().toString().compareTo("content")==0)
{
Cursor cursor =getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst())
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
Uri filePathUri = Uri.parse(cursor.getString(column_index));
String file_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Toast.makeText(this,"File Name & PATH are:"+file_name+"\n"+file_path, Toast.LENGTH_LONG).show();
}
}
}
}
}
#11
2
After getting an image from the gallery, just pass the URI in the below method only for Android 4.4 (KitKat):
从图库中获取图像后,只需将以下方法中的URI传递给Android 4.4 (KitKat):
public String getPath(Uri contentUri) {// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// Where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().query(
MediaStore.Images.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;
}
#12
2
This solution works for every case:
这个解决方案适用于所有情况:
It is too hard in some cases get the path from the URL. Then why do you need the path? To copy the file in other place? You don't need the path.
在某些情况下,很难从URL获取路径。那你为什么需要这条路呢?将文件复制到其他地方?你不需要路径。
public void SavePhotoUri (Uri imageuri, String Filename){
File FilePath = context.getDir(Environment.DIRECTORY_PICTURES,Context.MODE_PRIVATE);
try {
Bitmap selectedImage = MediaStore.Images.Media.getBitmap(context.getContentResolver(), imageuri);
String destinationImagePath = FilePath + "/" + Filename;
FileOutputStream destination = new FileOutputStream(destinationImagePath);
selectedImage.compress(Bitmap.CompressFormat.JPEG, 100, destination);
destination.close();
}
catch (Exception e) {
Log.e("error", e.toString());
}
}
#13
1
Here you get the name of the file
这里是文件的名称
String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
Uri uri = data.getData();
String fileName = null;
ContentResolver cr = getActivity().getApplicationContext().getContentResolver();
Cursor metaCursor = cr.query(uri,
projection, null, null, null);
if (metaCursor != null) {
try {
if (metaCursor.moveToFirst()) {
fileName = metaCursor.getString(0);
}
} finally {
metaCursor.close();
}
}
#14
1
Simple and easy. You can do this from the URI just like below!
简单和容易。您可以从URI中这样做,如下所示!
public void getContents(Uri uri)
{
Cursor vidCursor = getActivity.getContentResolver().query(uri, null, null,
null, null);
if (vidCursor.moveToFirst())
{
int column_index =
vidCursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Uri filePathUri = Uri.parse(vidCursor .getString(column_index));
String video_name = filePathUri.getLastPathSegment().toString();
String file_path=filePathUri.getPath();
Log.i("TAG", video_name + "\b" file_path);
}
}
#15
0
Slightly modified version of @PercyPercy - it doesn't throw and just returns null if anything goes wrong:
稍微修改过的@PercyPercy版本—它不会抛出,如果出现任何错误,它只返回null:
public String getPathFromMediaUri(Context context, Uri uri) {
String result = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
int col = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (col >= 0 && cursor.moveToFirst())
result = cursor.getString(col);
cursor.close();
return result;
}
#16
0
try this get image file path from Uri
public void getImageFilePath(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String image_id = cursor.getString(0);
image_id = image_id.substring(image_id.lastIndexOf(":") + 1);
cursor.close();
cursor = context.getContentResolver().query(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, MediaStore.Images.Media._ID + " = ? ", new String[]{image_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
upLoadImageOrLogo(path);
}
#17
-1
Try This
Still, if you are getting the problem to get the real path, you can try my answers. Above answers didn't help me.
不过,如果你想找到问题的真正路径,你可以试试我的答案。以上的回答对我没有帮助。
Explanation:- This method gets the URI and then check the API level of your Android device after that according to API level it will generate the Real path. Code for generating real path method is different according to API levels.
说明:-该方法获取URI,然后根据API级别检查您的Android设备的API级别,然后生成真正的路径。生成真实路径方法的代码根据API级别不同而不同。
-
method to get the Real path from URI
方法从URI获取实际路径
@SuppressLint("ObsoleteSdkInt") public String getPathFromURI(Uri uri){ String realPath=""; // SDK < API11 if (Build.VERSION.SDK_INT < 11) { String[] proj = { MediaStore.Images.Media.DATA }; @SuppressLint("Recycle") Cursor cursor = getContentResolver().query(uri, proj, null, null, null); int column_index = 0; String result=""; if (cursor != null) { column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); realPath=cursor.getString(column_index); } } // SDK >= 11 && SDK < 19 else if (Build.VERSION.SDK_INT < 19){ String[] proj = { MediaStore.Images.Media.DATA }; CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); if(cursor != null){ int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); realPath = cursor.getString(column_index); } } // SDK > 19 (Android 4.4) else{ String wholeID = DocumentsContract.getDocumentId(uri); // Split at colon, use second item in the array String id = wholeID.split(":")[1]; String[] column = { MediaStore.Images.Media.DATA }; // where id is equal to String sel = MediaStore.Images.Media._ID + "=?"; Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null); int columnIndex = 0; if (cursor != null) { columnIndex = cursor.getColumnIndex(column[0]); if (cursor.moveToFirst()) { realPath = cursor.getString(columnIndex); } cursor.close(); } } return realPath; }
-
Use this method like this
使用这种方法
Log.e(TAG, "getRealPathFromURI: "+getPathFromURI(your_selected_uri) );
Output:-
输出:
04-06 12:39:46.993 6138-6138/com.app.qtm E/tag: getRealPathFromURI: /storage/emulated/0/Video/avengers_infinity_war_4k_8k-7680x4320.jpg
04-06 12:39:46.993 6138 - 6138 / com.app。qtm E /标签:getRealPathFromURI:/存储/模拟/ 0 /视频/ avengers_infinity_war_4k_8k - 7680 x4320.jpg
#18
-1
Perfectly working for me fixed code from this post:
完美地为我工作固定代码从这篇文章:
public static String getRealPathImageFromUri(Uri uri) {
String fileName =null;
if (uri.getScheme().equals("content")) {
try (Cursor cursor = MyApplication.getInstance().getContentResolver().query(uri, null, null, null, null)) {
if (cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndexOrThrow(ediaStore.Images.Media.DATA));
}
} catch (IllegalArgumentException e) {
Log.e(mTag, "Get path failed", e);
}
}
return fileName;
}
#19
-2
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
位图位图= mediastore . image . media.getbitmap (getContentResolver(), uri));