本文最后更新于:1 个月前
Litepal,一个关于安卓数据库操作的一个第三方开源库,由《第一行代码》作者郭霖开源并维护。
1. Include library
dependencies {
implementation 'org.litepal.guolindev:core:3.1.1'
}
2. 配置litepal.xml
在项目的 assets 目录下新建一个 litepal.xml 文件,把下面的代码 copy 过去:
<?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>
3. 配置 LitePalApplication
由于操作数据库时需要用到 Context,而我们显然不希望在每个接口中都去传一遍这个参数,那样操作数据库就显得太繁琐了。因此,LitePal使用了一个方法来简化掉 Context 这个参数,只需要在 AndroidManifest.xml 中配置一下LitePalApplication,所有的数据库操作就都不用再传Context了,如下所示:
<manifest>
<application
android:name="org.litepal.LitePalApplication"
...
>
...
</application>
</manifest>
当然,有些程序可能会有自己的Application,并在这里配置过了。比如说有一个MyApplication,如下所示:
<manifest>
<application
android:name="com.example.MyApplication"
...
>
...
</application>
</manifest>
没有关系,这时只需要在自定义的 Application 中添加一句 Litepal.initialize(context)
:
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LitePal.initialize(this);
}
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!