I have this code: CollectionReference usersRef = db.collection("users"); private void…
- User
I have this code:
CollectionReference usersRef = db.collection("users"); private void saveToDB() { Map<String, Object> userdb = new HashMap<>(); userdb.put("score", amount);
usersRef.document(Objects.requireNonNull(mAuth.getUid())).set(userdb) //update-set .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { Log.d("TagDB", "Successfully added"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.w("TagDB","Error adding document",e); } }); } - Assistant
- User
Okay, but I need to retrieve the data associated with the current user. So please finish: private void readFromDB() {
} - Assistant
To retrieve the data associated with the current user, you can use the obtained from the and the current user's ID. Below is how you would typically implement the function in your code to fetch the user's score from Firestore:
- User
E FATAL EXCEPTION: main Process: com.HidiStudios.BeST, PID: 12223 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.HidiStudios.BeST/com.HidiStudios.BeST.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseAuth.getUid()' on a null object reference
- Assistant
The error message you're seeing indicates that there is a
NullPointerExceptionwhen callinggetUid()on an instance ofFirebaseAuth. This is usually caused when theFirebaseAuthinstance (mAuthin your case) has not been initialized before you try to use it.To resolve this issue, you need to ensure that you have initialized the
FirebaseAuthinstance before calling any methods on it, includinggetUid(). Here’s how you can initialize theFirebaseAuthinstance:private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up the content view, etc. // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); // Now you can use mAuth safely }