Search code examples
androidlistviewsearch

ListView with search function not expected behavior


I've a ListView filled with the data of an ArrayAdapter and I've implemented a search function because the list is very long.

Let's say that I have this list:

0 - orange 1 - apple 2 - tomatoe 3 - alligator 4 - train 5 - turtle 6 - dog 7 - cat

Okay, now in the EditText I use to filter this list, I write a t. Then, the list will be:

0 - tomatoe 1 - train 2 - turtle

The problem is that I've implemented an onItemClickListener so that I can access to a page or another depending on the item and when I click on the first one ( 0 - tometoe ), it picks the ( 0 ) of the first element of the list without filtering (0 - orange), when I click on the second one (1 - train), it picks the (1) of the first element of the list without filtering (1 - apple) and so on...

Here's the code I'm using:

ListView lv = new ListView(this);
        final String[] tricks;
        
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listviewcustom, tricks);
        
        lv.setAdapter(adapter);
        
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(android.widget.AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                showTrick(arg2, tricks[arg2], modality);
                //Log.e("itemClickListener", String.valueOf("LISTVIEWJ     " + arg2 + " - " + tricks[arg2] + " - " + modality));
            }
        });
        
        searchBox.addTextChangedListener(new TextWatcher() {
             
            public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                adapter.getFilter().filter(cs);
            }
         
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
         
            public void afterTextChanged(Editable arg0) { }
        });

        tricksLayout.addView(lv, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

So my question is: How can I manage to get it working as I want?


Solution

  • I did not completely understand your question. Here is the answer what I understand from your question, if it is not what you asked make a comment I will edit my answer.

    Make an ArrayList and populate it.

    ArrayList<String> list = new ArrayList<String>();
    
    list.add("orange"); //1
    list.add("apple"); //2
    list.add("tomatoe"); //3
    list.add("alligator"); //4
    list.add("train"); //5
    

    On filter you get listview like this 0 - tomatoe 1 - train 2 - turtle

    And now on onItemClickListener when you click on position 1

    String temp =  here you get "train" at index 1 
    //temp = "train"
    
    int i = termsList.indexOf("train"); 
    // it will give you actual position of train which is 5
    

    EDITED

    Also use notifyDataSetChanged to update list properly.