从 Firestore 实时更新数据

gau*_*all 0 java android firebase google-cloud-platform google-cloud-firestore

基本上,我创建了一个 Android 应用程序,用户在其中充值,然后 Firestore 的值更改为新值,但如果 Android 应用程序没有更改,则需要更改活动或重新启动应用程序,值已更新,但我希望更新值实时反映在 Android 应用程序中。

\n

火库

\n

这是我的代码:

\n
DocumentReference reference = \nFirebaseFirestore.getInstance().collection("Users").document(mobile);\n    reference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {\n        @Override\n        public void onComplete(@NonNull Task<DocumentSnapshot> task) {\n            if (task.isSuccessful()) {\n                DocumentSnapshot snapshot = task.getResult();\n                if (snapshot.getString("Wallet") != null) {\n                    String wallet = snapshot.getString("Wallet");\n                    walletshow.setText(wallet);     // This value was update in real time if his wallet changes to\n                } else {                            // 100\xe2\x82\xb9 to 150\xe2\x82\xb9 the user need to relaunch or change the activity to refresh the values\n                    walletshow.setText("Activate your account !");\n                    walletshow.setTextColor(Color.RED);\n                    Log.d("LOGGER", "No such document");\n                }\n            } else {\n                Log.d("LOGGER", "get failed with ", task.getException());\n                walletshow.setText("Login Again");\n            }\n        }\n    });\n
Run Code Online (Sandbox Code Playgroud)\n

就是这样

\n

Ale*_*amo 5

基本上,我创建了一个 Android 应用程序,用户在其中充值,然后 Firestore 的值更改为新值,但在 Android 应用程序中没有任何更改。

这是预期的行为,因为您使用的是DocumentReference#get()调用,该调用仅:

读取此 DocumentReference 引用的文档。

如果您想监听实时更新,那么您应该考虑使用DocumentReference#addSnapshotListener() ,它:

开始侦听此 DocumentReference 引用的文档。

正如官方文档中所解释的:

在代码中将是:

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");
        }
    }
});
Run Code Online (Sandbox Code Playgroud)