当前位置: 动力学知识库 > 问答 > 编程问答 >

android - cant get file path from URI

问题描述:

I am trying to open a intent that lets me choose a file. Im able to select a file but when I try creating a file with the Uri I got in the OnActivityResult method I get a file size of 0. I dont think Im getting the right file path.

 File file = new File(Environment.getExternalStorageDirectory().getPath()+"/TESTAPP4");

Intent intent = new Intent();

intent.setAction(Intent.ACTION_GET_CONTENT);

Uri data = Uri.fromFile(file);

String type = "*/*";

intent.setDataAndType(data, type);

startActivityForResult(intent, 12);

onActivityResult:

 Uri u= data.getData();

File file = new File( u.getpath);

file.length() // give 0

网友答案:
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();
    }
  }
}

Get filename and path from uri from mediastore

分享给朋友:
您可能感兴趣的文章:
随机阅读: