简体   繁体   中英

Load image from URL - Java

I am trying to load an image from a url in the handelResponse of my ASYNC Task that makes a GET request, and in handelResponse I have this

 InputStream is = (InputStream) new URL(homeScreenPicUrl).getContent();
 b = BitmapFactory.decodeStream(is);

But my ASYNC Task seems to have a problem with this as I get W/System.err﹕ android.os.NetworkOnMainThreadException how could I load the image in the hadelResponse , ideally I want to load it syncronously as I want to wait for it to load before moving to the next screen.

And since this is all happening on the splash screen I am just waiting for the pic before moving to the main page.

Thanks

This is because InputStream is just a handler: when you read() from it (which is what BitmapFactory does) you are in fact fetching data from the network, and Android forbids it because you are slowing the system.

Either you decode the stream in the background thread and change the return type of the AsyncTask to Bitmap , or you store the content of the stream in a byte[] and use that byte[] to build the image in the UI thread. Both solution are equivalent because you are consuming the stream in the background thread and store its content in memory.

public byte[] consume(InputStream in) throws Exception {
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  byte[] buffer = new byte[2048];
  int read = -1;
  while ((read = in.read(buffer)) > 0) {
    out.write(buffer, 0, read);
  }
  return out.toByteArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM