问题
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 whenever i try to call adapter.getitemcount it gives count 0 quickly even when my recyclerview will have values coming from firebase. So i think maybe till the values come the getItemCount method is executed before and returns 0 or maybe it is executed on separate thread. But either way i get 0 even when my recyclerview has values coming from firebase. So i want to check if my firebase recycler is empty or not and then change views accordingly, becoz i dont like to show the users and empty recyclerview (an empty activity). plz suggest how should i check it? btw heres my simple firebase adapter code :
allFriendsAdapter = new FirebaseRecyclerAdapter<FriendsModel, ViewHolder>(friendsOptions) {
@Override
protected void onBindViewHolder(@NonNull final ViewHolder holder, final int position, @NonNull FriendsModel model) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(allFriendsAdapter .getItemcount==0){ //this is always returning 0 even when my recyclerview has values
}
回答1:
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<FriendsModel> friendsOptions =
new FirebaseRecyclerOptions.Builder<FriendsModel>()
.setQuery(queries, FriendsModel.class)
.build();
回答2:
Simply override onDataChanged
and check for getItemCount()
there.
来源:https://stackoverflow.com/questions/49892299/how-to-check-if-firebase-recylerview-has-values-or-it-is-empty-in-android