0

I am getting a list of strings from API, same when I tried to insert in Room Db, I am getting an error -

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

Here is my method

 @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(list: List<String>).        --> this method giving error

And this is table for it

@Entity(tableName = "insuree")
public class Insuree {
    @ColumnInfo(name = "insurerName")
    @NonNull
    public String insurerName;

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "_id")
    public int id;
}

How can I resolve this error, or is there any other way to get this thing work.

Kushal
  • 8,100
  • 9
  • 63
  • 82
Anupriya
  • 1,663
  • 3
  • 17
  • 28

1 Answers1

1
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(list: List<String>).        --> this method giving error

In this situation Room cannot determine which table that you want to insert the data into.

That is when using @Insert annotation Room detemines the table to be inserted into according to the class of the object being inserted and then only if the class is defined using @Entity (so that it is a type that is registered with/understood by Room). The actual table name to use when building the underlying code can then be determined from the class/Entity.

As such it appears that you should have :-

fun insertAll(list: List<Insuree>) 

or perhaps more appropriately

fun insertAll(insurees: List<Insuree>)

You would then need to create a list of Insuree objects from your String array e.g.

    String[] insureeStringList = new String[]{"Insurer1","Insurer2","Insurer3"}; //<<<<< The list of Insurer names
    ArrayList<Insuree> insurees = new ArrayList<>();
    Insuree i = new Insuree();
    for (String insuree: insureeStringList) {
        i.insurerName = insuree;
        insurees.add(i);
    }
    // insurees is a List of Insuree objects
    appDatabase.insureeDao().insertAll(insurees);
MikeT
  • 51,415
  • 16
  • 49
  • 68
  • is that mean only one row will be created for insurerName and it will consisting of all insurersNames in it with comma separation.? – Anupriya Jan 06 '20 at 07:16
  • @Anupriya sorry that last code was wrong, as such I've removed that bit from the answer. Just create a List of Insuree objects from the names. – MikeT Jan 06 '20 at 07:47