Open file from Uri, independent of location in android

Go To StackoverFlow.com

3

I could use some help understanding how to open files in android. My specific problem has to do with opening an image file. In my application the user takes an image with a camera app of their choosing and then I operate on the image that is returned. Depending on the phone, version of android, and the camera app chosen, I get different parameters returned in onActivityResult. Sometimes I get a URI, sometimes just an image, and sometimes both.

The code for launching the camera is:

Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_IMAGE); 

I then receive the result as:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_IMAGE && resultCode == Activity.RESULT_OK) {
        Log.d(TAG,"In onActivityResult");
        Bitmap imageBmp = null;
        Uri imageUri = data.getData();

        if (data.getExtras() != null) {
        imageBmp = (Bitmap)data.getExtras().get("data");
        Log.d(TAG,"Got Bitmap");
        }
        ...
    }
}

My problem arises when I get a URI but not an image. If imageBmp is null then I need to load the image from the URI. I've tested this out several device/app combinations. Sometimes the URI is on the internal storage and other times on the SD card. If the file is on the SD card then I've used managedQuery to get the file.

String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(imageUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);                        
cursor.moveToFirst();
imageFileName = cursor.getString(column_index);  
File imageFile = new File(imageFileName);
...

If it's on the internal storage, then I get a FileNotFoundException.

My specific question is: How do I modify this to open a file independent of where it is on the file system, only knowing the URI? I would like to do something like:

File imageFile = new File(imageUri);

but File doesn't accept a Uri object. I do the managed query to convert it to a String.

My more general question is why do I need to do the query in the first place? Why can't I just use the URI that is returned?

2012-04-05 01:31
by John Sallay


8

You will have to use a contentResolver to access internal files passed as uri

ContentResolver cr = getContentResolver();
InputStream is = cr.openInputStream(imageUri);
2012-09-13 04:59
by nandeesh


0

You doing all right. You have file name. Just open it. That's it.

2012-04-05 02:37
by Alex
I edited the question to show that I'm only successful with this approach when the file is on the external storage. Sometimes the Uri points to the internal storage and I fail to find the file - John Sallay 2012-04-05 12:43
Ads