【问题标题】:update data in real time from Firestore从 Firestore 实时更新数据
【发布时间】:2021-12-03 11:02:19
【问题描述】:

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

这是我的代码:

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");
            }
        }
    });

就是这样

【问题讨论】:

    标签: java android firebase google-cloud-platform google-cloud-firestore


    【解决方案1】:

    基本上,我创建了一个 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");
            }
        }
    });
    

    【讨论】:

    • 如何在已经存在一些字段的 Firestore 中添加一个额外的字段我想从另一个活动中再添加 1 个字段作为顶部的类似图像
    • 在这种情况下,您必须执行update() 操作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2018-06-15
    • 2019-02-06
    • 2022-10-02
    • 2019-10-12
    • 2019-07-12
    • 1970-01-01
    相关资源
    最近更新 更多