我想在用户注册到我的应用时添加Firebase多个数据,包括一个带有一些孩子的节点“Scores”,但我不知道如何添加它。
Firebase数据库:
"Users" : {
"L89LA3099j-VAhi5Y5P" : {
"Admin" : false,
"Email" : "example@domain.com",
"Nickname" : "Anonymous",
"Picture" : "https://firebasestorage.googleapis.com/v0/b/cul...",
"Scores" : {
"Arts" : 0,
"Classical music" : 0,
"Literature" : 0
}
}
}
以下是Android Studio中的代码:
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password).addOnCompleteListener(UserRegistration.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(UserRegistration.this, "Invalid email or already existed email!", Toast.LENGTH_SHORT).show();
} else {
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
HashMap<String, Object> user_data = new HashMap<>();
user_data.put("Admin", false);
user_data.put("Email", email); // I got it correctly from EditText
user_data.put("Picture", "https://firebasestorage.googleapis.com/v0/b/cul...");
user_data.put("Nickname", "Anonymous");
usersRef.child("Users").push().setValue(user_data);
DatabaseReference scores_ref = usersRef.child("Scores"); // I guess it's wrong to do it like this
HashMap<String, Integer> user_scores = new HashMap<>();
user_scores.put("Arts", 0);
user_scores.put("Classical music", 0);
user_scores.put("Literature", 0);
// and now how to add Scores node inside the created user?
答案 0 :(得分:2)
如果您想在用户下添加Scores
,请尝试以下操作:
首先使用userid而不是push()
FirebaseUser mCurrentUser= task.getResult().getUser();
String userid=mCurrentUser.getUid();
然后改变这个:
usersRef.child("Users").push().setValue(user_data);
到此:
usersRef.child(userid).setValue(user_data);
DatabaseReference scores_ref =usersRef.child(userid).child("Scores");
scores_ref.child("Arts").setValue(0);
scores_ref.child("Classical music").setValue(0);
scores_ref.child("Literature").setValue(0);
userRef
指向孩子Users
这一行usersRef.child(userid).setValue(user_data);
将创建以下内容:
Users
userid
Admin : false
Email : example@domain.com
Nickname" : Anonymous
Picture" : https://firebasestorage.googleapis.com/v0/b/cul...
然后这一行DatabaseReference scores_ref =usersRef.child(userid).child("Scores");
将传递节点Users
,然后传递节点userid
,它将添加子Scores
及其子节点。所有这些都将在当前的userid
下。