Getting an image from gallery and camera (Android Studio)

I am working on an project where the user can change their profile picture either by taking a picture or selecting an image from Gallery. Despite following multiple tutorials, the code they use does not work for me. Whenever I select Camera on the Dialog Box, it goes to Gallery then Camera. Likewise when I select Gallery on the Dialog Box, it does go to Gallery but it will still go to Camera before displaying the image on the Image View. Is it because I am using Android Lollipop? I am not really sure too.

How can I get this fixed?

package com.example.user.imagestuff;    
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
     String[] Items;
     ImageView mImageView;
     Button mButton;
     final int bmpHeight = 160;
     final int bmpWidth = 160;
     static final int CAMERA_CODE = 1;
     static final int GALLERY_CODE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mImageView = (ImageView) findViewById(R.id.mImageView);
    mButton = (Button) findViewById(R.id.mButton);
    Items = getResources().getStringArray(R.array.DialogItems);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ImageOnClick(v);
        }
    });
}

public void ImageOnClick(View v) {
    Log.i("OnClick","True");
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle(R.string.AlertTitle);
    builder.setItems(Items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            for(int i=0; i < Items.length; i++){
                if (Items[i].equals("Camera")){
                    Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if(CameraIntent.resolveActivity(getPackageManager()) != null){
                        startActivityForResult(CameraIntent, CAMERA_CODE);
                    }

                }else if (Items[i].equals("Gallery")){
                    Log.i("GalleryCode",""+GALLERY_CODE);
                    Intent GalleryIntent = null;
                    GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    GalleryIntent.setType("image/*");
                    GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(GalleryIntent,GALLERY_CODE);
                }
            }
        }
    });
    builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK){
        switch(requestCode){
            case 1:
                Log.i("CameraCode",""+CAMERA_CODE);
                Bundle bundle = data.getExtras();
                Bitmap bmp = (Bitmap) bundle.get("data");
                Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
                mImageView.setImageBitmap(resized);

            case 0:
                Log.i("GalleryCode",""+requestCode);
                Uri ImageURI = data.getData();
                mImageView.setImageURI(ImageURI);
        }


    }
}

}

5 answers

  • answered 2018-04-17 05:10 Fazal Hussain

    You are opening an intent in for loop and there is another mistake is you are not breaking the case in your switch case. Use break in your switch case

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            switch(requestCode){
                case 1:
                    Log.i("CameraCode",""+CAMERA_CODE);
                    Bundle bundle = data.getExtras();
                    Bitmap bmp = (Bitmap) bundle.get("data");
                    Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth,bmpHeight, true);
                    mImageView.setImageBitmap(resized);
                    break;
    
                case 0:
                    Log.i("GalleryCode",""+requestCode);
                    Uri ImageURI = data.getData();
                    mImageView.setImageURI(ImageURI);
                    break;
            }
    
    
        }
    

  • answered 2018-04-17 05:10 vikas singh

    Because you are using for loop for checking Camera and Gallary Strings. You need to remove for loop and try ike below code

    And also you missing break in your swith case

    final CharSequence[] items = {"Camera", "Gallery"}
    
    
                    if (items[item].equals("Camera")){
                        Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        if(CameraIntent.resolveActivity(getPackageManager()) != null){
                            startActivityForResult(CameraIntent, CAMERA_CODE);
                        }
    
                    }else if (items[item].equals("Gallery")){
                        Log.i("GalleryCode",""+GALLERY_CODE);
                        Intent GalleryIntent = null;
                        GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        GalleryIntent.setType("image/*");
                        GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(GalleryIntent,GALLERY_CODE);
                    }
    

    Second Option

    You can also put break; keyword for breaking your for loop when your condition match

  • answered 2018-04-17 05:10 Rishabh Saxena

    This works fine for me.

    public static final int CAMERA_PERMISSION =100;
    public static final int REQUEST_IMAGE_CAPTURE =101;
    public static final int READ_STORAGE_PERMISSION =102;
    public static final int REQUEST_IMAGE_PICK =103 ;
    private Dialog mCameraDialog;
    private Uri mImageURI;
    
    /**
     * Method to show list dialog to choose photo form gallery or camera.
     */
    private void showChoosePhotoDialog() {
        mCameraDialog.setContentView(R.layout.dialog_choose_photo);
        if(mCameraDialog.getWindow()!=null)
            mCameraDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mCameraDialog.findViewById(R.id.camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCameraDialog.dismiss();
                onCameraOptionSelected();
            }
        });
        mCameraDialog.findViewById(R.id.gallery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCameraDialog.dismiss();
                onGalleryOptionSelected();
            }
        });
        mCameraDialog.show();
    }
    
    /**
     * Method to open gallery.
     */
    private void onGalleryOptionSelected() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intentGallery, REQUEST_IMAGE_PICK);
            overridePendingTransition(R.anim.push_left_right, R.anim.push_right_left);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    READ_STORAGE_PERMISSION);
        }
    }
    
    /**
     * Method to open chooser.
     */
    private void onCameraOptionSelected() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                            CAMERA_PERMISSION);
                } else {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION);
                }
            } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        CAMERA_PERMISSION);
    
            } else {
                mImageURI = Uri.parse(AppUtils.getFilename());
                startActivityForResult(AppUtils.getCameraChooserIntent(EditProfileActivity.this, mImageURI + ""),
                        REQUEST_IMAGE_CAPTURE);
            }
        } else {
            mImageURI = Uri.parse(AppUtils.getFilename());
            startActivityForResult(AppUtils.getCameraChooserIntent(this, mImageURI + ""),
                    REQUEST_IMAGE_CAPTURE);
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    
        switch (requestCode) {
            case CAMERA_PERMISSION:
                int j = 0;
                for (int grantResult : grantResults) {
                    if (grantResult != PackageManager.PERMISSION_GRANTED)
                        j = 1;
                }
                if (j == 1) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) || (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.CAMERA))) {
                        //           Toast.makeText(this, R.string.s_camera_permission, Toast.LENGTH_SHORT).show();
                    } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) || !ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.CAMERA)) {
                        // Open phone settings page. 
                        //         Toast.makeText(this, getString(R.string.s_app_needs_camera_permission), Toast.LENGTH_SHORT).show();
                    }
                } else
                    onCameraOptionSelected();
                break;
    
            case READ_STORAGE_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    onGalleryOptionSelected();
                else if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    //             Toast.makeText(this, getString(R.string.s_storage_permission), Toast.LENGTH_SHORT).show();
                } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.READ_EXTERNAL_STORAGE)) {
                     // Open Phone Settings   
                }
        }
    }
    

  • answered 2018-04-17 05:10 Saurabh Vadhva

    Please Replace your code

    public void ImageOnClick(View v) {
    Log.i("OnClick","True");
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle(R.string.AlertTitle);
    builder.setItems(Items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            for(int i=0; i < Items.length; i++){
                if (Items[i].equals("Camera")){
                    Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if(CameraIntent.resolveActivity(getPackageManager()) != null){
                        startActivityForResult(CameraIntent, CAMERA_CODE);
                    }
    
                }else if (Items[i].equals("Gallery")){
                    Log.i("GalleryCode",""+GALLERY_CODE);
                    Intent GalleryIntent = null;
                    GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    GalleryIntent.setType("image/*");
                    GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(GalleryIntent,GALLERY_CODE);
                }
            }
        }
    });
    builder.show();
    }
    

    To

    public void ImageOnClick(View v) {
        Log.i("OnClick","True");
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.AlertTitle);
        builder.setItems(Items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (Items[which].equals("Camera")){
                    Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    if(CameraIntent.resolveActivity(getPackageManager()) != null){
                        startActivityForResult(CameraIntent, CAMERA_CODE);
                    }
    
                }else if (Items[which].equals("Gallery")){
                    Log.i("GalleryCode",""+GALLERY_CODE);
                    Intent GalleryIntent = null;
                    GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    GalleryIntent.setType("image/*");
                    GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(GalleryIntent,GALLERY_CODE);
                }
            }
        });
        builder.show();
    }
    

  • answered 2018-04-17 05:10 Jyot

    you didnt use break statement thats why its moving to next statement. just use break statement when you are firing an intent

    public void ImageOnClick (View v){
            Log.i("OnClick", "True");
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle(R.string.AlertTitle);
            builder.setItems(Items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    for (int i = 0; i < Items.length; i++) {
                        if (Items[i].equals("Camera")) {
                            Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                            if (CameraIntent.resolveActivity(getPackageManager()) != null) {
                                startActivityForResult(CameraIntent, CAMERA_CODE);
                            }
                            break;
    
                        } else if (Items[i].equals("Gallery")) {
                            Log.i("GalleryCode", "" + GALLERY_CODE);
                            Intent GalleryIntent = null;
                            GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                            GalleryIntent.setType("image/*");
                            GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                            startActivityForResult(GalleryIntent, GALLERY_CODE);
                        }
                        break;
                    }
                }
            });
            builder.show();
        }
    

    To make it efficient use position value, when you set onclickListener it returns one int variable which is position of list which is clicked. In your case its int which So you can simply use

     public void ImageOnClick (View v){
                Log.i("OnClick", "True");
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(R.string.AlertTitle);
                builder.setItems(Items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                            if (Items[which].equals("Camera")) {
                                Intent CameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                if (CameraIntent.resolveActivity(getPackageManager()) != null) {
                                    startActivityForResult(CameraIntent, CAMERA_CODE);
                                }
                                break;
    
                            } else if (Items[which].equals("Gallery")) {
                                Log.i("GalleryCode", "" + GALLERY_CODE);
                                Intent GalleryIntent = null;
                                GalleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                GalleryIntent.setType("image/*");
                                GalleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                                startActivityForResult(GalleryIntent, GALLERY_CODE);
                            }
                            break;
    
                    }
                });
                builder.show();
            }
    

    Also in OnActivityResult method use break statement otherwise it will both cases

        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 1:
                    Log.i("CameraCode", "" + CAMERA_CODE);
                    Bundle bundle = data.getExtras();
                    Bitmap bmp = (Bitmap) bundle.get("data");
                    Bitmap resized = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, true);
                    mImageView.setImageBitmap(resized);
                    break;
                case 0:
                    Log.i("GalleryCode", "" + requestCode);
                    Uri ImageURI = data.getData();
                    mImageView.setImageURI(ImageURI);
                    break;
            }
    
    
        }
    }