获得从URI文件路径 [英] Get file path from URI
问题描述
我的URI的图像文件。
我用这个code从乌里获取文件的路径:
公共字符串getRealPathFromURI(URI contentUri){
光标光标= NULL;
尝试 {
的String []凸出= {MediaStore.Images.Media.DATA};
光标= mContext.getContentResolver()查询(contentUri,凸出,NULL,NULL,NULL);
INT与Column_Index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
返回cursor.getString(Column_Index中);
}赶上(例外五){
Log.message(e.getMessage());
} 最后 {
如果(光标!= NULL){
cursor.close();
}
}
返回null;
}
如果我从画廊的应用程序选择的图像(的Android 4.4.2,臂动车组),uri.getPath = /外部/图片/媒体/ 16和它的工作的罚款(我的文件路径:/存储/ SD卡/下载/ 0_cf15a_7800a7e5_orig .JPG)
如果我选择文件的应用程序图像(安卓4.4.2,臂动车组),我有uri.getPath = /文档/图片:16和功能getRealPathFromURI返回null
。我怎样才能回到正确的文件进行boths操作路径?
$ C $下选择文件:
@覆盖
公共无效的onClick(视图v){
最终文件的根=新的文件(Environment.getExternalStorageDirectory()+文件分割符+Photohunt+文件分割符);
root.mkdirs();
最后弦乐FNAME = Common.getUniqueImageFilename();
最终文件sdImageMainDirectory =新的文件(根,FNAME);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// 相机。
最后的名单,其中,意图> cameraIntents =新的ArrayList<意图>();
最终意图captureIntent =新的意图(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
最终PackageManager packageManager = mContext.getPackageManager();
最后的名单,其中,ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent,0);
对于(ResolveInfo RES:listCam){
最后弦乐的packageName = res.activityInfo.packageName;
最终意向意图=新的意图(captureIntent);
intent.setComponent(新的组件名(res.activityInfo.packageName,res.activityInfo.name));
intent.setPackage(的packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT,outputFileUri);
cameraIntents.add(意向);
}
// 文件系统。
最终意图galleryIntent =新意图();
galleryIntent.setType(图像/ *);
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
//的文件系统选项选择器。
最终意图chooserIntent = Intent.createChooser(galleryIntent,选择源);
//添加摄像头的选项。
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,cameraIntents.toArray(新Parcelable [] {}));
startActivityForResult(chooserIntent,PICTURE_REQUEST_ code);
}
拉手活动的结果:
@覆盖
公共无效onActivityResult(INT申请code,INT结果code,意图数据)
{
如果(结果code == Activity.RESULT_OK)
{
如果(要求code == PICTURE_REQUEST_ code)
{
最终布尔isCamera;
如果(数据== NULL)
{
isCamera = TRUE;
}
其他
{
最后弦乐行动= data.getAction();
如果(动作== NULL)
{
isCamera = FALSE;
}
其他
{
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
乌里selectedImageUri;
如果(isCamera)
{
selectedImageUri = outputFileUri;
}
其他
{
selectedImageUri =数据== NULL?空:data.getData();
}
Log.variable(URI,selectedImageUri.getPath());
ConfirmImageFragment片段=新ConfirmImageFragment(selectedImageUri,mContestId);
FragmentTransaction交易= getSherlockActivity()getSupportFragmentManager()的BeginTransaction()。
transaction.replace(R.id.main_container,片段);
transaction.addToBackStack(空);
器transaction.commit();
}
}
super.onActivityResult(要求code,因此code,数据);
}
加载所选文件到ImageView的正常工作,这两个国家:
私人无效的LoadImage(){
尝试 {
点阵位图= MediaStore.Images.Media.getBitmap(mContext.getContentResolver(),穆里);
mImage.setImageBitmap(位);
}赶上(FileNotFoundException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}赶上(IOException异常E){
// TODO自动生成的catch块
e.printStackTrace();
}
}
解决方法:
公共类RealPathUtil {
@燮pressLint(NewApi)
公共静态字符串getRealPathFromURI_API19(上下文的背景下,开放的URI){
字符串文件路径=;
串wholeID = DocumentsContract.getDocumentId(URI);
//分割在结肠,使用数组中的第二项
串的id = wholeID.split(:)[1];
字符串[]列= {MediaStore.Images.Media.DATA};
//其中id等于
字符串SEL = MediaStore.Images.Media._ID +=;
光标光标= context.getContentResolver()查询(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
列,SEL,新的String [] {ID},NULL);
INT参数:columnIndex = cursor.getColumnIndex(列[0]);
如果(cursor.moveToFirst()){
文件路径= cursor.getString(参数:columnIndex);
}
cursor.close();
返回文件路径;
}
@燮pressLint(NewApi)
公共静态字符串getRealPathFromURI_API11to18(上下文的背景下,乌里contentUri){
的String []凸出= {MediaStore.Images.Media.DATA};
字符串结果= NULL;
CursorLoader cursorLoader =新CursorLoader(
的背景下,
contentUri,凸出,NULL,NULL,NULL);
光标光标= cursorLoader.loadInBackground();
如果(光标!= NULL){
INT与Column_Index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
结果= cursor.getString(Column_Index中);
}
返回结果;
}
公共静态字符串getRealPathFromURI_BelowAPI11(上下文的背景下,乌里contentUri){
的String []凸出= {MediaStore.Images.Media.DATA};
光标光标= context.getContentResolver()查询(contentUri,凸出,NULL,NULL,NULL);
INT与Column_Index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
返回cursor.getString(Column_Index中);
}
}
<一个href="http://hmk$c$c.com/android-display-selected-image-and-its-real-path/">http://hmk$c$c.com/android-display-selected-image-and-its-real-path/
I have Uri for Image file.
I use this code for gets file path from Uri:
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = mContext.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) {
Log.message(e.getMessage());
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
If I choose image from Gallery app(Android 4.4.2, arm-emu), uri.getPath = /external/images/media/16 and it work's fine (My file path: /storage/sdcard/Download/0_cf15a_7800a7e5_orig.jpg)
If I choose image from Documents app(Android 4.4.2, arm-emu), I have uri.getPath = /document/image:16 and function getRealPathFromURI returns null.
How I can return correct path to file for boths action?
Code for choosing file:
@Override
public void onClick(View v) {
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "Photohunt" + File.separator);
root.mkdirs();
final String fname = Common.getUniqueImageFilename();
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = mContext.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, PICTURE_REQUEST_CODE);
}
Handle activity result:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == Activity.RESULT_OK)
{
if(requestCode == PICTURE_REQUEST_CODE)
{
final boolean isCamera;
if(data == null)
{
isCamera = true;
}
else
{
final String action = data.getAction();
if(action == null)
{
isCamera = false;
}
else
{
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if(isCamera)
{
selectedImageUri = outputFileUri;
}
else
{
selectedImageUri = data == null ? null : data.getData();
}
Log.variable("uri", selectedImageUri.getPath());
ConfirmImageFragment fragment = new ConfirmImageFragment(selectedImageUri, mContestId);
FragmentTransaction transaction = getSherlockActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.main_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Loading selected file into ImageView works fine for both state:
private void loadImage() {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), mUri);
mImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Solution:
public class RealPathUtil {
@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
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 = context.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();
return filePath;
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor 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);
}
}
http://hmkcode.com/android-display-selected-image-and-its-real-path/
这篇关于获得从URI文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!