Search code examples
javaandroidarrayssearchviewbaseadapter

Unable to get Search View items clickable in correct position


private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;     

adapter = new ListProductAdapter(this, mProductList);

    lvProduct.setAdapter(adapter);

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int 
        position2, long id) {

        }
    });

**Here is Search Query Listner **

 @Override
 public boolean onQueryTextChange(String s) {
    s=s.toLowerCase();
    ArrayList<Product> newList = new ArrayList<>();
    for (Product listProductAdapter : mProductList){
        String name = listProductAdapter.getSearchName().toLowerCase();
        if(name.contains(s)){
            newList.add(listProductAdapter);
            ;
        }
    }
    adapter.setFilter(newList);
    return true;
}

Here is ListAdapter and Filter adapter

public ListProductAdapter(Context mContext, List<Product> mProductList) {
    this.mContext = mContext;
    this.mProductList = mProductList;
}


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


@Override
public Object getItem(int position) {
    return mProductList.get(position);
}

@Override
public long getItemId(int position2) {
    return mProductList.get(position2).getId();
}


@Override
public View getView(int position2, View convertView, ViewGroup parent) {

    View v = View.inflate(mContext, R.layout.item_listview, null);
    v.setTag(mProductList.get(position2).getId());
    TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
    tvName.setText(mProductList.get(position2).getName());
    return v;
}

 public void setFilter(ArrayList<Product> newList){
    mProductList = new ArrayList<>();
    mProductList.addAll(newList);
    notifyDataSetChanged();
}

I want to get items clicked with mProductList.get(position2).getId() I am getting a sorted new adapter for searchview but i am getting previous adapter position id. But i want a updated listview position id's with updated listview adapter. Please Help me in this.


Solution

  • You need to clear old list and add new items.. Try this,

        public void setFilter(ArrayList<Product> newList){
        mProductList.clear();
        mProductList.addAll(newList);
        notifyDataSetChanged();
    }