【发布时间】:2017-11-13 21:09:09
【问题描述】:
是否可以通过新的 Android 架构组件和 Room Persistence 库将 Enum 类型用作实体类中的嵌入字段?
我的实体(带有嵌入式枚举):
@Entity(tableName = "tasks")
public class Task extends SyncEntity {
@PrimaryKey(autoGenerate = true)
String taskId;
String title;
/** Status of the given task.
* Enumerated Values: 0 (Active), 1 (Inactive), 2 (Completed)
*/
@Embedded
Status status;
@TypeConverters(DateConverter.class)
Date startDate;
@TypeConverters(StatusConverter.class)
public enum Status {
ACTIVE(0),
INACTIVE(1),
COMPLETED(2);
private int code;
Status(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
}
我的类型转换器:
public class StatusConverter {
@TypeConverter
public static Task.Status toStatus(int status) {
if (status == ACTIVE.getCode()) {
return ACTIVE;
} else if (status == INACTIVE.getCode()) {
return INACTIVE;
} else if (status == COMPLETED.getCode()) {
return COMPLETED;
} else {
throw new IllegalArgumentException("Could not recognize status");
}
}
@TypeConverter
public static Integer toInteger(Task.Status status) {
return status.getCode();
}
}
当我编译这个时,我收到一条错误消息Error:(52, 12) error: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
更新 1 我的 SyncEntity 类:
/**
* Base class for all Room entities that are synchronized.
*/
@Entity
public class SyncEntity {
@ColumnInfo(name = "created_at")
Long createdAt;
@ColumnInfo(name = "updated_at")
Long updatedAt;
}
【问题讨论】:
-
我认为您需要将字段设置为
public,提供public设置器,或者提供与@Query列匹配的public构造函数。否则,Room 无法为您提供数据。您唯一的构造函数是零参数的构造函数。 -
Getters 和 Setters 不能解决问题,并且 Enum 不允许公共构造函数。我认为 TypeConverter 可以解决问题并将 Enum 转换为 int,但事实并非如此。可能 Room 还不够成熟,无法用于这种用途。可能应该提出功能请求。
标签: android android-room android-architecture-components