Search code examples
javaandroidandroid-layoutandroid-recyclerviewsearchview

android - hide recyclerview if search is not made


I'm using Searchview to filter through firebase entries displayed in a Recyclerview. I want the Recyclerview to be gone when a search is not made, which is working fine until I go back from the the searched item to the main activity. The recyclerview list is visible again after a search is complete. I want it to always be hidden whenever a search is not made. Here is the relevant code:

    msearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {


        @Override
        public boolean onQueryTextSubmit(String mQuery) {


            /*while (query.length() > 4) {
                mRecyclerView.setVisibility(View.VISIBLE);
            } */

            if (!(mQuery == null || mQuery.trim().isEmpty())) {
                mRecyclerView.setVisibility(View.VISIBLE);
            }

            else {
                mRecyclerView.setVisibility(View.GONE);

            }

            firebaseSearch(mQuery);

            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {

            //filter as typed
            firebaseSearch(newText);
            return true;
        }
    });

    return super.onCreateOptionsMenu(menu);
}

Solution

  • Let's imagine that you have 2 activities: A and B.

    After you click on item on activity A, you go to activity B, but this time, acitivity A is not completely destroyed. So the state of input text and recylcerView will remain. After you go back from activity B to activity A, you better perform following action to clear the search view:

    msearchView.setQuery("",false);
    msearchView.setIconified(true);
    

    Since the searchView is cleared, onQueryTextChange() will be executed. You can check the condition here.