Reputation: 186
I'm trying to load an image from URL into Bitmap object, but I always end up with NetworkInUIThread kind of exception. Can anyone provide me a library for this?
Note, that I'm not trying to put the image into ImageView, I want to put it into Bitmap object first, as it will be used more times later in my app.
I found this code in some other StackOverflow thread, but it doesn't work.
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){
return null;
}
}
Upvotes: 0
Views: 5694
Reputation: 7905
Put this code inside the doInBackground
method of an AsyncTask
e.g.
private class MyAsyncTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch(IOException e) {
return null;
}
}
protected void onPostExecute(Bitmap result) {
//do what you want with your bitmap result on the UI thread
}
}
and call it in your activity by:
new MyAsyncTask().execute(src);
Upvotes: 2
Reputation: 253
You can use Glide To download image from server and store it in Bitmap Object.
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
Please Refer this to add glide dependency in your app -> https://github.com/bumptech/glide
Upvotes: 1
Reputation: 136
try
Bitmap bitmap = null;
InputStream iStream = null;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(7000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
iStream = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(iStream);
Upvotes: 1
Reputation: 287
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
Upvotes: 1