Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to insert a list of objects into Room?

I am trying to define common CRUD methods in a base interface as shown here:

interface BaseDao<in I> {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun create(obj: I)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun createAll(objects: List<I>)

    @Delete
    fun delete(obj: I)

}

The following ProductDao interface for Room inherits from the base interface:

@Dao
interface ProductDao : BaseDao<Product> {

    // Specific methods

}

When I compile the definition for fun createAll(objects: List<I>) produces the following error:

Type of the parameter must be a class annotated with @Entity or a collection/array of it.

like image 684
JJD Avatar asked Jan 09 '18 23:01

JJD


People also ask

How do I delete data from kotlin room database?

3.1 Add the Clear all data menu option In the Options menu, select Clear all data. All words should disappear. Restart the app. (Restart it from your device or the emulator; don't run it again from Android Studio) You should see the initial set of words.


2 Answers

Try adding @JvmSuppressWildcards to your function.

@Insert
@JvmSuppressWildcards
fun createAll(objects: List<I>)

From the docs:

Instructs compiler to generate or omit wildcards for type arguments corresponding to parameters with declaration-site variance, for example such as Collection has.

It may be helpful only if declaration seems to be inconvenient to use from Java.

like image 85
aneurinc Avatar answered Sep 19 '22 17:09

aneurinc


I've resolved issue by:

@Dao
interface BaseDao<T> {

    /**
     * Insert a list in the database. If the item already exists, replace it.
     *
     * @param list the items to be inserted.
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    @JvmSuppressWildcards
    abstract fun insertAll(list: List<T>)

}

@JvmSuppressWildcards done the trick for me

like image 37
Waqar UlHaq Avatar answered Sep 20 '22 17:09

Waqar UlHaq