一、什么是LitePal
LitePal是一款开源的Android数据库框架,采用了对象关系映射(ORM)的模式,将平时开发时最常用的一些数据库功能进行了封装,使得开发者不用编写一行SQL语句就可以完成各种建表、増删改查的操作。
二、设置LitePal
1、包含库
编辑build.gradle文件并添加下面的依赖关系
dependencies {
compile ‘org.litepal.android:core:1.6.1’
}
2、配置litepal.xml
右击app/src/main目录,创建一个assets文件夹,然后在这个文件夹下创建一个litepal.xml的文件,接着编辑这个文件中的内容,如下面所示:
<?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
为了简化API,只需要在AndroidManifest中配置LitepalApplication
<manifest>
<application
android:name="org.litepal.LitePalApplication"
...
>
...
</application>
</manifest>
三、使用Litepal
1、创建表格
定义模型-Album和Song
public clas