0

There is a Firebase Realtime Database into which I drive in some data during registration, they fall into the Users section under the UID key from Auth:

public void writeUserToDB(Object data, String currentUser){
    DatabaseReference myRef = mDataBase.child("Users/" + currentUser);
    myRef.setValue(data);
}


mRegisterBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        
        String id = mDataBase.getKey();
        String name = mName.getText().toString().trim();
        String email = mEmail.getText().toString().trim();
        String password = mPassword.getText().toString().trim();
        String userBinder = mUserBinder.getText().toString().trim();

        
        if (TextUtils.isEmpty(email)) {
            mEmail.setError("Write your email...");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            mEmail.setError("Write your password...");
            return;
        }
        if (TextUtils.isEmpty(name)) {
            mName.setError("Write your name...");
            return;
        }
        if (password.length() < 8) {
            mPassword.setError("Password must have 8+ symbols.");
            return;
        }

        
        fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override

            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    User newUser = new User(currentUser, id, name, email, password, userBinder);

                    
                    currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
                    writeUserToDB(newUser, currentUser);

                    Toast.makeText(Register.this, "Пользователь зарегистрирован.", Toast.LENGTH_LONG).show();
                    startActivity(new Intent(getApplicationContext(), MainActivity.class));

                } else {
                    Toast.makeText(Register.this, "Произошла ошибка. Повторите." +
                            task.getException().getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        });
    }
});

In firebase it looks like:

Users:
  UID: {
    email
    name
    password
    userbinder
  }

I need to get this data in MainActivity as String variables to use when another button is clicked. UPD - that's what I tried to do, but it doesnt work and performs a different function.

String uid = FirebaseAuth.getInstance().getUid();
        mDataBase = FirebaseDatabase.getInstance().getReference();
        DatabaseReference uidRef = mDataBase.child("Users/").child(uid);
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String email = ds.child("email").getValue(String.class);
                    String userBinder = ds.child("userBinder").getValue(String.class);
                    Log.d("TAG", email + "/" + userBinder);
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
            }
        };
        uidRef.addListenerForSingleValueEvent(valueEventListener);

I need to use this data in MainActivity button:

mSosButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatabaseReference databaseReference = FirebaseDatabase.getInstance()
                        .getReference().child("Sos");
                Toast.makeText(MainActivity.this, "Message sended!", Toast.LENGTH_LONG).show();

                Sos sos = new Sos(user_email, binded_user_email);
                databaseReference.push().setValue(sos);
            }
        });
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • The code to write the user data that you shared looks fine. What is the problem you have when reading the data back? If you didn't try it yet, I recommend starting here: https://firebase.google.com/docs/database/android/read-and-write#read_data – Frank van Puffelen May 26 '22 at 20:27
  • Show us what have you tried in code to read the data. Please respond with @AlexMamo – Alex Mamo May 27 '22 at 05:01
  • @AlexMamo , i cant write my code in comments, because its too long, where can i write it, so you will see it? – asaaasssOAS May 27 '22 at 06:26
  • Please add it to your question. – Alex Mamo May 27 '22 at 06:36
  • @AlexMamo i added it, hope you will help me :) – asaaasssOAS May 27 '22 at 12:48
  • So do you want to get the data of a specific (signed-in) user, or from all users that exist in the `Users` node? – Alex Mamo May 27 '22 at 12:51
  • @AlexMamo i want to get data from signed-in user. And then use it on button click of the same class (into which I get the data). I cant show you photo of how user-data look in firebase, because i dont hav e enough reputation, but its look like: Database->Users->UID->Data i want to get. – asaaasssOAS May 27 '22 at 12:54

1 Answers1

0

To be able to get the data of the signed-in user, you have to attach a listener that points exactly to the Users node. So please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = db.child("Users").child(uid);
uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            String email = snapshot.child("email").getValue(String.class);
            String userBinder = snapshot.child("userBinder").getValue(String.class);
            Log.d("TAG", email + "/" + userBinder);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

Please notice that there is no need to loop through the results. You only need to get the data that corresponds to both fields.

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