I'm learning Android studio with Kotlin, I have setup one listview in Oncreate, it list out user data, then I have another function onOptionItemSelected which add/delete user data item, the problem is : after I add/delete from another function, the data on listview cannot be updated:
Here is my code:
class MainActivity : AppCompatActivity() {
private lateinit var listView : ListView
override fun onCreate(savedInstanceState: Bundle?) {
.....
listView = findViewById(R.id.listview_main)
val adapter2 = listViews(this, array_firstname, array_lastname,array_age)
listView.adapter = adapter2
....
override fun onOptionsItemSelected(item: MenuItem): Boolean {
........
GlobalScope.launch {
db1.UsersDao().insertAll(User_tb(0,firstName, lastName, userAge))
(listView.adapter as listViews).notifyDataSetChanged()
}
With this, I got error "Only the original thread that created a view hierarchy can touch its views."
I searched internet and found I need to use runOnUiThread, then I below part under "listView.adapter = adapter2", but it still does not work:
Thread(Runnable {
this@MainActivity.runOnUiThread(java.lang.Runnable {
(listView.adapter as listViews).notifyDataSetChanged()
})
}).start()
I guess I did not understand runOnUiThread correctly but cannot figure out how, could somebody help?
Thanks!