尝试使用 Firestore 数据库从 "users" 集合中检索所有文档时出错

Getting error while trying to retrieve all documents from "users" collection with Firestore Database

我正在尝试从名为“users”的 Firestore 集合中检索所有文档,但我收到一条错误消息。我也尝试检索单个文档,但遇到了同样的错误。

错误:

数据库连接 | Database.java

  public Firestore db;

public Database() throws IOException {
    // Use a service account
    try {

        InputStream serviceAccount = new FileInputStream("./serviceAccount.json");
        GoogleCredentials credentials = GoogleCredentials.fromStream(serviceAccount);
        FirebaseOptions options = FirebaseOptions.builder()
           .setCredentials(credentials)
           .setDatabaseUrl("https://riskgameverycool.firebaseio.com/")
           .build();

        FirebaseApp.initializeApp(options);
        System.out.println("Connection  GREAT Success!");
    } catch(Exception e) {
      //  Block of code to handle errors
      e.printStackTrace();
      System.out.println("Connection Failed.");
    }
}

Database.java:

public void getAllUsers() {
    try {
        // asynchronously retrieve all documents
        ApiFuture<QuerySnapshot> future = db.collection("users").get();
        // future.get() blocks on response
        List<QueryDocumentSnapshot> documents = future.get().getDocuments();
        for (QueryDocumentSnapshot document : documents) {
          System.out.println(document.getId() + " => " + document.toObject(User.class));
        }
    } catch(Exception e) {
        e.printStackTrace();
        System.out.println("Query messed up.");
    }
}

Firestore:

如错误消息所述,您的 db 字段从未初始化。您可能想在 Database() 方法中这样做:

db = FirestoreDatabase.getInstance();

另请参阅 initializing Firestore 上的 Firebase 文档。