Skip to content Skip to sidebar Skip to footer

Convert Documentsnapshot Data To List

I want to read each Object list from the document 'list_of_clients' and export it to a custom List that i created In Realtime Database there is a function called GenericTypeIndicat

Solution 1:

To make it work, please see the following steps. So, in order to deserialize the fields correctly, please consider using a model class that looks like this:

publicclassUserList {
    privateString userAddr, userName, userPhone;

    publicUserList() {}

    publicUserList(String userAddr, String userName, String userPhone) {
        this.userAddr = userAddr;
        this.userName = userName;
        this.userPhone = userPhone;
    }

    publicStringgetUserAddr() {return userAddr;}

    publicStringgetUserName() {return userName;}

    publicStringgetUserPhone() {return userPhone;}
}

See the naming convention? Firebase will always look after fields that look like userAddr and a public getter that look like getUserAddr().

To add a UserList object in a correct way to your Cloud Firestore database, please use the following code:

UserListuserList=newUserList("Bolintin Vale", "Bogdan", "0251206260");
StringdocId= rootRef.collection("clients").document().getId();
rootRef.collection("clients").document(docId).set(userList);

To actually read the data, please use the following code:

FirebaseFirestorerootRef= FirebaseFirestore.getInstance();
rootRef.collection("clients").document("pu8NKFPNUKYgcy0yOitW").get().addOnSuccessListener(newOnSuccessListener<DocumentSnapshot>() {
    @OverridepublicvoidonSuccess(DocumentSnapshot documentSnapshot) {
        UserListuserList= documentSnapshot.toObject(UserList.class);
        Log.d(TAG, userList.getUserName());
    }
});

As you can see, I have used in my code the pu8NKFPNUKYgcy0yOitW id that was generated before. The output will be:

Bogdan

Bafta! ;)

Post a Comment for "Convert Documentsnapshot Data To List"