一,配置
dependencies {
implementation 'org.litepal.guolindev:core:3.1.1'
}
二,在main下新建assets文件夹,xml文件夹下新建litepal.xml 文件 如图
litepal.xml内容如下:
<?xml version="1.0" encoding="utf-8" ?>
<litepal>
<!-- 数据库名 -->
<dbname value="BookStore"></dbname>
<!-- 数据库版本号 -->
<version value="1"></version>
<list>
<mapping class="com.example.testall.Book">
</mapping>
<!-- 数据表:用于指定所有的映射模型
com.example.testall.Book 注意testall是我的类名-->
</list>
</litepal>
在AndroidMAainifest中加上
android:name="org.litepal.LitePalApplication"
三,使用
1,创建数据库
1)
首先先定义一个Book类 对应数据库中的表
package com.example.testall;
import org.litepal.crud.LitePalSupport;
import org.litepal.exceptions.DataSupportException;
public class Book extends LitePalSupport{
private int id;
private String author;
private double price;
private int pages;
private String name;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setAuthor(String author){
this.author = author;
}
public String getAuthor(){
return author;
}
public void setPrice(double price){
this.price = price;
}
public double getPrice(){
return price;
}
public void setPages(int pages){
this.pages = pages;
}
public int getPages(){
return pages;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2),在MainActivity中创建数据库
public void palCreat(View view){
Connector.getDatabase();//数据库创建完成
}
2,添加
public void palAdd(View v){//添加
Book book = new Book();
book.setAuthor("作者");
book.setName("名字");
book.setPages(534);
book.setPrice(56);
book.save();
}
3,获取
public void palQuery(View v){//查询
List<Book> books = LitePal.findAll(Book.class);
for(Book book:books){
Log.d("test","BookName:"+book.getName());
Log.d("test","Author:"+book.getAuthor());
Log.d("test","Page:"+book.getPages());
Log.d("test","Price:"+book.getPrice());
Log.d("test","All:"+book);
}
}
创建-添加-获取 得到:
4,删除
public void palDel(){//删除
LitePal.deleteAll(Book.class,"price < ?","15");
}
//第一个参数指定删除哪张表 "price < ?","15" 表示价格低于15都删除
5,更新
public void palUpdate(View view){//更新
Book book = new Book();
book.setPrice(10);
book.updateAll("name=? and author = ?","名字","作者");
}
更新在获取得到 价格变成10