Kotlin-使用Persistence Room:runtime lib从Room数据库返回新插入的ID [英] Kotlin - return new inserted id from Room database using Persistence Room:runtime lib
问题描述
我正在尝试使用Kotlin在Room数据库中插入用户记录,并且运行良好.
I am trying to insert user record in Room database using Kotlin and It's working perfectly.
现在,我想返回新插入的记录ID,以检查是否已成功将记录插入到Room数据库中.
And now I want to return newly inserted record id to check if a record is successfully inserted or not in Room database.
但是当我在insert方法中应用Long返回类型并在那段时间运行代码时,出现以下错误.
But when I am applying Long return type in the insert method and run the code that time I get the following error.
错误:方法返回的时间很长,但是它应该返回以下值之一:
void, long[], java.lang.Long[], java.util.List<java.lang.Long>
.如果 您要返回查询中的行ID列表,请插入 方法只能接收1个参数.
error: Method returns long but it should return one of the following:
void, long[], java.lang.Long[], java.util.List<java.lang.Long>
. If you want to return the list of row ids from the query, your insertion method can receive only 1 parameter.
public abstract long insertUser(@org.jetbrains.annotations.NotNull()
我正在使用此库.
实现"android.arch.persistence.room:runtime:1.0.0"
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
这是我的插入查询.
@Insert
fun insertUser(vararg userRegistrationEntity: UserRegistrationEntity):Long;
这是我的addAsyncTask,我在其中将记录插入到Room数据库中
Here is my addAsyncTask where I am inserting a record in Room database
private fun userRegistration(userRegistrationEntity: UserRegistrationEntity) {
addAsyncTask(appDatabase!!).execute(userRegistrationEntity)
}
private class addAsyncTask constructor(private val appDatabase: AppDatabase) : AsyncTask<UserRegistrationEntity, Void, Long>() {
override fun doInBackground(vararg params: UserRegistrationEntity): Long? {
// val a = appDatabase.userRegistrationDao().addUser(params[0]);
val newReturnId = appDatabase.userRegistrationDao().insertUser(params[0]);
return newReturnId
}
override fun onPostExecute(result: Long?) {
super.onPostExecute(result)
Log.d("value", result.toString())
}
}
推荐答案
如果要插入多个实体,则只能以数组或列表的形式获取它们的ID,例如:
If you're inserting multiple entities, you can only get their IDs back in an array or list, for example, like this:
@Insert
fun insertUsers(vararg userRegistrationEntities: UserRegistrationEntity): List<Long>
如果一次插入一个实体,则可以以Long
的形式获取其ID:
If you insert one entity at a time, you can get its ID back as a Long
:
@Insert
fun insertUser(userRegistrationEntity: UserRegistrationEntity): Long
这篇关于Kotlin-使用Persistence Room:runtime lib从Room数据库返回新插入的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!