realm.beginTransaction(); User user = realm.createObject(User.class); // Create a new object user.setName("John"); user.setEmail("john@corporation.com"); realm.commitTransaction();
将已存在对象拷贝进realm
1 2 3 4 5 6 7
Country country2 = new Country(); country2.setName("Russia"); country2.setPopulation(146430430); country2.setCode("RU"); realm.beginTransaction(); Country copyOfCountry2 = myRealm.copyToRealm(country2); realm.commitTransaction();
或者并不立即commit[4]
1 2 3 4 5
realm.beginWriteTransaction(); User user = realm.createObject(User.class); // Create a new object user.setName("John"); user.setEmail("john@corporation.com") realm.cancelTransaction();
或者
1 2 3 4 5 6 7 8
realm.executeTransaction(new Realm.Transaction() { @Override publicvoidexecute(Realm realm){ User user = realm.createObject(User.class); user.setName("Cuber"); user.setAge(26); } });
以及update
1 2 3 4 5 6 7 8 9
MyObject obj = new MyObject(); obj.setId(42); obj.setName("Fish"); realm.beginTransaction(); // This will create a new one in Realm // realm.copyToRealm(obj); // This will update a existing one with the same id or create a new one instead realm.copyToRealmOrUpdate(obj); realm.commitTransaction();
注意上面的createObject方法
1 2 3 4 5 6
public <E extends RealmObject> E createObject(Class<E> clazz) { checkIfValid(); Tabletable = getTable(clazz); long rowIndex = table.addEmptyRow(); returnget(clazz, rowIndex); }
// Execute the query: RealmResults<User> result1 = query.findAll();
// Or alternatively do the same all at once (the "Fluent interface"): RealmResults<User> result2 = realm.where(User.class) .equalTo("name", "John") .or() .equalTo("name", "Peter") .findAll();
// Execute the disposal of abandoned realm objects each time a new realm object is created context.executeDelayedDisposal(); long nativeViewPtr = nativeFindAll(nativePtr, 0, Table.INFINITE, Table.INFINITE); try { returnnew TableView(this.context, this.table, nativeViewPtr, this); } catch (RuntimeException e) { TableView.nativeClose(nativeViewPtr); throw e; } }
public class Migration implements RealmMigration {
@Override public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) { // During a migration, a DynamicRealm is exposed. A DynamicRealm is an untyped variant of a normal Realm, but // with the same object creation and query capabilities. // A DynamicRealm uses Strings instead of Class references because the Classes might not even exist or have been // renamed.
// Access the Realm schema in order to create, modify or delete classes and their fields. RealmSchema schema = realm.getSchema();
/************************************************ // Version 0 class Person @Required String firstName; @Required String lastName; int age;
// Version 1 class Person @Required String fullName; // combine firstName and lastName into single field. int age; ************************************************/ // Migrate from version 0 to version 1 if (oldVersion == 0) { RealmObjectSchema personSchema = schema.get("Person");
// Combine 'firstName' and 'lastName' in a new field called 'fullName' personSchema .addField("fullName", String.class, FieldAttribute.REQUIRED) .transform(new RealmObjectSchema.Function() { @Override public void apply(DynamicRealmObject obj) { obj.set("fullName", obj.getString("firstName") + " " + obj.getString("lastName")); } }) .removeField("firstName") .removeField("lastName"); oldVersion++; } } }
三、一些高级特性 1.Dynamic Realms[7]: 使用String 而不是Class,DynamicRealmObject person = realm.createObject(“Person”); 他会忽略schema,migration,和数据版本号,这种写法会放弃安全性和性能但会提高灵活性。在编译或者数据库升级时我们无法通过Class操作数据库等场景时可以考虑使用该种方式
2.和JSON结合使用
loadJsonFromStream
1 2 3 4 5 6 7 8 9 10 11 12 13
InputStream stream = getAssets().open("cities.json"); realm.beginTransaction(); try { realm.createAllFromJson(City.class, stream); realm.commitTransaction(); } catch (IOException e) { // Remember to cancel the transaction if anything goes wrong. realm.cancelTransaction(); } finally { if (stream != null) { stream.close(); } }
public classMyActivityextendsActivity { privateRealm realm; // A reference to RealmChangeListener needs to be held to avoid being // removed by the garbage collector. privateRealmChangeListener realmListener;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); realm = Realm.getDefaultInstance(); reamlListener = newRealmChangeListener() { @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(); } }
避免使用匿名类加入到listener中,自行维护listener的销毁。
7.关系和关联查询 任意两个RealmObject可以相互关联
1 2 3 4 5 6 7 8 9
public classContactextendsRealmObject { privateEmail email; // Other fields… }
public classContactextendsRealmObject { privateRealmList<Email> emails; // Other fields… }
也可以使用递归
1 2 3 4 5
public classPersonextendsRealmObject { privateString name; privateRealmList<Person> friends; // Other fields… }