1

I have a listview with CompoundDrawable, the images in the compound drawable need to be loaded from the web. How can i load images to CompoundDrawable from the URL. i think that i can get bitmap image from the URL convert it into Drawable and then load it into the CompoundDrawable. like this

public static Drawable drawableFromUrl(String url) throws IOException {
    Bitmap x;

    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.connect();
    InputStream input = connection.getInputStream();

    x = BitmapFactory.decodeStream(input);
    return new BitmapDrawable(x);
}

is there a better way to do it? can i do it directly without geting bitmap from URL and then converting bitmap to drawable?

null pointer
  • 5,874
  • 4
  • 36
  • 66
  • Yes, this is pretty much how it's done. I would consider using a proper image loader to do the heavy lifting though. Generally these will also cache your images on disk, which means that your app doesn't go off to a server every single time the image needs to be loaded. – MH. Oct 01 '13 at 18:18

1 Answers1

-1

try this one

public static Drawable getDrawableFromURL(String url1) {
    try {
        URL url = new URL(url1);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Drawable d = new BitmapDrawable(getResources(),myBitmap);
        return d;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Sunil Kumar
  • 7,086
  • 4
  • 32
  • 50