25

I'm storing the drawable resource path in an Uri in this way:

Uri uri = Uri.parse("android.resource://my_app_package/drawable/drawable_name");

How do I get the Drawable that the uri is referencing?

I don't want to put it in an ImageView, just retrieve the Drawable (or Bitmap) object.

Shanimal
  • 11,517
  • 7
  • 63
  • 76
Daniele Vitali
  • 3,848
  • 8
  • 48
  • 71

1 Answers1

60

getContentResolver cr object then call:

is = cr.openInputStream(uri) 

and finally call:

Drawable.createFromStream(InputStream is, String srcName)

...Here's an actual working code example so you can see for yourself:

try {
    InputStream inputStream = getContentResolver().openInputStream(yourUri);
    yourDrawable = Drawable.createFromStream(inputStream, yourUri.toString() );
} catch (FileNotFoundException e) {
    yourDrawable = getResources().getDrawable(R.drawable.default_image);
}
Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
pskink
  • 23,874
  • 6
  • 66
  • 77
  • thanks! I chose to edit @pskink's answer (vs. providing a new answer) since I could only take partial credit. – PeteH Aug 31 '13 at 23:34
  • 2
    Note: you may have to also call `yourDrawable.setBounds(...)`, in some cases like setting it as a compound drawable of a `TextView` – Avinash R Jan 05 '14 at 20:16
  • 1
    What @AvinashR mentions is correct, if not the drawable won't be draw on screen. – moxi May 01 '18 at 22:39