Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map FireStore Collection to Java POJO

I'm using FireStore database and I am wondering how can I convert these collections from "Hospital/DcbtizNr0ADNNnd0evlN" into a Java object? I mean, how could I search (with 1 query) for a specific Hospital and get all its documents and collections mapped to a java object?

This is my database structure

Pacientes/Fichas/Profissionais follows almost the same structure:

enter image description here

like image 813
Raphael Cardoso Fernandes Avatar asked Jan 30 '23 09:01

Raphael Cardoso Fernandes


1 Answers

You can easily map a QuerySnapshot to a list of objects, assuming your app contains a Hospital POJO class that matches the data:

db.collection("Hospital")
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    // Convert the whole snapshot to a POJO list
                    List<Hospital> objects = task.getResult().toObjects(Hospital.class);
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

The Hospital class could look like this:

public class Hospital {

  // These can either be public properties, or private properties
  // with standard-named getters and setters like getAvenida() and
  // setAvenida()
  public String avenida;
  public String bairro;
  public String cep;
  public String cidade;
  public String estado;
  public String name;
  public String numero;

  // Empty constructor required
  Hospital() {}

}

reference: https://firebase.google.com/docs/firestore/reference/android/QuerySnapshot.html#toObjects(java.lang.Class)

like image 100
Sam Stern Avatar answered Jan 31 '23 23:01

Sam Stern