参考文章
- Android数据库高手秘籍(一)——SQLite命令
- Android数据库高手秘籍(二)——创建表和LitePal的基本用法
- Android数据库高手秘籍(三)——使用LitePal升级表
- Android数据库高手秘籍(四)——使用LitePal建立表关联
- Android数据库高手秘籍(五)——LitePal的存储操作
- Android数据库高手秘籍(六)——LitePal的修改和删除操作
- Android数据库高手秘籍(七)——体验LitePal的查询艺术
- Android数据库高手秘籍(八)——使用LitePal的聚合函数
- LitePal 1.4.0版本发布,你们要的多数据库功能终于来了
- LitePal 1.5.0版本发布,你想要的都在这里
- LitePal 1.6.0版本来袭,数据加解密功能保障你的应用数据安全
Include library
implementation 'org.litepal.android:core:1.6.1'
Configure litepal.xml
Create a file in the assets folder of your project and name it as litepal.xml. Then copy the following codes into it.
<?xml version="1.0" encoding="utf-8"?>
<litepal>
<!--
Define the database name of your application.
By default each database name should be end with .db.
If you didn't name your database end with .db,
LitePal would plus the suffix automatically for you.
For example:
<dbname value="demo" />
-->
<dbname value="demo" />
<!--
Define the version of your database. Each time you want
to upgrade your database, the version tag would helps.
Modify the models you defined in the mapping tag, and just
make the version value plus one, the upgrade of database
will be processed automatically without concern.
For example:
<version value="1" />
-->
<version value="1" />
<!--
Define your models in the list with mapping tag, LitePal will
create tables for each mapping class. The supported fields
defined in models will be mapped into columns.
For example:
<list>
<mapping class="com.test.model.Reader" />
<mapping class="com.test.model.Magazine" />
</list>
-->
<list>
</list>
<!--
Define where the .db file should be. "internal" means the .db file
will be stored in the database folder of internal storage which no
one can access. "external" means the .db file will be stored in the
path to the directory on the primary external storage device where
the application can place persistent files it owns which everyone
can access. "internal" will act as default.
For example:
<storage value="external" />
-->
</litepal>
Configure LitePalApplication
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
LitePal.initialize(this);
}
}
ProGuard
-keep class org.litepal.** {
*;
}
-keep class * extends org.litepal.crud.DataSupport {
*;
}
注意事项
id关键字问题
如果实体中包含id字段,会被系统保留关键字id覆盖并且自增长,处理方法为:重命名为其他字段名
@Column(unique = true)
@SerializedName("id")
private int articleId;
如上,服务器传过来的id字段,SerializedName解决Gson映射问题。
保存的时候,保证唯一性,避免多次保存同一记录
article.saveOrUpdate("articleid = ?", String.valueOf(article.getArticleId()));