How to check if firebase recylerview has values or it is empty in android?

前端 未结 2 1582
有刺的猬
有刺的猬 2021-01-25 14:14

I dont like to show empty RecyclerView to users. I know there is getItemCount method in recyclerview, but i think reyclerview is executed on separate thread maybe. Its because w

2条回答
  •  悲哀的现实
    2021-01-25 14:50

    You can use ValueEventListener to check if any values exists:

    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
    Query queries = ref.orderByChild("name").equalTo(name_here);
    queries.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {
                    Toast.makeText(HomeActivity.this,"data exists",Toast.LENGTH_SHORT).show();
    
                }
                else{
                    Toast.makeText(HomeActivity.this,"No data exists",Toast.LENGTH_SHORT).show();
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
    
            }
        });
    

    In your Adapter, you need to use a query to be able to get the data, example as the above query and it will also check if the data exists.

    Then you can configure the adapter by building FirebaseRecyclerOptions:

    FirebaseRecyclerOptions friendsOptions =
            new FirebaseRecyclerOptions.Builder()
                    .setQuery(queries, FriendsModel.class)
                    .build();
    

提交回复
热议问题