Android ImageView - Load Image from URL

Xonal picture Xonal · Mar 6, 2014 · Viewed 29.1k times · Source

I have a number of "contact" objects each with an imageURL String associated with them. All the ways I've seen of putting images into a ListView involve manually putting images into a "drawable" folder and calling resources. Manually entering the images in would defeat the purpose of this. I've provided my getView method and the commented out line is the one I'm confused about.

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = inflater.inflate(R.layout.single_row, parent, false);
    TextView name = (TextView) row.findViewById(R.id.topLine);
    TextView phone = (TextView) row.findViewById(R.id.secondLine);
    ImageView icon = (ImageView) row.findViewById(R.id.icon);

    name.setText(contactArray.get(position).getName());
    phone.setText((CharSequence) contactArray.get(position).getPhone().getWorkPhone());
    //icon.setImage from contactArray.get(position).getImageURL(); ????

    return row;
}

Answer

Adnan picture Adnan · Mar 6, 2014

While using listView you should load image asynchronously, otherwise your view will be freezes and case an ANR. Following is a complete code example which would load image asynchronously.
Create this class inside your custom adapter.

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

  public ImageDownloader(ImageView bmImage) {
      this.bmImage = bmImage;
  }

  protected Bitmap doInBackground(String... urls) {
      String url = urls[0];
      Bitmap mIcon = null;
      try {
        InputStream in = new java.net.URL(url).openStream();
        mIcon = BitmapFactory.decodeStream(in);
      } catch (Exception e) {
          Log.e("Error", e.getMessage());
      }
      return mIcon;
  }

  protected void onPostExecute(Bitmap result) {
      bmImage.setImageBitmap(result);
  }
}

Now you can load the image very easily like following.

new ImageDownloader(imageView).execute("Image URL will go here");

Don't forget to add following permission into your project's Manifest.xml file

<uses-permission android:name="android.permission.INTERNET" />