使用LitePal无法插入带有List的对象的问题
项目场景:
在使用LitePal插入一个带List的时候发现插入的List始终为空,找了好久也没有解决,后来参考了郭神的这篇文章才彻底解决:https://blog.youkuaiyun.com/guolin_blog/article/details/39207945?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-6&spm=1001.2101.3001.4242
错误的示例:
public class TopicEntity extends LitePalSupport {
private String topic;
private String answer;
private List<OptionItem> list;
public static class OptionItem extends LitePalSupport{
String item;
}
}
1.一般服务端返回的数据我们就直接用插件生成数据类了,若该类的成员变量包含其他数据类会默认创建为内部类;**(注意)**这里的OptionItem不可以写成内部类,否则在操作该内部类的时候会报:`org.litepal.exceptions.DatabaseGenerateException: can not find a class named com.example.xxxx;
2.TopicEntity里的list对象要在这里实例化,否则在操作表的时候会报空异常;
解决方案:
1.TopicEntity里内部类改为外部类,并且要在litepal,xml里加入该类的声明。
数据类:
public class TopicEntity extends LitePalSupport {
private String topic;
private String answer;
private List<OptionItem> list = new ArrayList<>();
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public List<OptionItem> getList() {
return list;
}
public void setList(List<OptionItem> list) {
this.list = list;
}
}
public class OptionItem extends LitePalSupport {
String item;
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
asset的litepal.xml文件示例:
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<dbname value="xxxxx.db" />
<version value="1" />
<list>
<mapping class="com.example.testapplication.entity.TopicEntity" />
<mapping class="com.example.testapplication.entity.OptionItem" />
</list>
</litepal>
2.在TopicEntity和OptionItem都要调用.save()方法才可以插入数据库;
TopicEntity topic = new TopicEntity();
topic.setTopic("xxxx");
topic.setAnswer("xxxx");
List<OptionItem> item = topic.getList();
OptionItem option = new OptionItem();
option.setItem("xxxx");
option.save();
item.add(option);
topic.setList(item);
topic.save();
3.在查询的时候要使用LitePal.findAll(xxx.class,true);
第二个参数若不写就查询不到关联表的数据;
List<TopicEntity> all = LitePal.findAll(TopicEntity.class,true);
这样就可以查询到所有数据了。