0

I want my code to change a TextView and change its content that can be seen for the following 5s. Then the activity has to finish.

firestore.collection("Game").document(gameID).addSnapshotListener(new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
        firestore.collection("Room").document(roomID).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                if(documentSnapshot.getLong("inPlayers") == documentSnapshot.getLong("numPlayers")){
                    Intent in = new Intent(WaitingRoom.this, Game.class);
                    loadingView.setVisibility(View.GONE);
                    textoEsperando.setText("Starting...");
                    in.putExtra("roomID", roomID);
                    in.putExtra("gameID", gameID);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    startActivity(in);
                    finish();
                }
            }
        });
    }
});

That's my code. I've done it inside a EventListener for changes in a document in Firestore. The problem is that first waits the 5s and then in the last moment apply the changes in the TextView and finishes. I don't know what's goin on to execute first the sleep and then the other parts of the code.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
arranz99
  • 11
  • 2
  • `Thread.sleep` is a anti-pattern for wiating in Android apps. Consider something like this: https://stackoverflow.com/questions/11548864/how-to-make-an-android-program-wait or more from this search: https://www.google.com/search?q=how+to+wait+a+certain+time+in+an+android+app – Frank van Puffelen Jun 29 '22 at 01:32
  • That's not how you should handle such situations. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-cloud-firestore-using-get-bf03b6ee4953). – Alex Mamo Jul 06 '22 at 09:23

0 Answers0