I am using Room architecture component for persistence. I have created generic DAO interface to avoid boilerplate code. Room Pro Tips
But my code doesn't compile saying "Error:(21, 19) error: Type of the parameter must be a class annotated with @Entity or a collection/array of it." for the Generic class T.
interface BaseDao<T> {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(T... entity);
@Update
void update(T entity);
@Delete
void delete(T entity);
}
@Dao
public abstract class ReasonDao implements BaseDao<ReasonDao> {
@Query("SELECT * from Reason")
abstract public List<Reason> getReasons();
}
Is there anything I am missing here. It works like this here
Does your RoomDatabase subclass perhaps have an abstract method that is returning something other than DeviceDAO? That's an interface, not a class. Check your database class. When you define DAO, you must have use wrong type (Device instead of DeviceDAO). Hope this will work. Thanks
If you run into the following error you probably provide a class that is either not correctly annotated or shouldn’t be there. The source of this problem usually can be found by looking at your database class, the example code is in Kotlin but should also apply to Java:
When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.
The source of this problem usually can be found by looking at your database class, the example code is in Kotlin but should also apply to Java: Now make sure, that any referenced class in the @Database annotation in line 1 is annotated with @Entity.
Changed in gradle from this:
kapt "androidx.room:room-compiler:$roomVersion"
to this:
annotationProcessor "androidx.room:room-compiler:$room_version"
I had initially followed the method used in Kotlin, but that gives the error in Java code. Two quick changes fixed it for me
Please find the code below and now it runs properly
@Dao
abstract class BaseDao<T> {
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract void insert(T entity);
@Update
abstract void update(T entity);
@Delete
abstract void delete(T entity);
}
@Dao
public abstract class ReasonDao extends BaseDao<Reason>{
@Query("SELECT * from Reason")
abstract public List<Reason> getReasons();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With