After searching for ListView items in Android, always open first item of ListView (Issue)

♀尐吖头ヾ 提交于 2019-11-30 16:00:42

Normally if you have an ArrayAdapter of of a custom type like RowItem it won't automatically handle filtering for you. After all, how can it know which property of RowItem to filter? You should override the getFilter method, and store the filtered list separately from the overall list in your adapter. Something like this:

public class CustomListViewAdapter extends ArrayAdapter<RowItem>
{
    private final ArrayList<RowItem>  mItems;
    private       ArrayList<RowItem>  mFilteredItems;
    private final Comparator<Object> mComparator;

    public CustomListViewAdapter(Context context, int textViewResourceId, List<RowItem> items)
    {
        super(context, textViewResourceId);

        mItems = new ArrayList<RowItem>(items);
        mFilteredItems = new ArrayList<RowItem>(items);
        mComparator = new Comparator<Object>()
        {
            @Override
            public int compare(Object o1, Object o2)
            {
                String s1 = ((RowItem)o1).getTitle();
                String s2 = ((RowItem)o2).getTitle();
                return s1.toLowerCase(Locale.getDefault()).compareTo(s2.toLowerCase());
            }
        };

        Collections.sort(mItems, mComparator);
        Collections.sort(mFilteredItems, mComparator);
    }

    @Override
    public int getCount()
    {
        return mFilteredItems.size();
    }

    @Override
    public RowItem getItem(int position)
    {
        return mFilteredItems.get(position);
    }

    @Override
    public int getPosition(RowItem item)
    {
        return mFilteredItems.indexOf(item);
    }

    @Override
    public Filter getFilter()
    {
        return new Filter()
        {
            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results)
            {
                mFilteredItems = (ArrayList<RowItem>)results.values;
                if (results.count > 0)
                {
                    notifyDataSetChanged();
                }
                else
                {
                    notifyDataSetInvalidated();
                }
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint)
            {
                List<RowItem> filteredResults = new ArrayList<RowItem>();
                for (RowItem item : mItems)
                {
                    if (item.getTitle().toLowerCase(Locale.getDefault()).contains(constraint.toString().toLowerCase(Locale.getDefault())))
                    {
                        filteredResults.add(item);
                    }
                }

                Collections.sort(filteredResults, mComparator);
                FilterResults results = new FilterResults();
                results.values = filteredResults;
                results.count = filteredResults.size();

                return results;
            }
        };
    }
}

and in MainActivity:

        RowItem item = adapter.getItem(position)
        r.putExtra("cat_img", item.getImageId());
        r.putExtra("cat_id", item.getTermId());
        r.putExtra("cat_id2", item.getTermId());
        r.putExtra("cat_name", item.getTitle());

You Also have to add a termid field to RowItem, since it's in your JSON response...

Inside ArrayAdapter are two lists: the original list with all the items, and the list of current items that the adapter will create views for. In the beginning, these two lists have the same items. When you filter on the adapter, the original list will continue to hold all the items, but the list being used for display will change because of the filter. When you remove the filter, the current list of items will change again to reflect the original list.

Suppose you have five items. After filtering, the list only shows the last item. The state of these lists then is

currentItems: { item5 }
originalItems: { item1 , item2 , item3 , item4 , item5 }

When you click this item, the ListView reports that position 0 is clicked. This is because the list being shown only has one item. If you then looked for the item at position 0 in the current list, you would get item5. But if you looked for the item at position 0 of the original list, you would get item1, which is not the data for the item that was clicked.

I suspect you have a reference to the original list and are using that to get the item data, even when the list is filtered. Instead use adapter.getItem(position), it should give you the proper item.

Im using something like this and its working fine for me. Im using string value in my list onsitemclick for search and display of desired activity

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {


      String  itemValue    = (String) list.getItemAtPosition(position);
      if (itemValue == "INDIA") {
          Intent intent = new Intent(MainActivity.this, india.class);
          startActivity(intent);}
      else if (itemValue == "CHINA") {
          Intent intent = new Intent(MainActivity.this, china.class);
          startActivity(intent);}

          else if (itemValue == "IRAQ") {
              Intent intent = new Intent(MainActivity.this, usa.class);
              startActivity(intent);
     }

    }

get the listView item id from the list you are passing in //your adapter class.

herefor example if your adapter class is ##

 class CustomAdapetr(Context context,ArrayList<RowItem>list_item){}
    //mainactivity
 myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

       // HERE IS YOUR ITEM ID:):)
          int clickedItem=list_item.indexOf(parent.getAdapter().getItem(position));

            }
        });

cheers !!!! happy coding

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