1

I need my SearchView to have an AutoComplete dropdown List

Ive found this solution but it doesn't work. I marked error causing lines

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);

    MenuItem item = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) item.getActionView();
    searchView.setBackgroundColor(Color.YELLOW); //It works
    androidx.appcompat.widget.SearchView.SearchAutoComplete searchAutoComplete = searchView.findViewById(R.id.search_src_text);
    searchAutoComplete.setBackgroundColor(Color.YELLOW); //ERROR! null object reference

    String dataArr[] = {"Apple" , "Amazon" , "Amd", "Microsoft", "Microwave", "MicroNews", "Intel", "Intelligence"};
    ArrayAdapter<String> newsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, dataArr);
    searchAutoComplete.setAdapter(newsAdapter); //ERROR! null object reference 
    //...
}
artyom9912
  • 11
  • 3

1 Answers1

1

You don't use SearchAutoComplete with androidx SearchView.
That's for support v7.

Here's the answer to this in another question

You use searchView.setSuggestionsAdapter(adapter)
This has a more complicated set up than the autocomplete, it's already explained in the link with code examples.

Briefly described:

  1. Set up from column names and to view ids to display the data (I think you can include more columns without having to display them, but didn't test it).
  2. Create SimpleCursorAdapter with cursor null.
  3. In SearchView.OnQueryTextListener fetch your data (You could also do this outside, but that'll make your suggestions static)
  4. Create a MatrixCursor with rows of your suggestions, each row with an ID and the columns the adapter needs.
  5. Call searchView.getSuggestionsAdapter().changeCursor(matrixCursor)
  6. Use searchView.setOnSuggestionListener(new OnSuggestionListener()) to react to the user interactions.