'My ArrayAdapter gives me null value - Kotlin
I'm trying to display my sqlite data in textview with kotlin android app. But i have an error with this. When i run my app, it breaks. What is the problem?
Here is my read_data function in dbhelper:
fun read_data():MutableList<Kullanici> {
val userList:MutableList<Kullanici> = ArrayList()
val db = this.readableDatabase
val query = "SELECT * FROM $table_name"
val result = db.rawQuery(query,null)
if(result.moveToFirst()) {
do {
val kullanici = Kullanici()
kullanici.id = result.getString(result.getColumnIndexOrThrow(column_id)).toInt()
kullanici.hamle = result.getString(result.getColumnIndexOrThrow(column_hamle)).toInt()
kullanici.sure = result.getString(result.getColumnIndexOrThrow(column_sure)).toInt()
userList.add(kullanici)
}while (result.moveToNext())
}
result.close()
db.close()
return userList
}
And here is my main acitivity:
override fun onCreate(savedInstanceState: Bundle?) {
val lv = findViewById<ListView>(R.id.listView)
val db = DataBaseHelper(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportActionBar?.hide()
val kolay_butonu = findViewById<Button>(R.id.button2)
kolay_butonu.setOnClickListener {
val intent = Intent(this, Kolay::class.java)
startActivity(intent)
}
val liste = db.read_data()
val adapter_: ArrayAdapter<*>
adapter_ = ArrayAdapter(this, android.R.layout.simple_list_item_1, liste)
lv.adapter = adapter_
}
and finally the error i encountered:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
Solution 1:[1]
you should call findViewById after setContentView. The view is only inflated when setContentView is called, so when you find view before setContentView is called, it will return null.
just move this line
val lv = findViewById<ListView>(R.id.listView)
after setContentView
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dito cesartista |
