android studio 查询sqlite数据库并用listview显示前三个字段用kotlin编写
时间: 2024-02-17 15:35:43 浏览: 92
android sqlite 手机通讯录app
好的,您可以通过以下代码实现:
1. 安装SQLite数据库依赖库
```
implementation 'androidx.sqlite:sqlite:2.1.0'
```
2. 创建SQLiteOpenHelper类,并实现onCreate()方法和onUpgrade()方法
```
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
private const val DATABASE_VERSION = 1
private const val DATABASE_NAME = "database"
}
override fun onCreate(db: SQLiteDatabase) {
// 创建表
db.execSQL("CREATE TABLE IF NOT EXISTS user" +
"(id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"age INTEGER," +
"address TEXT);")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// 升级数据表操作
}
}
```
3. 创建数据库实例
```
val dbHelper = DatabaseHelper(this)
val db = dbHelper.readableDatabase
```
4. 查询数据库并显示前三个字段
```
val cursor = db.rawQuery("SELECT name, age, address FROM user", null)
val dataList = ArrayList<String>()
while (cursor.moveToNext() && dataList.size < 3) {
dataList.add(cursor.getString(cursor.getColumnIndex("name")) +
" | " + cursor.getInt(cursor.getColumnIndex("age")) +
" | " + cursor.getString(cursor.getColumnIndex("address")))
}
```
5. 显示数据到ListView
```
val listView: ListView = findViewById(R.id.listView)
val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, dataList)
listView.adapter = arrayAdapter
```
阅读全文