Unable to Update Firebase user table with userId

2019-09-21 08:12发布

问题:

In here I create a 'Firebase' user in the signup process with 'firstName', 'lastName', 'email', 'password'. After successful login I load all signup values to another screen with new two "Edittext'. Now I need to update that signup table by 'Firebase' 'userId' with new two values 'country' and 'occupation' that is entered in new 'EditText'. For do that signup process and add new values I used "UserProfileBean' class.

below is the code.

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("new_user");
        FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
        String userid=user.getUid();


        final UserProfileBean userProfileBean = new UserProfileBean();
        userProfileBean.setCountry(country.getText().toString());
        userProfileBean.setOccupation(occupation.getText().toString());

        Log.d("UPDATE_PROFILE", "UPDATE_PROFILE_DATA" + userid + "," +
                userProfileBean.getOccupation() + ", " + userProfileBean.getCountry());

        //myRef.child(userid).child("country").setValue(userProfileBean.getCountry());

        Query pendingTasks = myRef.child(userid).orderByChild("country").equalTo("");
        pendingTasks.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot tasksSnapshot) {
                for (DataSnapshot snapshot: tasksSnapshot.getChildren()) {
                    snapshot.getRef().child("country").setValue(userProfileBean.getCountry());
                    snapshot.getRef().child("occupation").setValue(userProfileBean.getOccupation());
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                System.out.println("The read failed: " + databaseError.getMessage());
            }
        });

above code is implemented by button 'onclickListener'.

回答1:

To update the user node, try the following:

FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("User").child(useruid);

 Map<String,Object> update=new HashMap<>();
 update.put("Country",userProfileBean.getCountry());
 update.put("Occupation",userProfileBean.getOccupation());

ref.updateChildren(update);

more info here:

https://firebase.google.com/docs/database/android/read-and-write#update_specific_fields