Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The onQueryTextSubmit in SearchView is processed twice in Android Java

Why the onQueryTextSubmit method in SearchView is processed twice? I need one result, how can I do it?

This is my code:

 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            if (query != null)
                audioRequest(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
    return true;
}
like image 834
Igor Lobanov Avatar asked Dec 10 '15 17:12

Igor Lobanov


People also ask

What is onQueryTextSubmit?

onQueryTextSubmit. Added in API level 11. public abstract boolean onQueryTextSubmit (String query) Called when the user submits the query. This could be due to a key press on the keyboard or due to pressing a submit button.

How do I get text from SearchView?

To get text of SearchView , use searchView. getQuery() .

What is setOnQueryTextListener?

Android SearchView setOnQueryTextListener(OnQueryTextListener listener) Sets a listener for user actions within the SearchView.

How do I use search view?

SearchView widget can be implemented over ToolBar/ActionBar or inside a layout. SearchView is by default collapsible and set to be iconified using setIconifiedByDefault(true) method of SearchView class. For making search field visible, SearchView uses setIconifiedByDefault(false) method.


2 Answers

SearchView has the following OnEditorActionListener on Android API 28:

private final OnEditorActionListener mOnEditorActionListener = new OnEditorActionListener() {

    /**
     * Called when the input method default action key is pressed.
     */
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        onSubmitQuery();
        return true;
    }
};

And in my debugger, I see that onEditorAction is called with both KeyEvent.action == KeyEvent.ACTION_DOWN and then KeyEvent.action == ACTION_UP.

This seems like a bug in SearchView.

like image 93
Heath Borders Avatar answered Sep 16 '22 22:09

Heath Borders


You can use the following code to prevent onQueryTextSubmit from getting executed twice:

searchView.clearFocus();

like image 24
Mahendra Liya Avatar answered Sep 18 '22 22:09

Mahendra Liya