我正在尝试为我的Android应用创建一个Room数据库,我遇到了自定义对象数组的问题。
错误讯息:
java.lang.IllegalArgumentException: cz.polreich.banks.model.airBank.OpeningHoursDay[]cannot be converted to an Element
这是嵌入有问题数组的对象:
@Entity
public class OpeningHours {
@PrimaryKey(autoGenerate = true)
private int ohId;
private boolean isNonstop;
@Embedded
private OpeningHoursDay[] days;
public OpeningHours() {
}
// getters and setters
这是我的数据库定义:
@Database(version = 1, entities = {OpeningHours.class, OpeningHoursDay.class})
abstract class AppDatabase extends RoomDatabase {
@TypeConverters({Converters.class})
abstract public BranchDao branchDao();
}
我也有类型转换器,我希望,通过将数组转换为List并返回来解决这个问题,但它没有帮助:
public class Converters {
@TypeConverter
public List<OpeningHoursDay> fromOpeningHoursDayArray(OpeningHoursDay[] ohda){
List<OpeningHoursDay> ohdList = new ArrayList<>();
ohdList.addAll(Arrays.asList(ohda));
return ohdList;
}
@TypeConverter
public OpeningHoursDay[] toOpeningHoursDayArray(List<OpeningHoursDay> ohdList){
OpeningHoursDay[] ohda = null;
for (int i = 0; i < ohdList.size(); i++) {
ohda[i] = ohdList.get(i);
}
return ohda;
}
}
修改 我试图更改TypeConverter以将对象转换为json,但它没有帮助:
public class Converters {
Gson gson = new Gson();
@TypeConverter
public String fromOpeningHoursDayArray(OpeningHoursDay[] ohda){
ArrayList<OpeningHoursDay> ohdList = new ArrayList<>();
ohdList.addAll(Arrays.asList(ohda));
return gson.toJson(ohdList);
}
@TypeConverter
public OpeningHoursDay[] toOpeningHoursDayArray(String ohdJson){
ArrayList<OpeningHoursDay> ohdList = new ArrayList<>();
ohdList = gson.fromJson(ohdJson, new TypeToken<ArrayList<OpeningHoursDay>>(){}.getType());
OpeningHoursDay[] ohda = null;
for (int i = 0; i < ohdList.size(); i++) {
ohda[i] = ohdList.get(i);
}
return ohda;
}
}
有谁知道如何解决这个问题?
答案 0 :(得分:1)
删除自定义对象数组的@Embedded
注释修复了该问题。