Realm,为移动设备而生。替代 SQLite 和 Core Data。
非常庆幸,官方帮助文档有中文: https://realm.io/cn/docs/java/latest/
尽管眼下最新的版本号0.88.3,连1.0的版本号都没有公布…可是全然不影响她的强大;
API文档: https://realm.io/docs/java/latest/api/
因为官方的帮助文档,有中文的…大家看起来非常easy懂,我这里仅仅依据个人使用经验,写写体验.
1:Realm的引用
Project级别的build.gradle文件:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath ‘com.android.tools.build:gradle:2.1.0-beta3‘
classpath ‘me.tatarka:gradle-retrolambda:3.3.0-beta4‘ //lambda表达式配置步骤1
classpath "io.realm:realm-gradle-plugin:0.88.3"//注意此行
}
}
allprojects {
repositories {
jcenter()
}
}
Module级别的build.gradle
apply plugin: ‘com.android.application‘
apply plugin: ‘me.tatarka.retrolambda‘ //lambda表达式配置步骤2
apply plugin: ‘realm-android‘ //注意此行
android {
...
//lambda表达式配置步骤3,结束.
compileOptions {
encoding "UTF-8"
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
...
}
(彩蛋:上述中,包括了lambda表达式的配置步骤…你懂得)
2:增删改查的操作
//封装的操作类
public class RRealm {
/**
* 必须调用的方法
*/
public static void init(Context context, String name, boolean clean) {
RealmConfiguration configuration = new RealmConfiguration.Builder(context).name(name).build();
if (clean) {
Realm.deleteRealm(configuration);
}
Realm.setDefaultConfiguration(configuration);
}
public static Realm realm() {
return Realm.getDefaultInstance();
}
/**
* 通常能够直接此方法
*/
public static void operate(OnOperate operate) {
if (operate != null) {
Realm realm = realm();
realm.beginTransaction();
operate.on(realm);
realm.commitTransaction();
realm.close();
}
}
public interface OnOperate {
void on(Realm realm);
}
}
private void add() {
RRealm.operate(realm -> {
for (int i = 0; i < Num; i++) {
TestRealmObject realmObject = realm.createObject(TestRealmObject.class);
realmObject.setAge(i);
realmObject.setName("name" + i);
realmObject.setTest("test" + i);
realmObject.setTime(System.currentTimeMillis());
}
});
}
private void delete() {
RRealm.operate(realm -> {
RealmResults<TestRealmObject> all = realm.where(TestRealmObject.class).findAll();
all.clear();
});
}
private void update() {
RRealm.operate(realm -> {
RealmResults<TestRealmObject> all = realm.where(TestRealmObject.class).findAll();
for (int i = 0; i < all.size(); i++) {
TestRealmObject object = all.get(i);
object.setName(object.getName() + " new");
object.setTest(object.getTest() + " new");
}
});
}
private void query() {
RRealm.operate(realm -> {
RealmQuery<TestRealmObject> where = realm.where(TestRealmObject.class);
RealmResults<TestRealmObject> all = where.findAll();
for (TestRealmObject object : all) {
e(object.toString());
}
});
}
3:性能评估
//測试类
public class TestRealmObject extends RealmObject {
public String name;
public int age;
public long time;
public String test;
}
//插入1000条数据: 149 毫秒 148 158 118
//查询1000条数据: 146 毫秒 183 178 192
//删除1000条数据: 39 毫秒 44 37 38
//更新1000条数据: 212 毫秒 195 185 216
//数据仅供參考
再次提醒:官方有中文文档,大家能够具体阅读,会比較好;
至此: 文章就结束了,如有疑问: QQ群:274306954 欢迎您的增加.