Home » Android » java – Room error: Not sure how to handle insert method's return type

java – Room error: Not sure how to handle insert method's return type

Posted by: admin June 15, 2020 Leave a comment

Questions:

I don’t get it, I though this is the way to get the id of newly inserted row.

DAO

@Dao
public interface AlarmDao {

    .....

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    long insertAll(AlarmEntity...alarms); //used long instead of void
}

ENTITY

@Entity(tableName = "tb_alarm")
public class AlarmEntity {

    @PrimaryKey(autoGenerate = true)
    private long id;

    ...

    public long getId(){
        return this.id;
    }
}

but building is failed and I’m getting error which is pointing into my Dao class and the error is:

error: Not sure how to handle insert method’s return type.

What did I missed about it?

How to&Answers:
AlarmEntity...alarms

this translates in multiple inserts. So the return type should be a List<Long> or a long[], and it makes sense. If you pass two items you will get two id, one for each newly inserted row.

If you want to insert only 1 item at time, remove the varargs (...). EG

@Insert
long insert(AlarmEntity alarms);

Answer:

From Accessing data using Room DAOs:

If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.

Change the return type of insertAll () to long[] or List

Answer:

Following the documentaion if the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List<Long> instead.
in your case you have a list as paramater, you should return long[] or List<Long>
Source : https://developer.android.com/training/data-storage/room/accessing-data#java