I want to get data from my Firebase Firestore database. I have a collection called user and every user has collection of some objects of the same type (My Java custom object
let’s assume we have a document that contains a property of type array. This array is named users and holds a few User objects. The User class is very simple, contains only two properties and looks like this:
class User {
public String name;
public int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
And this is the database structure:
So our goal is to get in code the users array as a List. To achieve that, we need to attach a listener on the document and use a get() call:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference applicationsRef = rootRef.collection("applications");
DocumentReference applicationIdRef = applicationsRef.document(applicationId);
applicationIdRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List
To actually get the values out of from users array, we are calling:
document.get("users")
And we cast the object to a List. So this object is actually a List of Maps. It’s true that we can iterate through the Map, get the data out and create the List ourselves. But as DocumentSnapshot contains different flavors for the get() method, according to each data type, getString(), getLong(), getDate(), etc, it would have been very helpful if we also had a getList() method, but unfortunately we don’t. So something like this:
List users = document.getList("users");
It’s not possible. So how can we still get a List?
The simplest solution is to create another class that holds only a property of type List. It looks like this:
class UserDocument {
public List users;
public UserDocument() {}
}
And to directly get the list, only the following lines of code are needed:
applicationIdRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List users = document.toObject(UserDocument.class).users;
//Use the the list
}
}
});
Get From : How to map an array of objects from Cloud Firestore to a List of objects?