Thursday, November 21, 2013

How to load Image View with direct link image URL in Android

Add this method to the activity:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
   ImageView bmImage;

   public DownloadImageTask(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);
   }
}

Then execute it by adding this line of code inside the onCreate:

new DownloadImageTask((ImageView) pic_profile_small)
        .execute("http://www.yourpicdirectlink.com/image.jpg");

The task will be loaded Async, so that the UI will not freeze.