Skip to content Skip to sidebar Skip to footer

App Crashes When Loading Image From Gallery

In my app ,i have two buttons ,one for loading the image from gallery(from device )and another one for taking pictures by accesing the camera of the device,My code is working prope

Solution 1:

I'm not sure but... maybe on some device this "EXTERNAL_CONTENT_URI" doesn't work because there's no external storage?

Solution 2:

This is issue in Lollypop+ devices so we have to write 2 logic to process LoolyPop below & above android versions to process the gallery Image.

Starting Gallery Image Picker Intent,

Intentintent=newIntent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        mContext.startActivityForResult(
                Intent.createChooser(intent, "Complete action using"),
                DigitalCareContants.IMAGE_PICK);

Process the Image,

  • Method to receive Image Path :

    privatestatic String getPath(final Context context, final Uri uri) {
    
    finalbooleanisKitKat= Build.VERSION.SDK_INT >= 19;
    
    
    if (isKitKat && DocumentsContract.isDocumentUri(uri)) {
    
        if (isExternalStorageDocument(uri)) {
            finalStringdocId= DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            finalStringtype= split[0];
    
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/"
                        + split[1];
            }
        }
    
        elseif (isDownloadsDocument(uri)) {
    
            finalStringid= DocumentsContract.getDocumentId(uri);
            longmId= Long.parseLong(id);
            UrimUri= Uri.parse("content://downloads/public_downloads");
            finalUricontentUri= ContentUris.withAppendedId(mUri, mId);
    
            return getDataColumn(context, contentUri, null, null);
        }
    
        elseif (isMediaDocument(uri)) {
            finalStringdocId= DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            finalStringtype= split[0];
    
            UricontentUri=null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } elseif ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } elseif ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
    
            finalStringselection="_id=?";
            final String[] selectionArgs = newString[] { split[1] };
    
            return getDataColumn(context, contentUri, selection,
                    selectionArgs);
        }
    }
    
    elseif ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    
    elseif ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    
    returnnull;}
    }
    
  • Received Gallery picker intent Processing :

    if(requestcode == 1000)
        {
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        UriselectedImage= data.getData();
    
        if (Build.VERSION.SDK_INT >= 19) {
            InputStream input;
            Bitmap bitmap;
            StringpicturePath= getPath(mActivity, selectedImage);
            try {
                input = mActivity.getContentResolver().openInputStream(
                        selectedImage);
                bitmap = BitmapFactory.decodeStream(input);
                Log.d("IMAGE", "Received Image Bitmap : " + bitmap);
                Log.d("IMAGE", "Received Image Bitmap Path : " + picturePath);
            } catch (FileNotFoundException e1) {
    
            }
        } else {
            Log.d(TAG, "Android Version is 18 below");
            Cursorcursor= mActivity.getContentResolver().query(
                    selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
    
            intcolumnIndex= cursor.getColumnIndex(filePathColumn[0]);
            StringpicturePath= cursor.getString(columnIndex);
            Log.d("IMAGE", "Received Image Bitmap Path : " + picturePath);
            BitmapFactory.Optionsoptions=newBitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            Bitmapbitmap= BitmapFactory.decodeFile(picturePath, options);
            Log.d("IMAGE", "Received Image Bitmap : " + bitmap);
            Log.d("IMAGE", "Received Image Bitmap Path : " + picturePath);
            cursor.close();
        }
        }       
    

    - Note: Please make sure to add below class in your package. It has been copied from the Lollypop open source code.

    publicclassDocumentsContract{
      privatestaticfinalString DOCUMENT_URIS =
    "com.android.providers.media.documents " +
    "com.android.externalstorage.documents " +
    "com.android.providers.downloads.documents " +
    "com.android.providers.media.documents";
    
    privatestaticfinalString PATH_DOCUMENT = "document";
    privatestaticfinalString TAG = DocumentsContract.class.getSimpleName();
    
    publicstaticString getDocumentId(Uri documentUri) {
    finalList<String> paths = documentUri.getPathSegments();
    if (paths.size() < 2) {
        thrownew IllegalArgumentException("Not a document: " + documentUri);
    }
    
    if (!PATH_DOCUMENT.equals(paths.get(0))) {
        thrownew IllegalArgumentException("Not a document: " + documentUri);
    }
    return paths.get(1);
    }
    
    publicstaticboolean isDocumentUri(Uri uri) {
    finalList<String> paths = uri.getPathSegments();
    Log.d(TAG, "paths[" + paths + "]");
    if (paths.size() < 2) {
        returnfalse;
    }
    if (!PATH_DOCUMENT.equals(paths.get(0))) {
        returnfalse;
    }
    return DOCUMENT_URIS.contains(uri.getAuthority());
    }
    }
    

Post a Comment for "App Crashes When Loading Image From Gallery"