1

I have 2 option to set an image, either by choosing it from gallery or by capturing it.

When user chooses image from gallery, it return a clank ImageView and when the user try to set image after capturing it, the app crashes giving following error: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.abc.xyz/com.abc.xyz.Activity}: java.lang.NullPointerException: uri

Here's how I'm launching the chooser:

protected DialogInterface.OnClickListener mDialogListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int position) {
            switch (position) {
                case 0: // Take picture
                    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
                    break;
                case 1: // Choose picture
                    Intent choosePhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    choosePhotoIntent.setType("image/*");
                    startActivityForResult(choosePhotoIntent, PICK_PHOTO_REQUEST);
                    break;
            }
        }
    };

Here's how I'm setting the image to the ImageView:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {

            if (requestCode == PICK_PHOTO_REQUEST || requestCode == TAKE_PHOTO_REQUEST) {
                if (data == null) {
                    // display an error
                    return;
                }
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // error on the line below
                Cursor cursor = this.getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                //
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();

                Picasso.with(this)
                        .load(picturePath)
                        .into(hPic);
                hPicTag.setVisibility(View.INVISIBLE);
            }

        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(getBaseContext(), "Something went wrong!", Toast.LENGTH_LONG).show();
        }

    }

Please let me know what is wrong here.

Sorry for bad formatting of the question. I'm still a beginner here.

Hammad Nasir
  • 2,889
  • 7
  • 52
  • 133

2 Answers2

4

The way to obtain path is different is certain Android versions. I use the following Util class for this purpose.

public class RealPathUtil {

    @SuppressLint("NewApi")
    public static String getRealPathFromURI_API20(Context context, Uri uri){
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = { MediaStore.Images.Media.DATA };

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{ id }, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        }
        cursor.close();
        return filePath;
    }


    public static String getRealPathFromURI_API11to19(Context context, Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        String result = null;

        if(Looper.myLooper() == null) {
            Looper.prepare();
        }
        CursorLoader cursorLoader = new CursorLoader(
                context,
                contentUri, proj, null, null, null);
        Cursor cursor = cursorLoader.loadInBackground();

        if(cursor != null){
            int column_index =
                    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            result = cursor.getString(column_index);
        } else {
            result = contentUri.getPath();
        }
        return result;
    }

    public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index
                = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
}

Now based on the device's OS version call appropriate methods as:

if (Build.VERSION.SDK_INT < 11) {
    RealPathUtil.getRealPathFromURI_BelowAPI11(...);
} else if(Build.VERSION.SDK_INT >= 11 && <= 19) {
    RealPathUtil.getRealPathFromURI_API11to19(...);
} else if(Build.VERSION.SDK_INT > 19){
    RealPathUtil.getRealPathFromURI_API20(...);
}
camelCaseCoder
  • 1,447
  • 19
  • 32
  • i implemented this and getting error on String wholeID = DocumentsContract.getDocumentId(uri); Error msg---Attempt to invoke virtual method 'java.util.List android.net.Uri.getPathSegments()' on a null object reference – Ahsan Jun 30 '17 at 02:20
0

Try like this. This will surely help you...Tested....

  final String[] items = new String[]{"Camera", "Gallery"};            
            new AlertDialog.Builder(getActivity()).setTitle("Select Picture")
                    .setAdapter(adapter, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            if (items[item].equals("Camera")) {

                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    startActivityForResult(intent, REQUEST_CAMERA);


                            } else if (items[item].equals("Gallery")) {
                                if (Build.VERSION.SDK_INT <= 19) {
                                    Intent intent = new Intent();
                                    intent.setType("image/*");
                                    intent.setAction(Intent.ACTION_GET_CONTENT);
                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                                } else if (Build.VERSION.SDK_INT > 19) {
                                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
                                }
                            }
                        }
                    }).show();

        }


        // get result after selecting image from Gallery
        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == PICK_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
                Uri selectedImageUri = data.getData();
                String selectedImagePath = getRealPathFromURIForGallery(selectedImageUri);
                decodeFile(selectedImagePath);
            } else if (requestCode == REQUEST_CAMERA && resultCode == getActivity().RESULT_OK && null != data) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                profileImage.setImageBitmap(photo);

                // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                Uri tempUri = getImageUri(getActivity().getApplicationContext(), photo);

                // CALL THIS METHOD TO GET THE ACTUAL PATH
                File finalFile = new File(getRealPathFromURI(tempUri));
                decodeFile(finalFile.toString());
            }
        }

        public String getRealPathFromURIForGallery(Uri uri) {
            if (uri == null) {
                return null;
            }
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
            if (cursor != null) {
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
            return uri.getPath();
        }

        public Uri getImageUri(Context inContext, Bitmap inImage) {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
            return Uri.parse(path);
        }

        public String getRealPathFromURI(Uri uri) {
            Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            return cursor.getString(idx);
        }


        // decode image
        public void decodeFile(String filePath) {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, o);
            // The new size we want to scale to
            final int REQUIRED_SIZE = 1024;
            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bitmap = BitmapFactory.decodeFile(filePath, o2);
            Security connection = new Security(context);
            Boolean isInternetPresent = connection.isConnectingToInternet(); // true or false
            if (isInternetPresent) {
                // submit usr information to server
                //first upload file
                updateUserProfileImage();
                Log.i("IMAGEPATH", "" + imagePath);
            }
            profileImageView.setImageBitmap(bitmap);
        }
Saurabh Vardani
  • 1,821
  • 2
  • 18
  • 33