Search code examples
androidlistviewandroid-listviewcustom-lists

Change image view source based on the value from database in custom listview


In my android application I have a custom listview (ArrayAdapter). in its getView() method there is a TextView and an Imageview, ImageView is for marking and un-marking favorite. When the application loads first time it checks in database if its id is available in the favorite table, if it there its image changes, but my problem is it marked favorite for non-favorite item. I am pasting my code below

      @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                View view = convertView;
                if (view == null) {
                    view = getActivity().getLayoutInflater().inflate(R.layout.custom_list_item, parent, false);
                }
                Item item = ItemList.get(position);
                TextView title = (TextView) view.findViewById(R.id.title);

                ImageView favorite = (ImageView) view.findViewById(R.id.favourite_mark_icon);
                if (mHandler.checkForIDMatchForFav(item)) {
                    favorite.setImageResource(R.drawable.fav_marked);
                }
 favorite.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    markFavourite(position, v);
                }
            });

                return view;
            }

any help is appreciated.


Solution

  • Since you are reusing the view, getting the parameter convertView, you need to change each view state before generate the new view. Recycling allow you to base your new view on a template (the old view) but you should change it if the content are dynamic

    Simply add an else branch, where the favorite ImageView is setted to the default non marked icon.

    if (mHandler.checkForIDMatchForFav(item)) {
        favorite.setImageResource(R.drawable.fav_marked);
    }else{
        favorite.setImageResource(R.drawable.not_marked);
    }