问题
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) {
}
});
}
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?
UPDATE: Add Rules And this is the rules I wrote
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"users": {
"$uid": {
".read" : "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
回答1:
Try to use addChileEventListener, here is the example
usersRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot post : dataSnapshot.getChildren()) {
}
UserModel users=dataSnapshot.getValue(UserModel.class);
items.add(users);
adapter=new CutomAdapter(items,ListShow.this);
listView.setAdapter(adapter);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Hope it works :)
回答2:
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) {
}
});
}
来源:https://stackoverflow.com/questions/43291815/how-to-save-new-user-data-to-firebase-realtime-database-after-login