2
votes

So, I create firebase user profile in firestore, it will save users data such as their name, email, phone number, and their reward point. The user logged in using Google Sign-in.

This is how I write the data to firestore.

 private void addNewUser() {
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        String uid = user.getUid();
        for (UserInfo profile : user.getProviderData()) {
            // Id of the provider (ex: google.com)
            String providerId = profile.getProviderId();

            // UID specific to the provider

            // Name, email address, and profile photo Url
            String name = profile.getDisplayName();
            String email = profile.getEmail();


            Map<String, Object> newUser = new HashMap<>();
            newUser.put("Nama", name);
            newUser.put("Email", email);




            // Add a new document with a generated ID
            db.collection("users").document(uid).set(newUser);
                        }


        }


    }

And that one works.

But when I try to retrieve the data using Document Reference

    @Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user != null) {
        String curUser = user.getUid();
        DocumentReference documentReference = db.document(curUser);
        documentReference.addSnapshotListener(this.getActivity(), new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@javax.annotation.Nullable DocumentSnapshot documentSnapshot, @javax.annotation.Nullable FirebaseFirestoreException e) {
                if (documentSnapshot.exists()) {
                    String userNama = documentSnapshot.getString(KEY_NAMA);
                    String userEmail = documentSnapshot.getString(KEY_EMAIL);

                    namaUser.setText(userNama);
                    emailUser.setText(userEmail);
                }
            }
        });




    } else {

        Intent intent = new Intent(Home.this.getActivity(), LoginActivity.class);
        startActivity(intent);


        }

    }

The document reference curUser in this case, returning null. I didn't know what did I do wrong.

1

1 Answers

2
votes

You need to have the collection name (users) in your DocumentReference

Change,

DocumentReference documentReference = db.document(curUser);

to,

DocumentReference documentReference = db.collection("users").document(curUser);