Reputation: 61
i am developing an android application using kotlin and room library. when i try to get the id of the inserted item i am getting the following error
Not sure how to handle insert method's return type. public abstract java.lang.Object insertReceipt(@org.jetbrains.annotations.NotNull()
i have tried other solutions like this but it is not working
here is my code
Receipt.kt
@Entity
data class Receipt(
@ColumnInfo() val receipt_timestamp: Timestamp,
@ColumnInfo() val receipt_items: Int,
@ColumnInfo() val receipt_total_price: BigDecimal
){
@PrimaryKey(autoGenerate = true)
var receiptNo: Int = 0
}
ReceiptDao.kt
@Insert()
suspend fun insertReceipt(receipt: Receipt): Int
ReceiptRepository.kt
suspend fun insertReceipt(receipt: Receipt): Int{
return receiptDAO.insertReceipt(receipt)
}
Upvotes: 1
Views: 2377
Reputation: 779
A method annotated with the @Insert annotation can return:
long for single insert operation long[] or Long[] or List for multiple insert operations void if you don't care about the inserted id(s)
So you must change your return type of insertReceipt from Int to Long:
return receiptDAO.insertReceipt(receipt).toLong()
Upvotes: 1
Reputation: 553
That is because you cannot get the id like this. You can get an id with this function but it will not be the one you want.
cf: https://developer.android.com/training/data-storage/room/accessing-data#convenience-insert the id returned is an internal id used by sqlite.
To achieve what you want, you need something like:
@Query("SELECT receiptNo FROM receipt WHERE receipt_timestamp = :receipt_timestamp AND receipt_items = : receipt_items AND receipt_total_price = :receipt_total_price LIMIT 1")
fun getId(receipt_timestamp: Timestamp, receipt_items: Int, receipt_total_price: BigDecimal): Int
Upvotes: 1