简体   繁体   中英

addListenerForSingleValueEvent keeps duplicating output

I use addListenerForSingleValueEvent to add value into the child "code" of the current user, but instead the data duplicated. Here is the database before the coding

This is the coding for the addListenerForSingleValueEvent

 b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mAuth = FirebaseAuth.getInstance(); mUser = mAuth.getCurrentUser(); final String UserId = mUser.getUid(); mReference = FirebaseDatabase.getInstance().getReference("Users"); final DatabaseReference currentUserId = mReference.child(UserId); currentUserId.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { User user = dataSnapshot.getValue(User.class); user.setCode(riasec1); currentUserId.child(UserId).setValue(user); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } });

Here is the database after the coding is executed Why is the whole user being duplicated instead of only value "code" inserted?

When you call

currentUserId.child(UserId).setValue(user);

you are saying "add WHOLE user in to node with name 'UserId'" . In general you are fetching WHOLE User, updating one field and updating again.


So when would you like to update a child without rewriting the entire object u should pass node name, eg

currentUserId.child(UserId).child("code").setValue(riasec1);

In this call you say:

  • find node with proper ID ( UserId )
  • find node "code"
  • set new value ( riasec1 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM