Firebase Firestore retrieve data Synchronously/without callbacks

后端 未结 2 1651
再見小時候
再見小時候 2020-12-09 05:02

I am using Cloud Firestore in a separate thread in my Android app, so I don\'t want to use listeners OnSuccessListener and OnFailureListener to run

2条回答
  •  抹茶落季
    2020-12-09 05:33

    Your can do something like this on the main thread...

    YourObject yourObject = (YourObject)new RunInBackground().
                              execute("someCollection","someDocument").get()
    

    And the background thread is...

    public class RunInBackground extends AsyncTask {
    
      @Override
      protected Object doInBackground(Object[] objects) {
    
        Task documentSnapshotTask = FirebaseFirestore.getInstance().
                 collection((String) objects[0]).document((String) objects[1]).get();
    
        YourObject obj=null;
    
        try {
            DocumentSnapshot documentSnapshot = Tasks.await(documentSnapshotTask);
    
            obj = new YourObject();
            obj.setter(documentSnapshot.get("your field"));
    
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        return obj;
      }
    }
    

提交回复
热议问题