Android - 用于获取文件路径的startActivityForResult

时间:2013-12-27 11:59:57

标签: java android file uri

我正在为Android编写一个简单的图像查看器。我的应用程序有“从图库打开文件”按钮。因此,当我从Gallery中选择图像时,它必须将文件路径返回到我的应用程序中,但它会返回一个奇怪的Uri,看起来像content://media/storage/2ch/30128

如何从这个Uri获取绝对文件路径? 这是启动Gallery的一些代码:


    Intent i = new Intent();
    i.setType("image/*");
    i.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(i, "Выберите файл"), PICTURE_REQUEST_CODE);

P.S。我的英语借口

3 个答案:

答案 0 :(得分:3)

使用此代码

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

   super.onActivityResult(requestCode, resultCode, data); 
   if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data){

      Uri selectedImage = data.getData();
      String[] filePathColumn = { MediaStore.Images.Media.DATA };
      Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
      cursor.moveToFirst();
      int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
      String picturePath = cursor.getString(columnIndex);
      cursor.close();
}

答案 1 :(得分:0)

您还可以使用URI获取图片:

试试这个

try {
            Uri selectedImage = selectedImageUri;
            //getContentResolver().notifyChange(selectedImage, null);
            ContentResolver cr = getContentResolver();
            Bitmap bitmap;
            bitmap = android.provider.MediaStore.Images.Media
                    .getBitmap(cr, selectedImage);
            rptImage.setImageBitmap(bitmap);

        } catch (Exception e) {
            Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                    .show();
            Log.e("Camera", e.toString());
        }

或者只是这个:

尝试:

ImageView.setImageUri(Uri.fromFile(new File("/sdcard/cats.jpg")));

或者用:

ImageView.setImageUri(Uri.parse(new File("/sdcard/cats.jpg").toString()));

答案 2 :(得分:0)

尝试以下代码

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_FILE && resultCode == Activity.RESULT_OK) {

   Uri mImageCaptureUri = data.getData(); 
   String [] proj       = {MediaStore.Images.Media.DATA};
   Cursor cursor        = managedQuery( contentUri, proj, null, null,null);
   if (cursor != null){
        int column_index    = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String path = cursor.getString(column_index);
   }
}


}

此处变量路径将返回所选图像的路径。