Now we have to explain how to display image from URL. ImageView is used
to display image in android. Here we use AsyncTask for loading image
from URL. Now lets we explain it with Example.
Above is our final Screen shot display image from URL.
Create new Android Project AndroidAdvanceDisplayImageURL.
Layout file main.xml looks like following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:text />
<ImageView
android:id="@+id/my_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
-> Here we take imageview to display image. Now coding part.
AndroidAdvanceImageLoad.java
public class AndroidAdvanceImageLoad extends Activity {
ImageView my_img;
Bitmap mybitmap;
ProgressDialog pd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new DisplayImageFromURL((ImageView) findViewById(R.id.my_image))
.execute("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg");
}
private class DisplayImageFromURL extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(AndroidAdvanceImageLoad.this);
pd.setMessage("Loading...");
pd.show();
}
public DisplayImageFromURL(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
pd.dismiss();
}
}
}
-> Here we create DisplayImageFromURL class which loads image from
URL and display it on imageview. It take 2 arguments one is image id and
another is Image URL from which you display image.