filtering custom adapter IndexOutOfBoundsException

前端 未结 4 1316
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 00:05

I\'m novice at android.

My custom Adapter cause exception when filtering.

here is my code. private class DeptAdapter extends ArrayAdapter implements Filter

相关标签:
4条回答
  • 2021-01-18 00:20

    You need to add this methods for better performance:

            @Override
            public int getCount() {
                return items.size();
            }
    
            @Override
            public Object getItem(int position) {
                return this.items.get(position);
            }
    
            @Override
            public long getItemId(int position) {
                return position;
            }
    
    0 讨论(0)
  • 2021-01-18 00:21

    Keep in mind that getView() will query the size of the items that the superclass has, which right now, is what you originally passed it when calling the superclass constructor,

    super(context, textViewResourceId, items);
    

    Therefore, the superclass doesn't know that you've changed the size when you have filtered. This means getCount() will return the original size of the array, which is understandably larger than your filtered array.

    This means You should override the getCount() method so you're sure that you're returning the actual valid size:

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

    You should also override the other methods related to the List operations (such as getting) if you are going to be using them. Eg:

    @Override
    public Dept getItem (int pos){
         return items.get(pos);
    }
    
    0 讨论(0)
  • 2021-01-18 00:32

    You are missing getCount() method, look at this demo

    I hope it will be helpful !

    0 讨论(0)
  • 2021-01-18 00:40
     private ArrayList<Dept> items;
        private ArrayList<Dept> mOriginalValues;
    
        public DeptAdapter(Context context, int textViewResourceId, ArrayList<Dept> items) {
                super(context, textViewResourceId, items);
                this.items = items;
                this.mOriginalValues=items;  //add this line in your code
        }
    
    0 讨论(0)
提交回复
热议问题