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(); } }); }
Advertisement
Answer
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.