Reputation: 13
I am getting a null pointer reference while using firebase firestore and my app is crashing. Here's my code :
private FirebaseFirestore fstore=FirebaseFirestore.getInstance();
private DocumentReference documentReference=fstore.collection("users").document("17030121084");
@Override
protected void onStart(){
super.onStart();
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (documentSnapshot.exists()){
String semester=documentSnapshot.getString("sem");
sem.setText(semester);
}
}
});
}
The sem here refers to my field in my document 17030121084.
Can someone please suggest a solution for this?
Upvotes: 1
Views: 521
Reputation: 598728
If there was an error while trying to read the document, the documentSnapshot
variable will be null
. So your code needs to check for that.
The simplest way to do so is by adding a simple null
check:
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (document != null && documentSnapshot.exists()){
String semester=documentSnapshot.getString("sem");
sem.setText(semester);
}
}
But the above code is not handling the error yet. And since clearly document
is null
in your situation, you'll actually need to know what the error is in order to be able to fix it.
So this is a better approach:
public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log(TAG, "Listen failed.", e);
return;
}
if (documentSnapshot.exists()){
String semester=documentSnapshot.getString("sem");
sem.setText(semester);
}
}
Note that this code closely matches what's in the documentation on listening for documents, so I highly recommend spending some time there.
Upvotes: 1