I'm trying to retrieve all documents from my Firestore collection called "users', but I get an error message. I've tried to retrieve a single document too, but got the same error.
Database connection | 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:
CodePudding user response:
As the error message says, your db
field is never initialized. You probably want to do that in the Database()
method:
db = FirestoreDatabase.getInstance();
Also see the Firebase documentation on initializing Firestore.