Home > Mobile >  How to get data from a specific field in Firestore (Android)
How to get data from a specific field in Firestore (Android)

Time:12-27

I am looking to get value from specific field in firestore. Below is my sample json from firestore

{
   "details":{
      "name":"rahul",
      "country":"India",
      "phone":"1234567890"
   },
   "course":{
      "subject":"cs",
      "duration":"6 months"
   }
}

I want to get the data from the field "details". I tried this below method and it's not working

override fun getStudentDetails() = callbackFlow {
    val snapshotListener =
        db.collection("studentDetails")
            .document(Constants.FirestoreCollections.STUDENT_DETAILS_ID)
            .collection(Constants.FirestoreCollections.Organisation.STUDENT_DETAILS)
            .addSnapshotListener { snapshot, e ->
                val taskResponse = if (snapshot != null) {
                    val tasks = snapshot.toObjects(Details::class.java)
                    Response.Success(tasks)
                } else {
                    Response.Failure(e)
                }
                trySend(taskResponse)
            }
    awaitClose {
        snapshotListener.remove()
    }
}

Is there any way to achieve this?

CodePudding user response:

Your snapshot object is a DocumentSnapshot. If you want to get a specific field, you can call get("details.name") (or any other relevant path).

CodePudding user response:

To get the value of a specific field in the JSON data you provided, you can use the dot notation to access the field. For example, to get the value of the "name" field, you can use the following code:

jsonData.details.name

This will return the value "rahul". Similarly, you can use the dot notation to access other fields in the JSON data, such as "country" or "duration".

For example, to get the value of the "duration" field, you can use the following code:

jsonData.course.duration

This will return the value "6 months".

You can also use square bracket notation to access the fields in the JSON data. For example, the following code will also return the value of the "name" field:

jsonData['details']['name']

Keep in mind that the field names in the JSON data are case-sensitive, so make sure to use the correct capitalization when accessing them.

  • Related