我正在尝试创建一个包含列表项的Room数据库。我在这里遵循以下示例:https://medium.com/mindorks/room-kotlin-android-architecture-components-71cad5a1bb35
这是我的数据类:
@Entity(tableName = "itemData")
data class ItemData(@PrimaryKey(autoGenerate = true) var id: Long? = null,
@ColumnInfo(name = "text") var text: String,
@ColumnInfo(name = "checked") var checked: Boolean
)
DAO:
@Dao
interface ItemDataDAO {
@Insert(onConflict = REPLACE)
fun insert(itemData: ItemData) : Long
}
数据库:
@Database(entities = arrayOf(ItemData::class), version = 1)
abstract class ItemDatabase() : RoomDatabase() {
abstract fun itemDataDao(): ItemDataDAO
companion object {
private var INSTANCE: ItemDatabase? = null
fun getInstance(context: Context): ItemDatabase? {
if (INSTANCE == null) {
synchronized(ItemDatabase::class) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
ItemDatabase::class.java, "items.db")
.build()
}
}
return INSTANCE
}
fun destroyInstance() {
INSTANCE = null
}
}
}
工作线程:
class DbWorkerThread(threadName: String) : HandlerThread(threadName) {
private lateinit var mWorkerHandler: Handler
override fun onLooperPrepared() {
super.onLooperPrepared()
mWorkerHandler = Handler(looper)
}
fun postTask(task: Runnable) {
mWorkerHandler.post(task)
}
}
这里是侦听器,而不是调用插入函数:
editText.setOnEditorActionListener { v, actionId, event ->
return@setOnEditorActionListener when (actionId) {
EditorInfo.IME_ACTION_DONE -> {
createItem(editText)
true
}
else -> false
}
}
这是被调用以插入项目的函数:
fun createItem(editText: EditText) {
var text = editText.text.toString().trim()
var itemData = ItemData(text = text, checked = false)
var id : Long? = 0
val task = Runnable {
id = mDb?.itemDataDao()?.insert(itemData)
println("inserted $id")
}
mDbWorkerThread.postTask(task)
}
但是ID始终为0,因此只能插入一项。谁能看到这个问题?
我还尝试过删除null
的默认id
值,但结果相同。
答案 0 :(得分:0)
您要添加一个自动增量列:
@Entity(tableName = "item_data")
public class ItemData extends BaseObservable {
/** Fields */
@ColumnInfo(name = "item_id")
@PrimaryKey(autoGenerate = true)
private int itemId;
...
}
答案 1 :(得分:0)
以下更改解决了该问题。
而不是像这样调用构造函数
var itemData = ItemData(text = text, checked = false)
我叫默认构造函数,然后在构造后设置参数。
var itemData = ItemData()
itemData.text = text
itemData.checked = false
这需要ItemData实体的以下构造函数:
constructor():this(null,"",false)