Android & Firebase Async tasks

Asked

Viewed 143 times

0

I have a class Java that I overwrote the method toString() within this method before returning I consult firebase and fill an object. My problem is the following return of toString() ends up being executed before firebase has filled the object. How can I tell the class to wait for the object to be filled before returning the same

public class exom(){
 private String ID;
 private String horaInicio;
 private String horaFim;
 private String IDEvento;
 // Objeto que deve vir do firebase
 Objeto obj;
  //Getters and setters....
   @Override
   public String toString() {
     FireDB fireDB = new FireDB(null);
     fireDB.getMdatabase().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
           for (DataSnapshot child : dataSnapshot.getChildren()) {
            obj = child.getValue(Objeto.class);
           }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

     return horaInicio + " - " + horaFim + " - "+ obj.getNome();
   }
}

1 answer

0

It’s actually not a good practice for you to perform this type of query that you need to "wait" on the main thread. As for firebase, unfortunately (or fortunately) it does not have a synchronous form to obtain data.

You should fill in the object before making any comparison with toString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.