Skip to content Skip to sidebar Skip to footer

Android Firebase: User-specific Real-time Data Is Removed When User Logs Back In

I am using Firebase Google authentication for login, and I had a list of data points associated with a user. The user populates their data by creating elements in a logged-in sessi

Solution 1:

The problem is in your writeNewUser() method. It looks like this is called every time the user authenticates - not just the first time (which the "new user" would suggest).

You have three options:

  1. Restructure your code so you check to see if the user exists, and then only writes the user info if it does not exist.

  2. Restructure your code so only changed data is updated.

  3. Restructure your data so user information is stored one level deeper - thus overwriting it doesn't change any of the sibling nodes.

You could implement 3 with something like:

privatevoidwriteNewUser(String userId, String[] names, String username, String email,String uid) {
    User user = newUser(username,names[0],names[1], email, uid);
    myUsers.child(userId).child("userInfo").setValue(user);
}

Solution 2:

You are overwriting the data because you are using the setValue() method. In stead of using that method, use updateChildren() method and your problem will be solved.

Hope it helps.

Solution 3:

To check if a user exists in Firebase Realtime Database before adding one upon user login/registration in Android:

privatevoidwriteNewUser(final String userId, String[] names, String username, String email,String uid) {
    final User user = newUser(username,names[0],names[1], email, uid);
    myUsers.addListenerForSingleValueEvent(newValueEventListener() {
        @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
            if (!dataSnapshot.hasChild(userId)) {
                myUsers.child(userId).setValue(user);
            }
        }
        @OverridepublicvoidonCancelled(DatabaseError databaseError) {}
    });

}

I got the tip from here and the guidance of @Prisoner's answer.

Post a Comment for "Android Firebase: User-specific Real-time Data Is Removed When User Logs Back In"