How to save new user data to Firebase Realtime Database after Login

丶灬走出姿态 提交于 2021-01-27 21:30:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!