Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 867
Polar Avatar asked Jul 10 '19 15:07

Polar


4 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);
like image 109
Blackbelt Avatar answered Oct 18 '22 00:10

Blackbelt


If anyone is having this issue in December 2021, I just fixed my problem and it may the same as yours.

As it is, kotlin 1.6.0 has been officially rolled out. However, with the stable 2.3.0 release of Room it doesn't include the dependencies to work with this updated kotlin.

What I did was update my room to 2.4.0-rc01 and that solved my problem!

like image 30
Hamid Ebadi Avatar answered Oct 17 '22 23:10

Hamid Ebadi


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

like image 43
prfarlow Avatar answered Oct 17 '22 23:10

prfarlow


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

like image 40
B.M Avatar answered Oct 18 '22 01:10

B.M