I'm fetching data from Firestore. I want to set the string data to a TextView. I'm able to get the data successfully . i.e I'm able to log it in the logcat. But when I try to set the text,it shows null in place of the data
Here is my code :
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
yourSector=view.findViewById(R.id.Sector_tv);
yourPincode=view.findViewById(R.id.Pincode_tv);
DocumentReference docRef = db.collection("customerUsers").document(userID);
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
pincode = document.getString("pincode");
sector = document.getString("sector");
Log.d("pincodetest", "onComplete: "+pincode);
} else {
Log.d("docref", "No such document");
}
} else {
Log.d("docref", "get failed with ", task.getException());
}
}
});
String sectorText="Sector : " + sector;
String pincodeText="Pincode : "+pincode;
yourSector.setText(sectorText);
yourPincode.setText(pincodeText);
My logcat (shows the correct data):
2020-06-14 00:41:43.779 14633-14633/? D/pincodetest: onComplete: 110001
When I set the text, on my screen I get: Sector : null
PS: Strings pincode,sector have already been declared outside onViewCreated
The OnCompleteListener completes asynchronously so you need to place your setTexts within the onComplete method of it. In other words, the sector and pincode local variables are not populated with data when they are accessed for the concatenation to form the sectorText and pincodeText Strings.
In simpler terms, the onComplete method runs after the string concatenation. Therefore, during the string concatenation the value of the variables sector and pincode are still null.
I've done a little fix in the code below:
if (document.exists()) {
pincode = document.getString("pincode");
sector = document.getString("sector");
Log.d("pincodetest", "onComplete: "+pincode);
String sectorText="Sector : " + sector;
String pincodeText="Pincode : "+pincode;
yourSector.setText(sectorText);
yourPincode.setText(pincodeText);
}