0

hi i'm trying to update some of user's data username and password

enter image description here

my code below checks if email of current user are exists or not if exists i want to update the old informations with new informations, but my code doesn't work ,it adds me a new user instead of updating user data

update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressBar.setVisibility(View.VISIBLE);
                updateUser();
            }
        });


private void updateUser() {
        final DatabaseReference mUser = mDatabase.child("users").child("id");
        mUser.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    User user = postSnapshot.getValue(User.class);
                    assert user != null;
                    String emailUser = user.getEmail();
                    if (email.equals(emailUser)) {
                        user.setUsername(name.getText().toString());
                        user.setPassword(newpassword.getText().toString());
                        user.setImageBase64(imageBase64);
                        mUser.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                Toast.makeText(getActivity(), "Votre compte a été modifé!", Toast.LENGTH_LONG).show();
                                startActivity(new Intent(getActivity(), LoginActivity.class));
                            }
                        });
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
ali
  • 189
  • 3
  • 14

2 Answers2

0

You're calling updateUser("id");. You probably want to call it as updateUser(id);

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
0

When you are using this line of code:

mUser.setValue(user)

It means that you are adding a new user under: users/id, it doesn't mean that you are updating that particular user. In order to update a value within a user object, I recommend you using a Map like this:

Map<String, Object> map = new HashMap<>();
map.put("password", newpassword.getText().toString());
mUser.child("-L7vu-6HqcC_YJW40fYa").updateChildren(map);

As you can see, I have used updateChildren() method instead of setValue() and I also have added the child that is missing from your reference.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193