I've found several other questions about this exception and none of them have an answer that works for me.
Here is my entire code:
class MainActivity : AppCompatActivity() {
private lateinit var listView: ListView
private lateinit var addItem: ImageButton
private lateinit var adapter: MyAdapter
private val names = arrayListOf("Person 1", "Person 2", "Person 3", "Person 4", "Person 5",
"Person 6", "Person 7", "Person 8", "Person 9", "Person 10")
private val descriptions = arrayListOf("Actor", "Activist", "Athlete", "Scientist", "Astronaut",
"Engineer", "Software Developer", "Politician", "Soldier", "Shopkeeper")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listView = list_view as ListView
addItem = addButton as ImageButton
adapter = MyAdapter(this, names, descriptions)
listView.adapter = adapter
addItem.setOnClickListener {
names.add("Person 11")
descriptions.add("Mortician")
adapter.notifyDataSetChanged()
Toast.makeText(this, "Button Clicked", Toast.LENGTH_LONG).show()
}
}
}
private class MyAdapter(val context: Context, val names: ArrayList<String>,
val descriptions: ArrayList<String>) : BaseAdapter() {
override fun getCount(): Int {
return names.size
}
override fun getViewTypeCount(): Int {
return count
}
override fun getItemViewType(position: Int): Int {
return position
}
override fun getItem(position: Int): Any {
return position
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val viewHolder: ViewHolder?
return if (convertView == null) {
val convertViewMutable = LayoutInflater.from(context).inflate(R.layout.activity_custom, parent, false)
val checkBox: CheckBox = convertViewMutable.findViewById(R.id.checkBox_name) as CheckBox
val desc: TextView = convertViewMutable.findViewById(R.id.textView_desc) as TextView
viewHolder = ViewHolder(checkBox, desc)
convertViewMutable.tag = viewHolder
checkBox.text = names[position]
desc.text = descriptions[position]
convertViewMutable
} else
convertView
}
}
private data class ViewHolder(private val checkBox: CheckBox, private val textView: TextView)
When I run the program, the list appears fine. When I click the button to add the new name and description it runs all the code in the listener since I see the Toast appear. I can then scroll down and see the new item at the bottom of the list. But, when I scroll back up the error is thrown.
I saw an answer for someone saying you shouldn't override getViewTypeCount() and getItemViewType() but I am only overriding them because if I take them out the items in my list will duplicate when I scroll through them. There were also answers saying the error happens because getItemViewType() is returning a number greater than getViewTypeCount() but they don't mention how to fix it.