LitePal是一个便于开发者使用SQLite的Android框架,极大的简化了SQLite的使用,这是它的github地址
https://github.com/LitePalFramework/LitePal
初期准备
1.导入
在build.gradle中加入依赖
dependencies {
compile 'org.litepal.android:core:1.6.1'
}
2.配置litepal.xml
在app/src/main下新建文件夹assets,在该文件夹下new->Android resource file新建一个xml文件命名为litepal,复制以下内容到这个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>
- dbname 该数据库的名字
- version 该数据库的版本
- list 配置映射类
- storage 配置数据的储存位置,只有internal和external两个值
3.配置 LitePalApplication
为便于使用,避免不必要的参数传递,在AndroidManifest.xml中作如下配置
<manifest>
<application
android:name="org.litepal.LitePalApplication"
...
>
...
</application>
</manifest>
然后在Application中初始化
public class MyOwnApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LitePal.initialize(this);
}
...
}
使用
1.创建数据表
定义一个类,类名为表名,成员变量为表中各个属性,为便于操作,需继承自DataSupport,假如有Album和Song两个表
public class Album extends DataSupport {
@Column(unique = true, defaultValue = "unknown")
private String name;
private float price;
private byte[] cover;
private List<Song> songs = new ArrayList<Song>();
// generated getters and setters.
...
}
public class Song extends DataSupport {
@Column(nullable = false)
private String name;
private int duration;
@Column(ignore = true)
private String uselessField;
private Album album;
// generated getters and setters.
...
}
然后在litepal.xml中的<List> </list>中添加
<list>
<mapping class="org.litepal.litepalsample.model.Album" />
<mapping class="org.litepal.litepalsample.model.Song" />
</list>
这样在下次操作数据库的时候就会生成这个表。
得到数据库:
SQLiteDatabase db = LitePal.getDatabase();
2.更新数据表
只需要改变该类的成员变量,然后改变litepal.xml中的verson值及可更新数据表
<!--
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>
-->
<version value="2" ></version>
3.添加数据
为该数据表添加数据只需新定义一个对象,然后调用save()就可以添加
Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
album.save(); //svae()方法
Song song1 = new Song();
song1.setName("song1");
song1.setDuration(320);
song1.setAlbum(album);
song1.save(); //svae()方法
Song song2 = new Song();
song2.setName("song2");
song2.setDuration(356);
song2.setAlbum(album);
song2.save(); //svae()方法
4.更新数据
调用find()找到id为i的该行数据,然后改变相应值,调用save()即可更新该行数据
id为数据表创建时自动添加的一个属性
Album albumToUpdate = DataSupport.find(Album.class, 1);
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.save();
如果想一次修改多条数据,调用updateAll();
Album albumToUpdate = new Album();
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.updateAll("name = ?", "album");
5.删除数据
删除单条,用delete()
DataSupport.delete(Song.class, id);
删除多条
DataSupport.deleteAll(Song.class, "duration > ?" , "350");
6.查找数据
查找单条数据(根据id)
Song song = DataSupport.find(Song.class, id);
查找所有数据
List<Song> allSongs = DataSupport.findAll(Song.class);
按条件查找并排序
List<Song> songs = DataSupport.where("name like ? and duration < ?", "song%", "200").order("duration").find(Song.class);
7.异步操作
每次数据库操作默认是在main thread操作的,如果有耗时查询,需要用异步操作findAllAsync(),存储用saveAsync()
操作结果在onFinish()回调,
DataSupport.findAllAsync(Song.class).listen(new FindMultiCallback() {
@Override
public <T> void onFinish(List<T> t) {
List<Song> allSongs = (List<Song>) t;
}
});
Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
album.saveAsync().listen(new SaveCallback() {
@Override
public void onFinish(boolean success) {
}
});