I am trying to retrieve data from the item I clicked but I always get null, I could not find a solution for this. My code:
override fun onStart() {
super.onStart()
val records = RecordDAO(this).findAll().map {
"${it.moduleName} ${it.moduleNum} (%${it.noteInProzent} ${it.creditPoints}crp)"
}
val adapter = ArrayAdapter(this,android.R.layout.simple_list_item_1,records)
this.recordListView.adapter = adapter
recordListView.setOnItemClickListener { parent, view, position, id ->
var record: Record? = recordListView.getItemAtPosition(position) as? Record
if(record!= null) println(record.moduleName)
else println("rec is null")
intent = Intent(this,EditFormActivity::class.java)
intent.putExtra("record",record)
startActivity(intent)
}
}
Every time in the null check it prints null so I can not retrieve my item somehow, when I print the position for example I get the right position but I can not retrieve the item at that position.
The records in your code are stored in the listView adapter, so in onItemClickListener, get your item from the adapter as shown below :
adapter.getItem(position)
Another approach could be :
(typecast_into_respective_object) parent.getItemAtPosition(position)
Here parent is the adapterView object in setOnItemClickListener.
This returns a String?
This will return the type of object which the adapter is storing.. like if the adapter is storing a list of strings, then it will return a String object.
Isn't it storing records?
Yes, so it will return the object of type "Record"