Этот код с использованием API Firestore:
FirebaseFirestore.getInstance().collection("Users")
.document(currentUserUid).collection("Meal Planner").addSnapshotListener(this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if(e != null){
return;
}
for(DocumentChange dc : documentSnapshots.getDocumentChanges()){
Meal meal = dc.getDocument().toObject(Meal.class);
switch(dc.getType()){
case ADDED:
meals.add(meal);
mAdapter.notifyItemRangeInserted(dc.getNewIndex(), meals.size());
totalCalories();
break;
case REMOVED:
meals.remove(dc.getOldIndex());
mAdapter.notifyItemRemoved(dc.getOldIndex());
mAdapter.notifyItemRangeRemoved(dc.getOldIndex(), meals.size());
totalCalories();
break;
}
}
}
});
Выше приведен перевод этого кода с использованием API базы данных реального времени:
FirebaseDatabase.getInstance().getReference().child( "Users")
.child(currentUserUid)
.child("Meal Planner")
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
Meal meal = dataSnapshot.getValue(Meal.class);
meals.add(meal);
mAdapter.notifyDataSetChanged();
// TODO: to be able to notify the adapter more granularly, you'll have to keep track of the index yourself
//mAdapter.notifyItemRangeInserted(dc.getNewIndex(), meals.size());
totalCalories();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A meal has changed, use the key to determine if we are displaying this
// meal and if so displayed the changed meal.
// ...
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A mean has been removed, use the key to determine if we are displaying this
// comment and if so remove it.
String mealKey = dataSnapshot.getKey();
// ...
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A meal has changed position, use the key to determine if we are
// displaying this meal and if so move it.
// ...
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "meals:onCancelled", databaseError.toException());
Toast.makeText(mContext, "Failed to load meals.",
Toast.LENGTH_SHORT).show();
}
};
Также см. Документацию Firebase по прослушиваниюдля детских событий .