How to load image from a URL or internet in android
Subscribe Here
To add internet permission in your android Manifest file.
<uses-permission android:name="android.permission.INTERNET" />
Add ImageView on your xml file.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<ImageView
android:id="@+id/ivPhoto"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:padding="5dp"
android:layout_gravity="center"
android:src="@drawable/photo"
/>
</LinearLayout>
To create an Async class as an inner class in our MainActivity class. The use of Asyn class is very important since it prevents us from downloading our remote image using the main application thread.
Code :
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import java.io.InputStream;
public class ImageloadActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imageload);
ImageView imgPhoto = (ImageView)findViewById(R.id.ivPhoto);
String urlPath = "http://10.42.0.1/dsms/backend/web/stud_photos/119426.jpg";
Downloadimagefromurl downloadTask = new Downloadimagefromurl(imgPhoto);
downloadTask.execute(urlPath);
}
private class Downloadimagefromurl extends AsyncTask<String,Void,Bitmap>{
ImageView bmImg;
public Downloadimagefromurl(ImageView bmImg) {
this.bmImg = bmImg;
}
@Override
protected Bitmap doInBackground(String... urls) {
String pathFile = urls[0];
Bitmap bitmap = null;
try {
InputStream inp = new java.net.URL(pathFile).openStream();
bitmap = BitmapFactory.decodeStream(inp);
} catch (Exception e){
Log.e("Error",e.getMessage());
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
bmImg.setImageBitmap(bitmap);
}
}
}
Display default image in imageview if no image returned from server
@Override
protected void onPostExecute(Bitmap bitmap) {
if(bitmap != null)
bmImg.setImageBitmap(bitmap);
else
bmImg.setImageResource(R.drawable.photo);
}