Basically, I created an Android app where users recharge then values of the Firestore was changes to a new value but if the android app did not change it will need to change activity or relaunch the app the values were updated but I want the values updated in Real-time that reflects in the Android app.
Here's my code:
DocumentReference reference =
FirebaseFirestore.getInstance().collection("Users").document(mobile);
reference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot snapshot = task.getResult();
if (snapshot.getString("Wallet") != null) {
String wallet = snapshot.getString("Wallet");
walletshow.setText(wallet); // This value was update in real time if his wallet changes to
} else { // 100₹ to 150₹ the user need to relaunch or change the activity to refresh the values
walletshow.setText("Activate your account !");
walletshow.setTextColor(Color.RED);
Log.d("LOGGER", "No such document");
}
} else {
Log.d("LOGGER", "get failed with ", task.getException());
walletshow.setText("Login Again");
}
}
});
That's it
CodePudding user response:
Basically I created an Android app where the user recharges then the values of the Firestore were changes to a new value but in the Android app was no changes.
That's the expected behavior since you are using a DocumentReference#get() call which only:
Reads the document referenced by this DocumentReference.
If you want to listen for real-time updates, then you should consider using DocumentReference#addSnapshotListener() which:
Starts listening to the document referenced by this DocumentReference.
As explained in the official documentation:
And in code that would be:
reference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot,
@Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
if (snapshot != null && snapshot.exists()) {
Log.d(TAG, "Current data: " snapshot.getData());
} else {
Log.d(TAG, "Current data: null");
}
}
});