I've been trying to download an image into a bitmap element to load them into a gridView with images, but I need to do it async because if not gives the error "android.os.NetworkOnMainThreadException".
Searching I found a lot of tutorials to do that, but all of them add this element to an ImageView when finished. Is there any way to do that but into a Bitmap?
Here I have ways to download without async that I found:
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
One more:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Wrap your getBitmapFromURL
method into an AsyncTask
, see below:
private class GetBitmapFromURLAsync extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
}
}
Nest the above AsyncTask
into your Activity:
public class MyActivity extends Activity {
// To store the Bitmap returned by doInBackground asynctask
private Bitmap result;
// existing Activity code
...
private class GetBitmapFromURLAsync extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
// return the bitmap by doInBackground and store in result
result = bitmap;
}
}
And to call the above code:
GetBitmapFromURLAsync getBitmapFromURLAsync = new GetBitmapFromURLAsync();
getBitmapFromURLAsync.execute("http://....");
You can't make heavy operations like http request from main (UI) thread in android. Or you will get that error. You can use AsyncTask .
class ImageDownloadTask extends AsyncTask<String, Void, Bitmap> {
//this operation is in backgrouund
@Override
protected Bitmap doInBackground(String... params) {
return getBitmapFromURL(params[0]);
}
//operation is finished, update the UI with bitmap
@Override
protected void onPostExecute(Bitmap bitmap) {
}
}
Or just use Picasso library, it does all work for you, including caching.
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
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.