android: cannot load external pictures [solved]

I’ve lost several hours trying to find out why I could not load picture based on filePath returned by the gallery app.

It happens that this filePath is not the correct one! (ie. the one in the file system!!!).

You have to decode it as follows.

First let’s see fake-path versus real path:

* Called when user picked an image via pict-browser
protected void onActivityResult(int requestCode, int resultCode, Intent data){
  switch (requestCode) {
      if (resultCode == RESULT_OK && data != null && data.getData() != null) {
        String filePath = data.getData().getPath(); //WARNING: this is NOT your real path (in my case, value is set to "/external/images/media/4"
        String realPath = this.getPath(data.getData()); //WARNING: this IS your real path (in my case, value is set to "/mnt/sdcard/DCIM/Camera/IMG_20111016_112607.jpg"
        (new File(filePath).exists(); // return false - file does NOT exist
        (new File(realPath).exists(); // return true - file DOES exist

Note that _PICK_FILE_RESULT_CODE is a value defined by you and can be any integer. It has no specific effect on this code. Read android doc for more information.

Now it is time to see the function that turns the fake-path into the real-path, in our case it’s the method getPath():

* Return real file path based on fake-filePath value returned by galllery
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);
  return cursor.getString(column_index);

That’s it!
You can know freely manipulate images.


Post a Comment

Your email is never published nor shared. You're allow to say what you want...