How to set ImageView image from URL in Android






activity_main.xml



<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DownLoad And Set Image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/iv"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>






MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.URL;


public class MainActivity extends Activity {
private ImageView mImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button btn = findViewById(R.id.button);
mImageView = findViewById(R.id.iv);

final String imgURL = "https://images.pexels.com/photos/" +
"1337332/pexels-photo-1337332.jpeg";

btn.setOnClickListener(v -> {
new DownLoadImageTask(mImageView).execute(imgURL);
});
}


private class DownLoadImageTask extends AsyncTask<String,Void,Bitmap> {
ImageView imageView;

public DownLoadImageTask(ImageView imageView){
this.imageView = imageView;
}

protected Bitmap doInBackground(String...urls){
String urlOfImage = urls[0];
Bitmap logo = null;
try{
InputStream is = new URL(urlOfImage)
.openStream();
logo = BitmapFactory.decodeStream(is);
}catch(Exception e){ // Catch the download exception
e.printStackTrace();
}
return logo;
}

protected void onPostExecute(Bitmap result){
imageView.setImageBitmap(result);
}
}
}