登录后如何将新用户数据保存到Firebase实时数据库 [英] How to save new user data to Firebase Realtime Database after Login
本文介绍了登录后如何将新用户数据保存到Firebase实时数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了一个函数,可以将新的用户数据写入这样的数据库
I have written a function to write new user data if needed to database like this
private void writeNewUserIfNeeded(final String userId, final String username, final String name) {
final DatabaseReference usersRef = rootRef.child("users");
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(userId))
usersRef.child(userId).setValue(new User(username, name));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
但是问题是即使调用了该函数,也从未调用 onDataChange
,所以我无法保存新的用户数据.保存新数据的最佳做法是什么?
But the problem is the onDataChange
never called eventhough the function is called, so I cannot save my new user data. How is the best practice to save the new data?
更新:添加规则这是我写的规则
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"users": {
"$uid": {
".read" : "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
推荐答案
我已经解决了该问题.只需要添加 UID
I already fix the problem.
Only need add child of the UID
private void writeNewUserIfNeeded(final String userId, final String username, final String name) {
final DatabaseReference usersRef = rootRef.child("users").child(userId);
usersRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists())
usersRef.setValue(new User(username, name));
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
这篇关于登录后如何将新用户数据保存到Firebase实时数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文