Home » Android » Searching Listview with onClick view showing wrong

Searching Listview with onClick view showing wrong

Posted by: admin November 1, 2017 Leave a comment

Questions:

Can anyone help me how to fix wrong result from searchview of listview. for example I have data from list view (1,2,3,4,5) When I search data 2 from searchview an I click it, always data 1 that show it, and when I didn’t search data from searchview the result if true, I click data 1 show 1, 2 show 2

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView) findViewById(R.id.listview);

    MaterialSearchBar searchBar = (MaterialSearchBar) findViewById(R.id.searchBar);
    searchBar.setHint("Search..");
    searchBar.setSpeechMode(true);
    final String[] values= new String[]{"cemento","muro","puerta"};
    final ArrayAdapter<String> adapter  = new ArrayAdapter<String>(this,
            android.R.layout.activity_list_item,android.R.id.text1,values);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view,
                                int position, long id) {
            if(position==0){
                Intent myintent = new Intent(view.getContext(),cemento.class);
                startActivityForResult(myintent,0);
            }
            if(position==1){
                Intent myintent = new Intent(view.getContext(),muro.class);
                startActivityForResult(myintent,1);
            }
            if(position==2){
                Intent myintent = new Intent(view.getContext(),puerta.class);
                startActivityForResult(myintent,2);
            }
        }
    });



    searchBar.addTextChangeListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            adapter.getFilter().filter(charSequence);
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });


}}
Answers:

After your filtering, the position by your click listener can not be the same as what you have in your if statement.

Possible solution: Get the position of clicked item using your dataset and compare its content against your values.