0

I was wondering how i set a buttons background image from a URL on android. The buttons id is blue if you need to know that.

I tried this but it didn't work.

    public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
    in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
    copy(in, out);
    out.flush();

    final byte[] data = dataStream.toByteArray();
    BitmapFactory.Options options = new BitmapFactory.Options();
    //options.inSampleSize = 1;

    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
    Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
    closeStream(in);
    closeStream(out);
    }

    return bitmap;
    }
user2192418
  • 49
  • 1
  • 5

3 Answers3

1

I used the next code for obtain the bitmap, one important thing is sometimes you can't obtain the InputStream, and that is null, I make 3 attemps if that happens.

public Bitmap generateBitmap(String url){
    bitmap_picture = null;

    int intentos = 0;
    boolean exception = true;
    while((exception) && (intentos < 3)){
        try {
            URL imageURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
            conn.connect();
            InputStream bitIs = conn.getInputStream();
            if(bitIs != null){
                bitmap_picture = BitmapFactory.decodeStream(bitIs);
                exception = false;
            }else{
                Log.e("InputStream", "Viene null");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            exception = true;
        } catch (IOException e) {
            e.printStackTrace();
            exception = true;
        }
        intentos++;
    }

    return bitmap_picture;
}
0

Don't load the image directly in the UI (main) thread, for it will make the UI freeze while the image is being loaded. Do it in a separate thread instead, for example using an AsyncTask. The AsyncTask will let the image load in its doInBackground() method and then it can be set as the button background image in the onPostExecute() method. See this answer: https://stackoverflow.com/a/10868126/2241463

Community
  • 1
  • 1
Piovezan
  • 3,215
  • 1
  • 28
  • 45
0

Try this code:

Bitmap bmpbtn = loadBitmap(yoururl);

button1.setImageBitmap(bmpbtn);
Sagar Maiyad
  • 12,655
  • 9
  • 63
  • 99