Reputation: 1
I am trying to GET a Bitmap image from a URL.
(Example: https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png)
But there seems to be a problem with the connection.connect()
line, that I can't figure out.
I have allowed internet access in the app.
public static Bitmap getBitmapFromURL(String src) {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
}
return BitmapFactory.decodeStream(inputStream);
}
Upvotes: 0
Views: 5938
Reputation: 1750
Generally network connection should be done is a separate thread. You can use AsyncTask
for that. For example, this works:
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_layout);
imageView = (ImageView) findViewById(R.id.imageView);
new LoadImage().execute("https://cdn.bulbagarden.net/upload/9/9a/Spr_7s_001.png");
}
private class LoadImage extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = null;
try {
InputStream inputStream = new URL(strings[0]).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}
Upvotes: 0
Reputation: 1068
You could use glide for a short solution
implementation "com.github.bumptech.glide:glide:4.11.0"
annotationProcessor "com.github.bumptech.glide:compiler:4.11.0"
try {
Bitmap bitmap = Glide
.with(context)
.asBitmap()
.load(imageUrl)
.submit()
.get();
} catch (Exception e) {
e.printStackTrace();
}
Upvotes: 3