我在用Kotlin开发的Android应用程序中拥有一个SQlite
数据库。在此数据库中,我存储了class
Device_info类
class Device_info {
var id : Int = 0
var name : String = ""
constructor(id : Int, name: String){
this.id = id
this.name = name
}
}
现在在id
变量中,我想存储数据库将自动提供的raw_id
。我在一些教程中发现了如何创建数据库处理程序,并且已经做到了这样
数据库处理程序类
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
private const val DATABASE_NAME = "Devices_db"
private const val TABLE_NAME = "Devices"
private const val RAW_ID = "raw_id"
private const val COLUMN_NAME = "name"
private const val COLUMN_ID = "id"
class DataBaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, 1) {
override fun onCreate(db: SQLiteDatabase?) {
val createTable = "CREATE TABLE " + TABLE_NAME + "(" + RAW_ID +
" INTEGER PRIMARY KEY, " + COLUMN_NAME + " TEXT, " +
COLUMN_ID + "INTEGER)"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {}
fun insertData(device: Device_info){
val db = this.writableDatabase
val cv = ContentValues()
cv.put(COLUMN_ID, device.id)
cv.put(COLUMN_NAME, device.name)
db.insert(TABLE_NAME, null, cv)
db.close()
}
fun readData() : MutableList<Device_info>{
val list : MutableList<Device_info> = ArrayList()
val db = this.readableDatabase
val query = "Select * from " + TABLE_NAME
val result = db.rawQuery(query, null)
if(result.moveToFirst()){
do{
val device = Device_info()
device.id = result.getString(result.getColumnIndex(COLUMN_ID)).toInt()
device.name = result.getString(result.getColumnIndex(COLUMN_NAME)
list.add(device)
}while(result.moveToNext())
}
result.close()
db.close()
return list
}
fun UpdateId(device: Device_info){
val db = this.readableDatabase
val cv = ContentValues()
cv.put(COLUMN_ID, device.id)
db.update(TABLE_NAME, cv, "id = " + device.id, null)
db.close()
}
fun UpdateName(device: Device_info){
val db = this.readableDatabase
val cv = ContentValues()
cv.put(COLUMN_NAME, device.name)
cv.put(COLUMN_ID, device.id)
db.update(TABLE_NAME, cv, "id = " + device.id, null)
db.close()
}
fun deleteData(device: Device_info){
val db = this.writableDatabase
val cv = ContentValues()
cv.put(COLUMN_ID, device.id)
cv.put(COLUMN_NAME, device.name)
db.delete(TABLE_NAME, "id = " + device.id, null)
db.close()
}
}
因此,在我通过传入构造函数创建对象并以id
-1
的形式创建对象之后,因为当时我还不了解raw_id
在数据库中添加对象后,我调用了函数insertData
,对象成功存储在数据库中,但列id
包含-1
到所有元素。我的问题是如何复制raw_id
列中的id
列?
答案 0 :(得分:1)
为什么两列存储的值完全相同?除非您不打算操作id,否则不建议这样做。
仅访问一列raw_id会更有效。这样不会浪费空间,而是可以缓存更多数据,依此类推。
我想关于您意图的线索位于,因为当时我不知道raw_id,因为我还没有在数据库中添加对象,因为您基本上想知道 id 是什么。以下是如何检索 id (raw_id)的方法:-
您检索从插入返回的值,并从 insertData 方法返回该值。
类似:-
fun insertData(device: Device_info): Long{
val db = this.writableDatabase
val cv = ContentValues()
cv.put(COLUMN_ID, device.id)
cv.put(COLUMN_NAME, device.name)
val rv = db.insert(TABLE_NAME, null, cv)
db.close()
return rv
}