1

I am trying to set the picture that the user chooses from their gallery, by using Uri, as their background for an app, but I cant quite figure it out. One thing that I tried doing was straight up setting the background to the uri, but it fails do to compatibility mismatch. How can I do this, either by programmatically setting the drawable or any other way at at all?

Here is what I have tried

 protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

    super.onActivityResult(requestCode, resultCode, intent);
    if (requestCode == 1) {

        if (intent != null && resultCode == RESULT_OK) {

            Uri selectedImage = intent.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 filePath = cursor.getString(columnIndex);
            cursor.close();

            if (bmp != null && !bmp.isRecycled()) {
                bmp = null;
            }

            bmp = BitmapFactory.decodeFile(filePath);
            imageView.setBackground(selectedImage);//error here

            //imageView.setBackgroundResource(0);//originally this, but this crashes also
            imageView.setImageBitmap(bmp);

        }
    }
}
mr nooby noob
  • 1,860
  • 5
  • 33
  • 56

1 Answers1

4

Check out this link Retrieve drawable resource from Uri

     try {
            InputStream inputStream = getContentResolver().openInputStream(yourUri);
            yourDrawable = Drawable.createFromStream(inputStream, yourUri.toString() );
            imageView.setImageDrawable(yourDrawable);
        } catch (FileNotFoundException e) {
            yourDrawable = getResources().getDrawable(R.drawable.default_image);
        }
Community
  • 1
  • 1
Soham
  • 4,397
  • 11
  • 43
  • 71
  • EDIT: Thank you, but it still is crashing; this is what I have now in the try statatement: InputStream inputStream = getContentResolver().openInputStream(selectedImage); Drawable uploadedPic = Drawable.createFromStream(inputStream, selectedImage.toString()); imageView.setImageDrawable(uploadedPic); – mr nooby noob Apr 15 '15 at 02:16
  • 1
    Don't forget this line: finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception ignored ) {} } – MarcJames May 19 '17 at 16:31