从galary /文件管理器获取选定的文件路径

时间:2014-03-21 05:35:09

标签: android android-intent onactivityresult

我正在尝试获取所选文件的路径,但它没有回复我....这是我正在尝试的代码,但我无法弄清楚问题

  public void getPic() {


         Intent intent = new Intent();
         intent.setType("image/*");
         intent.setAction(Intent.ACTION_GET_CONTENT);
         startActivityForResult(Intent.createChooser(intent,
                 "Select Picture"), SELECT_PICTURE);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);

                Log.v("IMAGE PATH====>>>> ",selectedImagePath);
            }
        }
    }
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

2 个答案:

答案 0 :(得分:0)

尝试使用此代码获取路径。

 Uri chosenImageUri = data.getData(); 
//                      mImageCaptureUri=chosenImageUri;
                        try 
                        {

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize=4;
                options.inScaled=false;
                BitmapmBitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(chosenImageUri),null,options);
                options.inPurgeable = true;
                System.runFinalization();
                Runtime.getRuntime().gc();
                System.gc();

                String chosenstring=chosenImageUri+"";
                if(chosenstring.contains("content://"))
                {                      
                path=getRealPathFromURI(chosenImageUri);
                }
                else if (chosenstring.contains("file:///"))
                {
                String[] splitval=chosenstring.split("//");
                path=splitval[1];       

    }

答案 1 :(得分:0)

在getPath()函数中进行更改,如下所示

public String getPath(Uri uri) {

        Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

希望这会对你有所帮助.. :)