I'm trying to get a String value from my Firestore Database and assigning it to a TextView to test my connection to the database, but I'm not having any luck at all.
I have all dependencies in my .gradle file and both my app and firestore are linked. My Firestore usage even says I have read the database 27 times so far, but I can't seem to get the String value and use it in my TextView.
Here's what I've right now after trying numerous other ways
FirebaseFirestore db = FirebaseFirestore.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
tvMenu = findViewById(R.id.tvMainMenu);
btOpenOs = findViewById(R.id.btNewOs);
DocumentReference docRef =
db.collection("usuarios")
.document("idtest");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String dbValue = document.getString("password");
Log.d("TAG", "DocumentSnapshot data: " document.getData());
} else {
Log.d("TAG", "No such document");
}
} else {
Log.d("TAG", "get failed with ", task.getException());
}
}
});
tvMenu.setText(value);
}
This just sets my TextView to nothing, as if the string value was null. The value I'm expecting is "teste".
CodePudding user response:
Any code that needs to have access to the data from the database, has to be inside the completion listener that gets called when that data is available.
So:
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String dbValue = document.getString("password");
tvMenu.setText(dbValue); //