how can we html.fromhtml to load image from web and set into imageview ?
Asynchronous Image Downloading
First thing to do is to make sure you request permission to download images inside the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
Then, to download an image from the web we need to open an HTTP connection, download and return the image. This method should go inside the activity.
private Bitmap DownloadImage(String URL)
Then we would then add the downloaded image to the ImageView
Bitmap bitmap = DownloadImage("http://www.streetcar.org/mim/cable/images/cable-01.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
However, this isn’t asynchronous.
Normally we would create a thread to do some background work but a thread can’t update a view it didn’t create.
To solve this problem we can use AsyncTask. I’ve written this little inner class that extends AsyncTask.
class DownloadImagesTask extends AsyncTask<String, Integer, Bitmap> {
private int imageViewID;
protected void onPostExecute(Bitmap bitmap1) {
setImage(imageViewID, bitmap1);
}
public void setImageId(int imageViewID) {
this.imageViewID = imageViewID;
}
@Override
protected Bitmap doInBackground(String... url) {
Bitmap bitmap1 =
DownloadImage(url[0]);
return bitmap1;
}
}
The three types used by AsyncTask are
- Params, the type of the parameters sent to the task upon execution.
- Progress, the type of the progress units published during the background computation.
- Result, the type of the result of the background computation.
So to replace the old code we can now use
DownloadImagesTask task1 = new DownloadImagesTask();
task1.setImageId(R.id.img1);
task1.execute("http://assets.devx.com/articlefigs/39810_1.jpg");
This got a lot longer than I planned. The codes not perfect but I hope it’s helped you.
Note: This was is based on Connecting to the web at DevX
References
- Connecting to the web : http://www.devx.com/wireless/Article/39810/1954
- AsyncTask: http://developer.android.com/reference/android/os/AsyncTask.html