Android——LitePal
implementation 'org.litepal.android:java:3.0.0'
1. 修改AndroidManifest.xml
android:name="org.litepal.LitePalApplication"
2. main包下生成assets文件夹,并创建litepal.xml
<?xml version="1.0" encoding="utf-8" ?> <litepal> <!-- 数据库名 --> <dbname value="weather.db"/> <!-- 版本号 --> <version value="1"/> <!-- 和类映射的mapping文件,如果有多个实体类,那就写多个mapping--> <list> <!-- mapping 映射 包名加上类全名 --> <mapping class="com.example.myandroiddemo.domain.Weather" /> <!-- <mapping class="com.example.myandroiddemo.domain.Data" />--> </list> <!-- 每更新一次数据库,版本号需要改变, +1--> </litepal>
<!--
dbname设置数据库名称
version 设置版本号,修改表结构或者新增与删除表需要更改 version
list 里添加表
-->
3. 创建bean类,继承LitePalSupport
package com.example.myandroiddemo.domain; import org.litepal.crud.LitePalSupport; public class Weather extends LitePalSupport { private String date; private String temperature; private String weather; private String direct; public String getTemperature() { return temperature; } public void setTemperature(String temperature) { this.temperature = temperature; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public String getDirect() { return direct; } public void setDirect(String direct) { this.direct = direct; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } @Override public String toString() { return "Weather{" + "date='" + date + '\'' + ", temperature='" + temperature + '\'' + ", weather='" + weather + '\'' + ", direct='" + direct + '\'' + '}'; } }
4. 在util包下生成:LiteHelper 暴露接口
package com.example.myandroiddemo.litepalManager; import android.content.ContentValues; import com.example.myandroiddemo.domain.Weather; import org.litepal.LitePal; import java.util.ArrayList; import java.util.List; public class LitePals { // 删除 public static void deleteWeather(int id){ // 根据id删除 LitePal.delete(Weather.class,id); } // 增加 public static void addWeatherData(Weather weather){ weather.save(); //继承的那个 , 设置后直接save } //查询 public static List<Weather> findAllWeatherData(){ // List<Weather> list = new ArrayList<>(); List<Weather> weatherList = LitePal.findAll(Weather.class); // for (int i = 0; i < list.size(); i++) { // list.add(weatherList.get(i)); // } return weatherList; } //修改 public static void updateWeatherData(int id){ ContentValues contentValues = new ContentValues(); LitePal.update(Weather.class,contentValues,id); } }