简体   繁体   中英

Get item at position at Android ListVIew

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM