Search code examples
androidfirebasekotlingoogle-cloud-platformgoogle-cloud-firestore

Cannot find the id using Firebase Firestore Database - Android kotlin


I'm having trouble with my code or rather fetching the data from my Firebase Firestore database. The weird thing here is that every other field ASIDE from ID can be readable. I already read the logcat and I'm getting a null ID or rather it's not getting any ID.

Here is my code for my Adapter:

holder.cardView.setOnClickListener {
    val intent = Intent(context, UpdateTenantActivity::class.java).apply {
        putExtra("room_number", tenant.id)
        Log.d("TenantAdapter", "Room ID being passed: ${tenant.id}")
    }
   context.startActivity(intent)
      // onUpdateTenant(tenant.room_number)
}

Here is the code for my data class

data class Tenant(
    val id: String = "",
    val room_number: String = "",
    val kost_name: String = "",
    val first_name: String = "",
    val phone_number: String = "",
    val floor_number: String = "",
    val room_ac: String = "",
    val water_heater: String = "",
    val room_clean: String = "",
    val room_vacancy: String = "",
    val ampere_number: String = "",
    val room_note: String = ""        
)

Here is my firestore database


Solution

  • If you want to map a Firestore document into an object of type Tenant, then all the fields in the class should have a corresponding value in the database. For example, if you have a field in your class called ampere_number, then inside your document, you should have the exact same field containing a value. In this example, there is a match, the ampere_number exists and contains the value of "4".

    The weird thing here is that every other field ASIDE from ID can be readable. I already read the logcat and I'm getting a null ID or rather it's not getting any ID.

    That is the expected behavior because inside your document there is no field called id. So the Firestore SDK cannot map a non-existing field into an id field, hence the value of null.

    So there are ways in which you can solve this issue:

    1. When you write the data to Firestore, you generate the ID first, and then you populate the id field before writing the data to Firestore.

    2. When you read the data from Firesrore, even if you don't have the document ID as a field, you can call DocumentSnapshot#getId() and populate the id field with the document ID.