Not able to get the text entered in search bar in android

414 views Asked by At

I am trying to implement search functionality for my android application. I am not able to get the text entered in the search bar. I have tried all the methods mentioned in SO. Please let me know what mistake am I doing. I am struggling from a long time.

my code:

  @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater = getActivity().getMenuInflater();
        inflater.inflate(R.menu.menu_activity_for_fragments, menu);

        SearchManager searchManager = (SearchManager)
                getActivity().getSystemService(Context.SEARCH_SERVICE);
        searchMenuItem = menu.findItem(R.id.search);
        searchView = (SearchView) searchMenuItem.getActionView();

        searchView.setSearchableInfo(searchManager.
                getSearchableInfo(getActivity().getComponentName()));
      enteredText = (String) searchView.getQuery();

        Log.d("iFocus", "" + enteredText);
        searchView.setSubmitButtonEnabled(true);

       searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
           @Override
           public boolean onQueryTextSubmit(String query) {
               Log.d("iFocus", ""+searchView.getQuery());

               if (0 != searchView.getQuery().length()) {
                   String spnId = searchView.getQuery().toString();
                   setSearchResult(spnId);
               } else {
                   setData();
               }


               return true;
           }

           @Override
           public boolean onQueryTextChange(String newText) {

               Log.d("iFocus", ""+newText.toString());
               adapter.getFilter().filter(newText);

               return true;
           }
       });


    }

All suggestions are welcome. Thanks in advance.

2

There are 2 answers

4
Gabriella Angelova On

Why don't you use in the overridden method onQueryTextSubmit the parameter that you become to get the query like this:

@Override
public boolean onQueryTextSubmit(String query) {
    Log.d("iFocus", query);

    if (0 != query.length()) {
         setSearchResult(query);
    } else {
         setData();
    }

    return true;
} 
4
Max77 On

See my example project with ToolBar and search menu item, min API level = 7:

android-toolbar-search