Ad

How To Save Firebase DataSnapshot Object And Key Into Kotlin DTO Data Class?

- 1 answer

The objective: Update Firebase realTime database from an Android device.

My data structure simplified:

enter image description here

My Data Class TasksDTO.kt:

data class TasksDTO(var customer : String ="", var date : String ="", var location : String ="", var key : String="") { 
   

}

I've added an addValueEventListener under onCreate:

 private var allTasks = ArrayList<TasksDTO>()//Used to update recyclerView. 
 reference.child("tasks").addValueEventListener(object : ValueEventListener {
    override fun onCancelled...

    override fun onDataChange(dataSnapshot: DataSnapshot) {
        val children = dataSnapshot.children
       
        allTasks.clear()

        children.forEach {

            var taskObj = it.getValue()//without key: it.getValue(TasksDTO::class.java)
            var task = TasksDTO()

            with(task){
                customer = taskObj.customer //**ERROR: Unresolved reference**
                date = taskObj.date //**ERROR: Unresolved reference**
                location = taskObj.location //**ERROR: Unresolved reference**
                key = it.key!!
            }

            //
            allTasks.add(task!!)

        }
        recyclerView.adapter!!.notifyDataSetChanged()
        

    }

}

I want to be able to update firebase data in the onclick item listener function of the recyclerView. To do that I need to have reference to the key to update the database. Unless there is a more efficient method. I'm open to correction.

Thanks for the help!

Ad

Answer

A HashMap stores key, value pairs which can be referenced unlike an object from a database.

var taskObj = it.getValue() as HashMap<*, *>
                    var task = TasksDTO()

                    with(task){
                        customer = taskObj ["customer"].toString()
                        key = it.key.toString()
                        date = taskObj ["date"].toString()
                        location = taskObj ["location"].toString()
                    }

Credit goes to Doug Stevenson see OP's comments.

Ad
source: stackoverflow.com
Ad