views:

1516

answers:

1

how can we html.fromhtml to load image from web and set into imageview ?

+2  A: 

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

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. 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

Ally
This looks good, but when i use code with custom listview where at every listitem had a row icon images and new async task was executing to display image for every row icon.But images are not displaying appropriatly 1st row image at 2nd row and 2nd row image at first row why is that though i am passing imageview reference to the asyntask but still have the same issue.
Faisal khan
So your initial problem is solved? I'm not really sure what's going on. If you want me to take a look at your new problem then post some code. :)
Ally