首页 > 解决方案 > 如何将 Firebase Firestore 连接到实时数据库?

问题描述

我做了一个应用程序,用户可以通过测验获得积分。我也有排行榜。

我的主数据库是 cloud firestore。但我需要排行榜更加实时,就像每次用户在不刷新或关闭片段的情况下获得积分时都需要更新。

所以我需要将firebase firestore连接到实时数据库,(如果我更改firestore数据(如指定用户的硬币或任何),它也需要更改实时数据)

我编写了代码,但效果不佳。我在这里附上了代码。

 private void LoadFirestore() {
    firebaseFirestore.collection("Users")
            .document(FirebaseAuth.getInstance().getUid())
            .get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
        @Override
        public void onSuccess(DocumentSnapshot documentSnapshot) {

            user = documentSnapshot.toObject(User.class); 
            totalCoins.setText(String.valueOf(user.getCoins()));

        }
    });
}


private void uploadToRealtime() {

    HashMap<String, Object> map = new HashMap<>();
    map.put("coins", totalCoins);
    firebaseDatabase.getReference().child("Users").child(FirebaseAuth.getInstance().getUid())

            .updateChildren(map);


            }
}

标签: androidfirebasefirebase-realtime-databasegoogle-cloud-firestore

解决方案


您可以使用 aonSnapshotListener直接从firestore实时获取fata。这是一个基本示例:

final DocumentReference docRef = db.collection("cities").document("SF");
docRef.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");
        }
    }
});

你可以在这里查看更多信息。

仅为实时功能创建与 RealtimeDatabase 的同步在这里没有任何意义,并且会给您的 Firebase 项目带来更多成本。


推荐阅读