Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - return new inserted id from Room database using Persistence Room:runtime lib

I am trying to insert user record in Room database using Kotlin and It's working perfectly.

And now I want to return newly inserted record id to check if a record is successfully inserted or not in Room database.

But when I am applying Long return type in the insert method and run the code that time I get the following error.

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()

I am using this lib.

implementation "android.arch.persistence.room:runtime:1.0.0"

kapt "android.arch.persistence.room:compiler:1.0.0"

Here is my insert query.

@Insert
fun insertUser(vararg userRegistrationEntity: UserRegistrationEntity):Long;

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()) 
        }
    }
like image 940
Vikas singh Avatar asked Jul 06 '18 06:07

Vikas singh


1 Answers

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>

If you insert one entity at a time, you can get its ID back as a Long:

@Insert
fun insertUser(userRegistrationEntity: UserRegistrationEntity): Long
like image 159
zsmb13 Avatar answered Oct 05 '22 08:10

zsmb13