I am facing a strange error I can't figure out why exactly this happens, as I have a mutableMapOf and I want to keep adding keys and values to it dynamically every time they add new items. what happens is that no matter how much data its entered it only stores the last items, If I hard coded the data it stores it normally, but within the scope of the method it doesn't work and I cant figure out why?
private fun showDialogBody() {
val dialog = Dialog(this)
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setCancelable(true)
dialog.setContentView(R.layout.dialogue_view)
val bodyKey = dialog.findViewById(R.id.key) as EditText
val bodyvalue = dialog.findViewById(R.id.value) as EditText
val addBtn = dialog.findViewById(R.id.dialogDismiss_button) as Button
val finishBtn = dialog.findViewById(R.id.dialogDismiss_finish_button) as Button
keyjson = bodyKey.text.toString().trim()
valuejson = bodyvalue.text.toString().trim()
jsonMap = mutableMapOf(keyjson to valuejson)
addBtn.setOnClickListener {
jsonMap.put(keyjson, valuejson)
Toast.makeText(this, "${bodyKey.text} Added", Toast.LENGTH_SHORT).show()
bodyKey.text.clear()
bodyvalue.text.clear()
}
finishBtn.setOnClickListener {
dialog.dismiss()
Toast.makeText(this, " number of key value ${jsonMap.size}", Toast.LENGTH_SHORT).show()
}
dialog.show()
}
CodePudding user response:
It's because you're doing this when you initialise the dialog:
keyjson = bodyKey.text.toString().trim()
valuejson = bodyvalue.text.toString().trim()
You're setting those values once, right after the dialog's layout has been inflated. So those values are just the initial contents of those EditText
s. Even if the user types something into them, keyjson
and valuejson
are never changed.
You need to read those values right before you store them, so you're grabbing the current data:
addBtn.setOnClickListener {
val keyjson = bodyKey.text.toString().trim()
val valuejson = bodyvalue.text.toString().trim()
jsonMap.put(keyjson, valuejson)
Toast.makeText(this, "${bodyKey.text} Added", Toast.LENGTH_SHORT).show()
bodyKey.text.clear()
bodyvalue.text.clear()
}