solid_soap
solid_soap

Reputation: 55

How to retrieve and display data from users that are logged in - Firestore

I am trying to get and display my user's information when they are logged in. (i.e: name, email, phone)

I have tried multiple snippets i have found on youtube and on stack overflow but they have failed. Most tutorials use realtime Database, which is not what i am looking for.

I have also tried making a "users" object.

private void getData(){
        FirebaseFirestore db = FirebaseFirestore.getInstance();

        db.collection("users")
                //.document(FirebaseAuth.getInstance().getCurrentUser().getUid())
                .whereEqualTo("email:", FirebaseAuth.getInstance().getCurrentUser().getUid())
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (DocumentSnapshot document : task.getResult()) {
                                //Toast.makeText(getApplicationContext(),document.getId() +"==>" + document.getData(),Toast.LENGTH_LONG).show();
                                //Toast.makeText(getApplicationContext(),""+ document.get("Email") ,Toast.LENGTH_LONG).show();

                                nameEdt.setText((CharSequence) document.get("First Name"));
                                emailEdt.setText((CharSequence) document.get("Email"));
                                phoneEdt.setText((CharSequence) document.get("Phone"));


                            }
                        } else {
                            Toast.makeText(getApplicationContext(),"No such document",Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

Database Structure: db structure

I understand that documents in firestore are not associated with users, but i dont know how to set my code up so that it only retrieves data from the user that is signed in* It works fine for newly created accounts, but if i were to log out and sign in with a different user it will not update the "account/user information".

In short, how would I access and display my database information from signed in users?

Additional Notes: I am using Email and Password for authentication

Upvotes: 2

Views: 7456

Answers (2)

solid_soap
solid_soap

Reputation: 55

After a couple days head butting at trying to find a solution, i have found one that is able to retrieve user information from the database. However it is important to note that because my application is not holding a lot of data so this structure works for me.

So i was essentially on the right track, but with some lack of understanding of firebase i missed a few concepts.

    private void getData(){
        FirebaseFirestore db = FirebaseFirestore.getInstance();
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        final String current = user.getUid();//getting unique user id

        db.collection("users")
                .whereEqualTo("uId",current)//looks for the corresponding value with the field
                // in the database
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (DocumentSnapshot document : task.getResult()) {

                                nameEdt.setText((CharSequence) document.get("firstName"));
                                emailEdt.setText((CharSequence) document.get("email"));
                                phoneEdt.setText((CharSequence) document.get("phone"));
                                // These values must exactly match the fields you have in your db

                            }
                        } 

As mentioned before, documents do not associate with users, but you CAN link them together by creating a field in your db called "whatever your want" (i made mine uId). This is because firebase generates a unique id for each user when authenticated. By creating a field that holds that unique id you are able to retrieve the associated information in that collection.

bd struc

How to create the field: I created a "user" object that would grab the uid from my edit text. In my code, i passed the uid wherever i was creating/authenticating a new user/account.

FirebaseUser testUser = FirebaseAuth.getInstance().getCurrentUser(); //getting the current logged in users id
                            String userUid = testUser.getUid();                       
                            String uidInput = userUid;

User user = new User(firstNameInput,lastNameInput,uidInput);

 db.collection("users").document(userUid)
                                    .set(user)
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {

note: I believe you can also add it to your hash map if you have it done that way.

Upvotes: 1

Jack
Jack

Reputation: 5614

To access your user data stored in Firestore, it shouldn't be as complicated as you thought, there's no queries needed, you just need to fetch the documents corresponding to the user's uid, and fetch the specific fields or do whatever you need with them, like this:

db.collection("users").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
        .get().addOnCompleteListener(task -> {
    if(task.isSuccessful() && task.getResult() != null){
        String firstName = task.getResult().getString("First Name");
        String email = task.getResult().getString("Email");
        String phone = task.getResult().getString("Phone");
        //other stuff
    }else{
        //deal with error
    }
});

Original Answer:

User information is not stored in the Firestore database, they are associated with the Firebase Authentication which you set up for the log in. To retrieve the related user information, you need to use the related FirebaseAuth APIs. Use this to retrieve the current log in user:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

Then you can get the name and email with something like this:

String name = user.getDisplayName();
String email = user.getEmail();

For more information, refer to the documentation.


If FirebaseAuth doesn't resolve, that probably means you didn't follow the set up guides correctly and forgot to include the dependency in your gradle file:

implementation 'com.google.firebase:firebase-auth:17.0.0'

Upvotes: 5

Related Questions