I have a collection of products and I want to get realtime updates. This is my code:
query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot querySnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) return;
List<Product> list = new ArrayList<>();
for (DocumentChange documentChange : querySnapshot.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:
Product product = documentChange.getDocument().toObject(Product.class);
list.add(product);
break;
case MODIFIED:
adapter.notifyDataSetChanged();
break;
case REMOVED:
//
break;
}
}
adapter = new ProductAdapter(context, list);
recyclerView.setAdapter(adapter);
}
});
If the price of a product changes and I have the app in foreground, I cannot see the change in my RecyclerView
at all. I still see the old price even if I notify the adapter. There is also something weird happening. If the price of tenth product changes, the scroll goes to first position.
How can I see the realtime change when a price is changed? And how can remain at the current position in the RecyclerView
when a change occurs?
Edit:
case MODIFIED:
Product modifiedProduct = documentChange.getDocument().toObject(Product.class);
for(Product p : list) {
if(p.getProductName().equals(modifiedProduct.getProductName())) {
list.remove(p);
}
}
list.add(modifiedProduct);
adapter.notifyDataSetChanged();
The same thing happens. Still seeing the old price.