Search code examples
javaandroidpositionsearchview

Issue with position using SearchView for a ListView Java


I have a listview that is populated with these words

    arrayList.add("apple");
    arrayList.add("banana");
    arrayList.add("bell");
    arrayList.add("cheese");

If I click on a row, a message appears

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

            Toast.makeText(getApplicationContext(), arrayList.get(position), Toast.LENGTH_SHORT).show();
        }
    });

I have a searchview that filers out words that are not what the user is typing

editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String text = editText.getText().toString().toLowerCase(Locale.getDefault());
            adapter.getFilter().filter(text);

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

If I type "b" into the searchview, "banana" and "bell" are the only items in the listview. But if I click on "banana", the Toast says "apple". I understand what the problem is and why it is doing this, but I don't know a simple way to fix it.

One way to solve this is like so...

int textLength = text.length();

            if (textLength == 0) {
                test.addAll(arrayList);
            } else {

                int counter = 0;

                for (String string : arrayList) {

                    if (string.toLowerCase().substring(0, textLength).equals(text)) {
                        test.add(string);
                        intPositions.add(counter);
                    }

                    counter++;
                }
            }

If I do this, my onClickListener for the listview changes to this

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

            int i = intPositions.get(position);

            Toast.makeText(getApplicationContext(), arrayList.get(i), Toast.LENGTH_SHORT).show();
        }
    });

NOTE: This only works if the user types something into the searchview before clicking on a row.

This is fine, but if my arrayList has 2000, 3000 or 5000 items in it, this isn't a very efficient method. Any help is appreciated.


Solution

  • Change below code:

    Toast.makeText(getApplicationContext(), arrayList.get(position), Toast.LENGTH_SHORT).show();
    

    with following code:

    String text = ((TextView) view).getText().toString();
    Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();