gpt4 book ai didi

android - 如何在同一节点中为同一用户添加多组值?

转载 作者:行者123 更新时间:2023-12-04 07:40:42 26 4
gpt4 key购买 nike

我正在使用实时数据库。因为多个用户将提供相同的数据集,如 Snapshot1 中所示。每当同一用户提交其他数据集时,它都会更新旧记录,但我想添加为新记录,就像单个用户可以像 Snapshot2 一样保存多组数据。
我的代码是:

   Contribution cont = new Contribution(money, month, payment, date, tref, rem);
FirebaseDatabase.getInstance().getReference("Contribution")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(cont).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ContributionDeclarationForm.this, "Successfully Submitted", Toast.LENGTH_LONG).show();
Intent intent = new Intent(ContributionDeclarationForm.this, DashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(ContributionDeclarationForm.this, "Not Submitted", Toast.LENGTH_LONG).show();
}
});
提前致谢。
快照1:
Snapshot1
快照2:
Snapshot2

最佳答案

为此,您可以简单地使用 DatabaseReference 的 push()方法,其中:

Creates a reference to an auto-generated child location.


所以像:
FirebaseDatabase.getInstance().getReference("Contribution")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.push().setValue(cont).addOnCompleteListener(new OnCompleteListener<Void>() {
...
这意味着您将为 (Contribution/$uid) 下的每个 child 获得一个唯一的 key 。因此,您的新架构将如下所示:
Firebase-root
|
--- Contribution
|
--- $uid
|
--- $pushedId
|
--- Amount: "369"
|
--- Contribution_Month: "5-2025"
|
--- //Other properties
如果要获取单个用户的所有子级,则需要使用指向 UID 的引用并循环遍历结果,如以下代码行所示:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Contribution").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String amount = task.getResult().child("Amount").getValue(String.class);
Log.d("TAG", amount);
}
} else {
Log.d(TAG, task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
logcat 中的结果将是上述引用下存在的每个子项的“数量”。
如果您需要数字,最好将它们作为数字和 存储在数据库中。不是 作为字符串值。

关于android - 如何在同一节点中为同一用户添加多组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67482423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com