android - 如何将 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);
}
}
解决方案
您可以使用 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 项目带来更多成本。
推荐阅读
- shell - 为什么 'next' 对 awk 有影响
- c# - richTextBox 在 dataGridView CurrentCellChanged 事件上获得“额外的行”
- merge - SAS 占位符值
- awk - 根据第一列比较两个文件,打印一个文件的唯一部分
- compiler-construction - 计算行政范式
- python - Python中for循环问题内的Tkinter按钮
- javascript - 如何从所有节点生成带有 JSON.stringify 的数组
- security - VSTS 隐藏构建和发布菜单
- python - 给定范围的 Python 打印浮点数列表
- linux - 处理 kmalloc 返回的优化