Search code examples
javaandroidlistviewadaptersearchview

How to filter string based on the searchView input


I want to create suggestions for my searchView.

I have a listView and a Map that contains the entire contacts list. I created a custom adapter to populate the ListView. I also have a searchView to allow user to search for specific contact.

Now I'm using OnQueryTextChange, but I don't know how to create an other Map to pass it in the adapter in order to display only names typed by the user.

I'm stuck because I just want to add a contact name based on the first letter. Example: If the user types "m" then I want to create a Map with all contact starting with "m", then the user continues adding letter and the Map should filter the contact until there is only one name.

Here is the code:

@Override
        public boolean onQueryTextChange(String newText) {
            for (String name : mKeys) { // here Im looping the keys of my contact Map
                if (something) {
                   Map.put(name, contact.get(name));  // contact is the contact Map
                }
                createContactAdapter(Map);
                }
            }

            return false;
        }

Thanks for the help

EDIT

My updated code:

@Override
        public boolean onQueryTextChange(String newText) {
            Toast.makeText(ContactsActivity.this, newText, Toast.LENGTH_SHORT).show();
            for (String name : mKeys) {
                name = name.trim();
                if (name.startsWith(newText) && newText.length() > 0)  {
                    mFilteredMap.put(name, "00000000000"); // NPE here

                    if (mFilteredMap.size() > 1) {
                        createContactAdapter(mFilteredMap);
                    }
                }


            } 
            return false;

first let's handle only the adding function.


Solution

  • I think I get it now. Is...

    if (name.startsWith(newText))

    what you're looking for?

    String.startsWith()

    This would see if the key begins with the text from the search; if so, add it to the map.

    At this point you'd have a map of all keys for the first letter. If you want to filter this map you'll have to have an empty check to see which set of keys you're working on. Then you'd have to remove all entries with...

    if (! name.startsWith(newText)) { /* remove it */ }

    This tells you that the given key doesn't match the search and then you remove it.