- 同步操作:增加一对多表,Person包含多个Men(以executeTransaction为例)
MorePerson类在文章最下方提供
mRealm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
MorePerson morePerson = realm.createObject(MorePerson.class);
morePerson.setCity(“杭州”);
morePerson.setProject(“开发工程师”);
morePerson.setTime(simpleDateFormat.format(new Date()));
for (int i = 0; i < 3; i++) {
Men men = realm.createObject(Men.class);
men.setName(“huangxiaoguo” + i);
men.setAge(new Random().nextInt(100));
morePerson.getMens().add(men);
}
}
});
注意:在Realm中不能使用android原有的list集合,需要Realm特定的RealmList集合!
- 同步操作:增加一对多表,Person包含多个Men(以copyToRealm为例)
final MorePerson morePerson1 = new MorePerson();
morePerson1.setCity(“杭州”);
morePerson1.setProject(“开发工程师”);
morePerson1.setTime(simpleDateFormat.format(new Date()));
RealmList menList = new RealmList<>();
for (int i = 0; i < 3; i++) {
Men men2 = new Men();
men2.setName(“huangxiaoguo” + i);
men2.setAge(new Random().nextInt(100));
menList.add(men2);
}
morePerson1.setMens(menList);
for (int i = 0; i < 3; i++) {
Men men2 = new Men();
men2.setName(“huangxiaoguo” + i);
men2.setAge(new Random().nextInt(100));
morePerson1.getMens().add(men2);
}
mRealm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
realm.copyToRealm(morePerson1);
}
});
- 同步操作:beginTransaction和commitTransaction方法插入数据(不建议使用)
//注意:在UI和后台线程同时开启创建write的事务,可能会导致ANR错误。
// 为了避免该问题,可以使用executeTransactionAsync来实现。
mRealm.beginTransaction();//开启事务
Student student1 = mRealm.createObject(Student.class);
student1.setName(“事务方式插入数据”);
student1.setNum(new Random().nextInt(100) + 100);
mRealm.commitTransaction();
异步操作(建议使用)
- 异步操作:使用executeTransactionAsync直接插入数据
//该方法会开启一个子线程来执行事务,并且在执行完成后进行结果通知。
realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Student student2 = realm.createObject(Student.class);
student2.setName(“使用executeTransactionAsync直接插入数据”);
student2.setNum(new Random().nextInt(100) + 200);
}
});
异步操作需要在activity不可见或关闭时取消任务
@Override
protected void onDestroy() {
super.onDestroy();
if (realmAsyncTask != null && !realmAsyncTask.isCancelled()) {
realmAsyncTask.cancel();
}
if (mRealm != null && !mRealm.isClosed()) {
mRealm.close();
}
}
- 异步操作:使用executeTransactionAsync并且进行监听
//注意:如果当Acitivity或Fragment被销毁时,在OnSuccess或OnError中执行UI操作,
// 将导致程序奔溃 。用RealmAsyncTask .cancel();可以取消事务
//在onStop或onDestroy中调用,避免crash
realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Student student2 = realm.createObject(Student.class);
student2.setName(“使用executeTransactionAsync监听”);
student2.setNum(new Random().nextInt(100) + 300);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess