LitePal数量级存储
我的是androidX,和v7添加的依赖可能不一样
数据很多可以用这个,不需要懂SQL操作
1,添加依赖
implementation 'org.litepal.android:core:2.0.0'
把下面这句话添加到AndroidManifest.xml中
android:name="org.litepal.LitePalApplication"
2,创建一个assset文件,如下图,在里面添加一个litepal.xml文件
litepal.xml代码如下
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<dbname value="account" ></dbname>
<version value="1" ></version>
<list>
//com.coolweather.accountbook.list.ListItem这个是相关的类,后面会看到
<mapping class="com.coolweather.accountbook.list.ListItem"></mapping>
</list>
</litepal>
3,把存的信息变成一个类(这里用的是不继承LitePalSupport )
public class ListItem {
int id;
private Integer img;
private String sum;
private String remarks;
private String label;
private String time;
public ListItem(int id, Integer img, String sum, String remarks, String label, String time) {
this.id = id;
this.img = img;
this.sum = sum;
this.remarks = remarks;
this.label = label;
this.time = time;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getImg() {
return img;
}
public void setImg(Integer img) {
this.img = img;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getSum() {
return sum;
}
public void setSum(String sum) {
this.sum = sum;
}
}
5,封装成一个工具类
public class MyData {
private static String TAG = "MyData";
//添加
public static int add(ListItem listItem){
LitePal.getDatabase();
listItem.save();
Log.d(TAG, "添加ID:"+listItem.getId());
return listItem.save() ? 1: 0;
}
//删除
public static int delete(int id){
LitePal.deleteAll(ListItem.class, "id = ?",String.valueOf(id));
Log.d(TAG, "删除成功!");
return 1;
}
//更新
public static int updata(int id, ListItem newListItem){
ListItem listItem1 = LitePal.find(ListItem.class, id);
if(listItem1 == null){
return 0;
}
listItem1.setImg(newListItem.getImg());
listItem1.setLabel(newListItem.getLabel());
listItem1.setRemarks(newListItem.getRemarks());
listItem1.setSum(newListItem.getSum());
listItem1.setTime(newListItem.getTime());
listItem1.save();
Log.d(TAG, "更新成功!");
return 1;
}
//查询所有
public static List<ListItem> queryAll(){
List<ListItem> nowList = LitePal.findAll(ListItem.class );
for(ListItem l : nowList){
Log.d(TAG, "列表ID:"+l.getId());
}
return nowList;
}
//查询某个id
public static ListItem queryId(int id){
ListItem listItem = LitePal.find(ListItem.class, id);
return listItem;
}
}
5,开始使用
在onCreate加入这个,声明一下
LitePal.initialize(this);
使用方法(增,删,改,查)
//获取所有
List<ListItem> list_all = MyData.queryAll();
//获取单个
listItem = MyData.queryId(id);
//删除
MyData.delete(id);
//添加
MyData.add(listItem);
//修改
MyData.updata(id, newlistItem);