How to use setImageUri() on Android

ilredelweb picture ilredelweb · Oct 6, 2010 · Viewed 79.6k times · Source

Can you help me please? I've tried :

ImageButton imgbt=(ImageButton)findViewById(R.id.imgbutton);
Uri imgUri=Uri.parse("/data/data/MYFOLDER/myimage.png");
imgbt.setImageUri(imgUri);

but I didn't see anything, simply a void button.

Answer

SoH picture SoH · Feb 6, 2012

ImageView.setImageUri only works for local Uri, ie a reference to a local disk file, not a URL to an image on the network.

Here is an example of how to fetch a Bitmap from the network.

    private Bitmap getImageBitmap(String url) {
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
       } catch (IOException e) {
           Log.e(TAG, "Error getting bitmap", e);
       }
       return bm;
    } 

Once you have the Bitmap from getImageBitmap(), use: imgView.setImageBitmap(bm);