How to get ArrayList<String> image URLs into ImageView of ListView getView method

1.1k views Asked by At
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null){
        convertView = inflater.inflate(resource, null);
    }

    ImageView imageView;
    imageView = (ImageView) convertView.findViewById(R.id.ivGallery);
    for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
        Glide.with(getContext()).load(images).into(imageView);
    }
    return convertView;
}

// image URLs are stored in string ArrayList . I defined getter and setter for array list but still I don't know how to use get method for showing ArrayList images dynamically in ListView

2

There are 2 answers

1
Tassadar On

Extend the class from BaseAdapter

Override getCount() method and return here the total amount of images you need to show.

In the getView load with Glide only ONE url (remove the for loop), the getView method will be called N times to show in the list the "total" amount of images you returned in the getCount method, the position parameter in the getView method will run from 0 to (total - 1).

You should map 1 position to 1 url, maybe you will need to change the way you access the objects that contain the urls.

2
Chantell Osejo On

Okay so first: stop using ListView, use RecyclerView.

Next, you need to override getItemCount(). You can either choose to do this using a for loop:

int count = 0;

for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
    count += images.size();
}

Or, what is likely preferable, flatten your model object into just what this adapter actually cares about (which is the image URL strings). Something like this:

ArrayList<String> imageUrls = new ArrayList<String>();

for(HospitalModel model : hospitalModelList) {
    imageUrls.addAll(model.getImagesList().getImageUrls());
}

Then pass in the imageUrls ArrayList to the Adapter instead. You should only need to flatten this when the model is updated (whether that's initialization or changed). When that occurs, use the notify... methods on the adapter.

After that, it's just a simple Glide.with(getContext()).load(imageUrls.get(position)).into(imageView); inside getView (or onBindViewHolder if you're using a RecyclerView, which I HIGHLY recommend).