0

I use docRef.get() to get a Map of a collection from the Cloud Firestore. However, I cannot use the value in the map after I leave public void onSuccess(DocumentSnapshot documentSnapshot) method. In JS, I know I can do a subscribe method but in Android I don't know what to do.

This is my code to get the Map:

docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if(documentSnapshot.exists()){
                    doc = documentSnapshot.getData();
                    Toast.makeText(ChatActivity.this,"Data loaded",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(ChatActivity.this,"No data exists",Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(ChatActivity.this, "Error", Toast.LENGTH_SHORT).show();
                Log.d("TAG",e.toString());
            }
        });

And I want to use the Map after that, to set the textView to be the message:

for(String key : doc.keySet()){
    message += key + "\n" + doc.get(key)+"\n";
} 
ui.setText(message);
Andrew
  • 795
  • 4
  • 18
Yu Peijia
  • 13
  • 4

1 Answers1

1

As @a_local_nobody points, Firestore calls are Asynchronous and you could use a callback to trigger when you have downloaded that data and this are disponible. Your doc variable have this data disponible once the onSuccess callback are executed but maybe other part of your code use it before onSuccess are called (Async).

Another approach would be to wrap your code into a method and use them inside the onSuccess principal callback, so you are sure this method will execute when the data get disponible and you don't need an extra interface to use it as callback:

public void setMessagesToUi(Doc doc){
for(String key : doc.keySet()){
    message += key + "\n" + doc.get(key)+"\n";
} 
ui.setText(message);
}

And then use it:

docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if(documentSnapshot.exists()){
                    setMessagesToUi(documentSnapshot.getData());
                    Toast.makeText(ChatActivity.this,"Data loaded",Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(ChatActivity.this,"No data exists",Toast.LENGTH_SHORT).show();
                }
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(ChatActivity.this, "Error", Toast.LENGTH_SHORT).show();
                Log.d("TAG",e.toString());
            }
        });
Bogdan Android
  • 1,345
  • 2
  • 10
  • 21