我愿意从Android尝试新的室图书馆和我遇到下面的错误:错误试图缓存采用Android室图书馆一个HashSet
Error:(19, 29) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
此错误是指下列类成员:
private HashSet<String> fruits;
我有以下类:
@Entity(tableName = "SchoolLunches")
public class SchoolLunch {
@PrimaryKey(autoGenerate = true)
private int lunchId;
private boolean isFresh;
private boolean containsMeat;
private HashSet<String> fruits;
public int getLunchId() {
return lunchId;
}
public void setLunchId(int lunchId) {
this.lunchId = lunchId;
}
public boolean isFresh() {
return isFresh;
}
public void setFresh(boolean fresh) {
isFresh = fresh;
}
public boolean isContainsMeat() {
return containsMeat;
}
public void setContainsMeat(boolean containsMeat) {
this.containsMeat = containsMeat;
}
public HashSet<String> getFruits() {
return fruits;
}
public void setFruits(HashSet<String> fruits) {
this.fruits = fruits;
}
此外,还有是一个相对的DAO类:
因为我想成为一个很好的开发者,我写了一个单元测试如下:
@Test
public void singleEntityTest() {
HashSet<String> fruitSet = new HashSet<>();
fruitSet.add("Apple");
fruitSet.add("Orange");
SchoolLunch schoolLunch = new SchoolLunch();
schoolLunch.setContainsMeat(false);
schoolLunch.setFresh(true);
schoolLunch.setFruits(fruitSet);
schoolLunchDAO.insertAll(schoolLunch);
List<SchoolLunch> schoolLunches = schoolLunchDAO.getAll();
assertEquals(schoolLunches.size(), 1);
SchoolLunch extractedSchoolLunch = schoolLunches.get(0);
assertEquals(false, extractedSchoolLunch.isContainsMeat());
assertEquals(true, extractedSchoolLunch.isFresh());
assertEquals(2, extractedSchoolLunch.getFruits().size());
}
我应该怎么做吗?
请注意,这只有在单个字符串本身不使用''''时才有效。否则,除了用作列表分隔符的那些外,你的'split()'调用将把这些单独的字符串分割为它们的','字符。我添加了一些代码给我的答案,显示使用JSON,它应该能够处理任意字符串(虽然它比你的解决方案更详细)。 – CommonsWare