Search code examples
androidandroid-galleryandroid-button

Insert an Image from the gallery on a button in Android


Im trying to do this:

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

    if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        Bitmap bmp = BitmapFactory.decodeFile(picturePath);
        b[1].setCompoundDrawablesWithIntrinsicBounds(null, new BitmapDrawable(bmp), null, null);
}

But it wont set the image, no matter what. I have tried several different methods too, like using an imagebutton instead of a button and using:

imageButton.setImageBitmap(bmp)

The gallery opens fine and and the callback comes to onActivityResult(...) but the image wont appear on the button, I have an array of buttons.


Solution

  • I made a rapid test. The following code works for me. If with this you still can't set the image I would check if there's a layout problem (i.e. the image is set but there's no room to show it).

    activity_main.xml has just an ImageButton set to wrap_content, inside the main layout which is match_parent.

    public class MainActivity extends Activity {
    
        ImageButton imgButton;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            imgButton = (ImageButton) findViewById(R.id.imgButton);
    
            imgButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    intent.setType("image/*");
    
                    startActivityForResult(intent, 0);
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if(requestCode == RESULT_CANCELED) return;
    
            ParcelFileDescriptor fd;
            try {
                fd = getContentResolver().openFileDescriptor(data.getData(), "r");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return;
            }
    
            Bitmap bmp = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor());
    
            imgButton.setImageBitmap(bmp);
        }   
    }