2017年1月26日 星期四

How to use Realm

Intsall



Create Models


public class User extends RealmObject {

   private String          name;
   private int             age;

   @Ignore
   private int             sessionId;

   // Standard getters & setters generated by your IDE…
   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; }
}


How to write

Realm realm = Realm.getDefaultInstance();

way 1

realm.beginTransaction();
User user = realm.createObject(User.class); // Create a new object
user.setName("John");
user.setEmail("john@corporation.com");
realm.commitTransaction();


way 2

not block the UI thread
realm.executeTransactionAsync(new Realm.Transaction() {
           @Override
           public void execute(Realm bgRealm) {
               User user = bgRealm.createObject(User.class);
               user.setName("John");
               user.setEmail("john@corporation.com");
           }
       }, 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.
           }
       });

if use primary key


@PrimaryKey
   private String name;


final String name = edName.getText().toString();
               final String old = edOld.getText().toString();

               Realm.Transaction transaction = new Realm.Transaction() {
                   @Override
                   public void execute(Realm bgrealm) {

                       User user = new User(name, old);
                       bgrealm.copyToRealmOrUpdate(user);

                   }
               };

How to query

RealmResults<User> result2 = realm.where(User.class)
                                 .equalTo("name", "John")
                                 .or()
                                 .equalTo("name", "Peter")
                                 .findAll();

result.get(result.size() - 1);


condition

  • between(), greaterThan(), lessThan(), greaterThanOrEqualTo() & lessThanOrEqualTo()
  • equalTo() & notEqualTo()
  • contains(), beginsWith() & endsWith()
  • isNull() & isNotNull()
  • isEmpty() & isNotEmpty()


and   or

Each condition is implicitly logical-and together. Logical-or must be applied explicitly with or().


RealmResults<User> r = realm.where(User.class)
                           .greaterThan("age", 10)  //implicit AND
                           .beginGroup()
                               .equalTo("name", "Peter")
                               .or()
                               .contains("name", "Jo")
                           .endGroup()
                           .findAll();


other…

Sorting

RealmResults<User> result = realm.where(User.class).findAll();
result.sort("age"); // Sort ascending
result.sort("age", RealmResults.SORT_ORDER_DESCENDING);



Auto-Updating Results
auto-updating views into the underlying data, which means results never have to be re-fetched



result = realm.where(User.class).findAll();
    

       result.addChangeListener(new RealmChangeListener<RealmResults<User>>() {
           @Override
           public void onChange(RealmResults<User> element) {
               useResultToSetTheUi(element);
           }
       });




Delete


// obtain the results of a query
final RealmResults<Dog> results = realm.where(Dog.class).findAll();

// All changes to data must happen in a transaction
realm.executeTransaction(new Realm.Transaction() {
   @Override
   public void execute(Realm realm) {
       // remove single match
       results.deleteFirstFromRealm();
       results.deleteLastFromRealm();

       // remove a single object
       Dog dog = results.get(5);
       dog.deleteFromRealm();

       // Delete all matches
       results.deleteAllFromRealm();
   }
});



Thread

Using a Realm across Threads
The only rule to using Realm across threads is to remember that Realm, RealmObject or RealmResults instances cannot be passed across threads

Learn how to work with Android




use with RxJava