最近新出来Realm Android,性能口碑都不错,因为项目中需要构建数据库,所以学而记之。
1.安装
compile 'io.realm:realm-android:0.84.1'
2.模型
/** * Created by wangchang on 2016/6/20. */
public class User extends RealmObject{
private String name;
@PrimaryKey
private int age;
@Ignore
private int sessionId;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public int getSessionId() { return sessionId; }
public void setSessionId(int sessionId) { this.sessionId = sessionId; }
}
修饰符:
@Required:
告诉 Realm 强制禁止空值(null)被存储。只有 Boolean、 Byte、 Short、 Integer、 Long、 Float、 Double、 String、 byte[] 以及 Date 可以被 @Required 修饰。在其它类型属性上使用 @Required 修饰会导致编译失败。
@Ignore :
标识不想保存到数据库的字段
@PrimaryKey:
主键
3.写入
/** * Created by wangchang on 2016/6/20. */
public class MyApplication extends Application{
private static MyApplication application;
private static RealmConfiguration realmConfiguration;
@Override
public void onCreate() {
super.onCreate();
application=this;
//方式1
realmConfiguration = new RealmConfiguration
.Builder(this)
.name("known")//设置数据库名称
// .encryptionKey(key)//设置加密
.build();
//方式2
// realmConfiguration = new RealmConfiguration.Builder(application).build();
// Realm.setDefaultConfiguration(realmConfiguration);
}
public static MyApplication getInstance(){
return application;
}
public static RealmConfiguration getRealmConfig(){
return realmConfiguration;
}
}
使用:
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
realm=Realm.getInstance(MyApplication.getRealmConfig());
realm=Realm.getDefaultInstance();
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
}
写入(增):
RealmConfiguration realmConfig = new RealmConfiguration.Builder(getApplicationContext()).build();
Realm.setDefaultConfiguration(realmConfig);
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
//创建对象
User user = realm.createObject(User.class);
user.setName("www");
user.setAge(14);
user.setSessionId(1001);
realm.commitTransaction();
创建对象createObject/copyToRealm:
User user = new User("John");
user.setEmail("[email protected]");
// Copy the object to Realm. Any further changes must happen on realmUser
realm.beginTransaction();
User realmUser = realm.copyToRealm(user);
realm.commitTransaction();
写入不提交:
realm.beginWriteTransaction();
//写入
realm.cancelTransaction();
添加json到Realm
public class City extends RealmObject {
private String city;
private int id;
// getters and setters left out ...
}
// Insert from a string
realm.beginTransaction();
realm.createObjectFromJson(City.class, "{ city: \"Copenhagen\", id: 1 }");
realm.commitTransaction();
事务执行块(Transaction blocks):
使用 realm.executeTransaction() 方法,它会自动处理写入事物的开始和提交,并在错误发生时取消写入事物。
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
User user = realm.createObject(User.class);
user.setName("John");
user.setAge(1);
}
});
异步事务(Asynchronous Transactions):
事务会相互阻塞其所在的线程,在后台线程中开启事务进行写入操作可以有效避免 UI 线程被阻塞。通过使用异步事务,Realm 会在后台线程中进行写入操作,并在事务完成时将结果传回调用线程。
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm bgRealm) {
User user = bgRealm.createObject(User.class);
user.setName("John");
user.setEmail("[email protected]");
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
在onstop/ondestory中添加:
public void onStop () {
if (transaction != null && !transaction.isCancelled()) {
transaction.cancel();
}
}
查询:
RealmQuery<User> query = realm.where(User.class);
query.equalTo("name", "www");
RealmResults<User> result = query.findAll();
RealmResults<User> result1 = realm.where(User.class)
.equalTo("age", "12")
.findAll();
Log.e("TAG",result+"//"+result1);
日志:
06-20 17:57:18.195 8545-8545/com.example.com.testrealm E/TAG: [User = [{name:www},{age:12}], User = [{name:www},{age:13}], User = [{name:www},{age:14}], User = [{name:www},{age:15}], User = [{name:www},{age:16}], User = [{name:www},{age:17}], User = [{name:www},{age:18}]]//[User = [{name:www},{age:12}]]
查询支持:
between()、greaterThan()、lessThan()、greaterThanOrEqualTo() 和 lessThanOrEqualTo() equalTo() 和 notEqualTo() contains()、beginsWith() 和 endsWith() isNull() 和 isNotNull() isEmpty() 和 isNotEmpty()
当查询复杂而且耗费大量时间时采用异步查询:
RealmResults<User> result = realm.where(User.class)
.equalTo("name", "John")
.or()
.equalTo("name", "Peter")
.findAllAsync();
排序:
RealmResults<User> result = realm.where(User.class).findAll();
result.sort("age"); // 升序
result.sort("age", RealmResults.SORT_ORDER_DESCENDING);//降序
删除:
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
//刪除第一條
result.remove(0);
//删除最后一条
result.removeLast();
//删除固定一条
User user= result.get(0);
user.removeFromRealm();
// 清空
result.clear();
}
});
更新修改:
//更新
RealmResults<User> results = realm.where(User.class).findAll();
for (User u : results) {
u.setName("李四");
realm.copyToRealmOrUpdate(results);
realm.commitTransaction();
}
//
RealmResults<User> resultd = realm.where(User.class).findAll();
for (int i = 0; i < resultd.size(); i++) {
User u = resultd.get(i);
u.setName("李四");
realm.copyToRealmOrUpdate(results);
realm.commitTransaction();
}
监听器:
当后台线程向Realm添加数据,您的UI线程或者其它线程可以添加一个监听器来获取数据改变的通知。监听器在Realm数据改变的时候会被触发。
public class MyActivity extends Activity {
private Realm realm;
// A reference to RealmChangeListener needs to be held to avoid being
// removed by the garbage collector.
private RealmChangeListener realmListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
reamlListener = new RealmChangeListener() {
@Override
public void onChange() {
// ... do something with the updates (UI, etc.) ...
}};
realm.addChangeListener(realmListener);
}
@Override
protected void onDestroy() {
super.onDestroy();
// Remove the listener.
realm.removeChangeListener(realmListener);
// Close the realm instance.
realm.close();
}
}