Suraj
Suraj

Reputation: 165

Pick Image from gallery works fine on emulator but not on device

Hello I am beginner in android. I am writing code to pick image from gallery. My code works fine on Nexus_S emulator with Lollipop 5.1.1, but not working on device (Motorola E2 with Lollipop 5.1.1) Here is my code,

     @Override
    public void onClick(View v)
    {
        if(v.getId()==R.id.layout_pickImage)
        {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            intent.putExtra("return-data", true);
            startActivityForResult(intent, Utilities.REQUEST_ADD_IMAGE);
        }
    } 

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==Utilities.REQUEST_ADD_IMAGE)
        {
            if(data!=null)
            {
                final Bundle extras = data.getExtras();
                if (extras != null)
                {
                    try{
                        Uri uri = data.getData();

                        selected_img_bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                        imgv_selected.setImageBitmap(selected_img_bitmap);

                        imgv_selected.setVisibility(View.VISIBLE);
                    }catch(Exception e)
                    {
                        Toast.makeText(this, "error "+e, Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }

Upvotes: 0

Views: 108

Answers (1)

Eduardo Herzer
Eduardo Herzer

Reputation: 2113

Why do you need the extras? You are not using it anywhere. Just remove that extras and it should work.

The onActivityResult would look like this:

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

    if ( requestCode == Utilities.REQUEST_ADD_IMAGE ) {
        if ( data != null ) {
            try {
                Uri uri = data.getData();

                selected_img_bitmap = MediaStore.Images.Media.getBitmap( getContentResolver(), uri );
                imgv_selected.setImageBitmap( selected_img_bitmap );

                imgv_selected.setVisibility( View.VISIBLE );
            } catch ( Exception e ) {
                Toast.makeText( this, "error " + e, Toast.LENGTH_SHORT ).show();
            }
        }
    }
}

Let me know if it solves your problem

Upvotes: 1

Related Questions