androidurigalleryandroid-cursor

Not able to select few photos from Gallery in Android


I'am invoking default gallery app from my app to select any photo. Below is my code to get the selected image path from gallery. It's working fine for all the photos except few. When i select any of PICASA uploaded photos from Gallery, app is force closing. Please help me.


Inside onActivityResult()....

            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 selectedPhotoPath = cursor.getString(columnIndex).trim();  <<--- NullPointerException here
            cursor.close(); 
            bitmap = BitmapFactory.decodeFile(selectedPhotoPath);
            ......      

Solution

  • Sometimes data.getData(); returns null depending on the app you use to get the picture. A workaround for this is to use the above code in onActivityResult:

    /**
    *Retrieves the path of the image that was chosen from the intent of getting photos from the galery
    */
    Uri selectedImageUri = data.getData();
    
    // OI FILE Manager
    String filemanagerstring = selectedImageUri.getPath();
    
    // MEDIA GALLERY
    String filename = getImagePath(selectedImageUri);
    
    String chosenPath;
    
    if (filename != null) {
    
       chosenPath = filename;
    } else {
    
       chosenPath = filemanagerstring;
    }
    

    The variable chosenPath will have the correct path of the chosen image. The method getImagePath() is this:

    public String getImagePath(Uri uri) {
        String selectedImagePath;
        // 1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            selectedImagePath = cursor.getString(column_index);
        } else {
            selectedImagePath = null;
        }
    
        if (selectedImagePath == null) {
            // 2:OI FILE Manager --- call method: uri.getPath()
            selectedImagePath = uri.getPath();
        }
        return selectedImagePath;
    }