Search code examples
androidfirebasefirebase-realtime-databaseandroid-recyclerviewsearchview

Check if firebase query (for firebase options) returns empty (does not exist)


I am using a filter query for a firebaseRecyclerAdapter (firebaseOptions).

Since I am using a searchView the recycler updates with every typed letter, if the query exists.

The problem is that I would like to clear the recycler if the query does not exist.

How can I add a check to see if the query is successful or not?

I am implementing a search, if the query exists I populate the recyclerview, if the query does not exist I want to clear the recyclerview.

public void fireSearch(String queryInput) {
        String start = queryInput.toUpperCase(), end = queryInput.toLowerCase() + "\uf8ff";
    Log.d("myTag", start + " " + end);
    firebaseQuery = databaseReference.orderByKey().startAt(start).endAt(end);
    searchRecyclerView.setVisibility(View.VISIBLE);
    FirebaseRecyclerOptions<BusinessDetails> options =
            new FirebaseRecyclerOptions.Builder<BusinessDetails>()
                    .setQuery(firebaseQuery, BusinessDetails.class)
                    .setLifecycleOwner(this)
                    .build();
}

Solution

  • If the query has no results, the FirebaseRecyclerViewAdapter will already clear the existing data. There is no need for you to handle this case yourself.

    If you want to do some additional work when there is no data, you can override the onDataChanged method in your adapter class.

    FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<Chat, ChatHolder>(options) {
        // ...
    
        @Override
        public void onDataChanged() {
            // Called each time there is a new data snapshot. You may want to use this method
            // to hide a loading spinner or check for the "no documents" state and update your UI.
            // ...
        }
    
        @Override
        public void onError(DatabaseError e) {
            // Called when there is an error getting data. You may want to update
            // your UI to display an error message to the user.
            // ...
        }
    };
    

    Also see the FirebaseUI documentation on data and error events, where I got the above code from.