androidgalleryrecent-file-list

Android app getting crash when select image from Recent images from gallery


My app work perfectly when select image from Pictures or images categories in Gallery but app getting crash when select image from recent images

This is my intent call

galleryLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (EasyPermissions.hasPermissions(getActivity(), perms_gallery)) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
            }else {
                EasyPermissions.requestPermissions(getActivity(), getString(R.string.read_file),
                        READ_REQUEST_CODE, perms_gallery);
            }
        }
    });

Crash happen from here String id = wholeID.split(":")[1];

public String getPathFromUriGallery(Context context, Uri uri) {
    Cursor cursor = null;
    try {
        String wholeID = DocumentsContract.getDocumentId(uri);
        String id = wholeID.split(":")[1];
        String sel = MediaStore.Images.Media._ID + "=?";

        String[] filePath = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePath, sel, new String[]{id}, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePath[0]);
        return  cursor.getString(columnIndex);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

this my error log

Process: io.test.susitkMed.doctor, PID: 9576
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://com.google.android.apps.docs.storage/document/acc=3;doc=encoded=0ajgvv25pDn5wcNiiiv1YFYu7neaIdrulcWk/kBdEa8TqupNEKLhnLzz flg=0x1 launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 } }} to activity {io.test.susitkMed.doctor/io.test.susitkMed.doctor.ui.activities.MainActivity}: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
    at android.app.ActivityThread.-wrap22(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
 Caused by: java.lang.ArrayIndexOutOfBoundsException: length=1; index=1

Solution

  • I found this solution from this github sample https://github.com/maayyaannkk/ImagePicker

    This is the solution for above issue

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == PICK_IMAGE && resultCode == RESULT_OK
                && null != data) {
    
            Uri selectedImage = data.getData();
            String   imageEncoded = getRealPathFromURI(getActivity(), selectedImageUri);
            Bitmap selectedImage = BitmapFactory.decodeFile(imageString);
            image.setImageBitmap(selectedImage);
        }
    }
    

    These method use for get image url

    public String getRealPathFromURI(Context context, Uri contentUri) {
        OutputStream out;
        File file = new File(getFilename(context));
    
        try {
            if (file.createNewFile()) {
                InputStream iStream = context != null ? context.getContentResolver().openInputStream(contentUri) : context.getContentResolver().openInputStream(contentUri);
                byte[] inputData = getBytes(iStream);
                out = new FileOutputStream(file);
                out.write(inputData);
                out.close();
                return file.getAbsolutePath();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
    
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }
        return byteBuffer.toByteArray();
    }
    
    private String getFilename(Context context) {
        File mediaStorageDir = new File(context.getExternalFilesDir(""), "patient_data");
        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            mediaStorageDir.mkdirs();
        }
    
        String mImageName = "IMG_" + String.valueOf(System.currentTimeMillis()) + ".png";
        return mediaStorageDir.getAbsolutePath() + "/" + mImageName;
    
    }