My code below fails when I call adapter.notifyDataSetChanged(). I got this code from an example. Not important to the question but I am filling an editText box with a scanned barcode. I then try to add it to the listview. I want to keep adding barcodes to the listview.
From the stack trace I believe this is the error: FATAL EXCEPTION: main Process: com.example.barcodereaderwedge, PID: 31252 java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
class MainActivity : AppCompatActivity() {
private lateinit var editText: EditText
private lateinit var listView: ListView
private lateinit var adapter: ArrayAdapter<String>
private val itemList = mutableListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
listView = findViewById(R.id.myListView)
editText = findViewById(R.id.editTextText)
editText.isFocusable = true
editText.requestFocus()
adapter = ArrayAdapter(this, R.layout.item_view, itemList)
listView.adapter = adapter
editText.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
// This method is called before the text is changed.
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
// This method is called when the text is changed.
//Toast.makeText(this@MainActivity, "Text changed: $s", Toast.LENGTH_SHORT).show()
}
override fun afterTextChanged(s: Editable?) {
//just using a dummy value for testing
val newItem = "test"
if (newItem.isNotEmpty()) {
itemList.add("newItem")
adapter.notifyDataSetChanged()
editText.requestFocus()
}
}
})
}
}