0

I'm using the below code for inserting data to the Firebase real-time database:

private void addUserDataToFirebase(String name,String phoneNumber,String email){

    firebaseDatabase = FirebaseDatabase.getInstance();
    databaseReference = firebaseDatabase.getReference().child("Users");

    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            HashMap<String , String > usermap = new HashMap<>();

            usermap.put("Name",name);
            usermap.put("Email",email);
            usermap.put("PhoneNumber",phoneNumber);

            databaseReference.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(usermap);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(RegisterActivity.this, "data added", Toast.LENGTH_SHORT).show();
        }
    });
}

enter image description here

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84

1 Answers1

3

If you only want to write the user to the database, there is no need to attach a ValueEventListener. You can only use:

HashMap<String, String > usermap = new HashMap<>();
usermap.put("Name",name);
usermap.put("Email",email);
usermap.put("PhoneNumber",phoneNumber);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseReference.child(uid).setValue(usermap);

There is no need to read anything, or listen for real-time updates, when writing data, unless you need to do some verifications, for example, to check if the user already exists.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hey, Rushikesh. Can I help you with other information? – Alex Mamo Sep 22 '22 at 06:51
  • yes, please. The code in the below link is written in onCreate method of MainActivity. So the problem is application is not navigating to loginActivity from mainActivity else it is executing mainActivity code. https://stackoverflow.com/questions/73818245/im-using-below-code-to-nevigate-to-loginactivity-from-mainactivity-but-the-cond – Rushikesh khandekar Sep 23 '22 at 03:23
  • I'll take a look and if I'll know the answer, I'll write to you. – Alex Mamo Sep 23 '22 at 06:38