SearchView: Getting the selected item from the suggestion listener

5.1k views Asked by At

I have a search view that has the suggestions populated by a MatrixCursor (because I already have an array of Strings). However I would like to get which item is being selected by the user. So far I am only able to get the position where the user has clicked on the suggestion list:

searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
        @Override
        public boolean onSuggestionClick(int position) {
            String selectedItem = (String)mAdapter.getItem(position);
            Log.e("search view", selectedItem);
            return true;
        }

However I have got an error: android.database.MatrixCursor cannot be cast to java.lang.String and I am not sure how to go around with it. Really appreciate for any kind of help.

2

There are 2 answers

0
Rishab Jain On

If someone is still looking for the answer. Use this code.

searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {

    @Override
    public boolean onSuggestionSelect(int position) {
        return true;
    }

    @Override
    public boolean onSuggestionClick(int position) {
        Cursor cursor= searchView.getSuggestionsAdapter().getCursor();
        cursor.moveToPosition(position);
        String suggestion =cursor.getString(2);//2 is the index of col containing suggestion name.
        searchView.setQuery(suggestion,true);//setting suggestion
        return true;
    }
});
0
IIRed-DeathII On

The position brings the suggested list selected item position. If your suggested list is a Cursor (from the Exception I may think is a MatrixCursor), you have to get the item that is in the position of the Cursor.

public boolean onSuggestionClick(int position) {
    Cursor searchCursor = mySearchViewAdapter.getCursor();
    if(searchCursor.moveToPosition(position)) {
        String selectedItem = searchCursor.getString(columnOfTheItemStringInTheMatrix);
    }
}

columnOfTheItemStringInTheMatrix is the column number that you assigned when you created the Matrix and added the row. For example:

MatrixCursor c = new MatrixCursor("item"});

and when you added a row (a new item to the MatrixCursor):

String item =  "myItem";
c.addRow(new Object[]{item});

Then the columnOfTheItemStringInTheMatrix = 0;