简介
LitePal 是一款开源的 Android 数据库框架,它采用了对象关系映射(ORM)的模式,将我们平时使用的一些数据库(比如 Sqlite)功能进行了封装。
一、配置LitePal
所以操作在https://github.com/guolindev/LitePal介绍很清楚,这里依据GitHub的过程总结一下
1、添加依赖
dependencies {
implementation 'org.litepal.guolindev:core:3.2.3'
}
2、在项目app/src/main目录下创建一个assets目录(directory),再在assets中创建一个litepal.xml文件(可以右键new 选择file 输入 litepal.xml)
3、在文件中添加如下代码
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<dbname value="demo" />
<version value="1" />
<list>
<!--映射创建文件的路径-->
<mapping class="com.example.test.DB.WeatherInfo" />
</list>
</litepal>
4、配置LitePalApplication ,打开AndroidManifest.xml, 在application标签前标签中增加
<manifest>
<application
android:name="org.litepal.LitePalApplication"
...
>
...
</application>
</manifest>
以上是LitePal的配置
二、代码实现
1、创建实体类,继承LitePalSupport
import org.litepal.annotation.Column;
import org.litepal.crud.LitePalSupport;
public class WeatherInfo extends LitePalSupport {
@Column(unique = true, defaultValue = "unknown")
private String cityName;
private String currentTemperature;
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCurrentTemperature() {
return currentTemperature;
}
public void setCurrentTemperature(String currentTemperature) {
this.currentTemperature = currentTemperature;
}
}
2、Then add these models into the mapping list in litepal.xml:
<list>
<!--映射创建文件的路径-->
<mapping class="com.example.test.DB.WeatherInfo" />
</list>
3、如果想得到数据库,就可以在java代码中
SQLiteDatabase db = LitePal.getDatabase();
4、实现添加数据,可以编写一个方法,只要调用这个方法就可以把数据添加到数据库中
import android.text.TextUtils;
import com.example.test.DB.WeatherInfo;
import com.example.test.gson.JsonRootBean;
import com.example.test.gson.Results;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.litepal.LitePal;
import java.util.List;
public class DBManger {
//把请求响应的数据保存到数据库中
public static boolean addData(String responseData){
if(!TextUtils.isEmpty(responseData)){
try {
//通过gson解析数据
Gson gson=new Gson();
JsonRootBean rootBean=gson.fromJson(responseData,JsonRootBean.class);
List<Results> results =rootBean.getResults();
String name=results.get(0).getLocation().getName();
String currentTemperature= results.get(0).getNow().getTemperature();
//创建实体类的对象,把数据传入到实体类中,然后保存,数据就存储到数据库中
WeatherInfo weatherInfo=new WeatherInfo();
weatherInfo.setCityName("Tom");
weatherInfo.setCurrentTemperature("30");
weatherInfo.save();
return true;
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
}
return false;
}
}
5、查询数据,查询所有数据,一行代码搞定
LitePal.findAll(WeatherInfo.class);
6、依据条件查询,更多查询可参照GitHub
LitePal.where("name = ?","北京").find(WeatherInfo.class);