Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MohammadSamandari/63aa021ba54de12782f73f55e0312614 to your computer and use it in GitHub Desktop.
Save MohammadSamandari/63aa021ba54de12782f73f55e0312614 to your computer and use it in GitHub Desktop.
Learning: Downloading Image from internet with async task
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
return bitmap;
} catch (Exception e) {
Log.i("Lord", "Error");
return null;
}
}
}
public void downloadImage(View view) {
DownloadImageTask downloadImageTask = new DownloadImageTask();
try {
Bitmap bitmap = downloadImageTask.execute("https://www.cahill.com/professionals/mohammad-islam/_res/id=Picture").get();
imageView.setImageBitmap(bitmap);
Log.i("Lord", "Done");
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment