Ad
How To Save Firebase DataSnapshot Object And Key Into Kotlin DTO Data Class?
The objective: Update Firebase realTime database from an Android device.
My data structure simplified:
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
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View
Ad