Android ImageView - Load Image from URL [closed]

孤人 提交于 2019-12-06 10:23:33

问题


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;
}

回答1:


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" />



回答2:


Load Image from URL like this.

URL url = new URL(contactArray.get(position).getImageURL());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
icon.setImageBitmap(bmp);

Perhaps if you are looking for more comprehensive way and you have very large data set. I would recomend you to use Android-Universal-Image-Loader library.



来源:https://stackoverflow.com/questions/22212463/android-imageview-load-image-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!