Warm tip: This article is reproduced from serverfault.com, please click

Get item at position at Android ListVIew

发布于 2020-11-28 01:04:15

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.

Questioner
Yasin Eraslan
Viewed
0
Ankit Gupta 2020-11-28 23:12:09

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.