相信技术的力量

Realm数据库简单入门

官网

Realm官网

android文档

一个不错的Realm简介博客

模型

public class Dog extends RealmObject {
    public String name;
    public int age;
}

创建实体的方法:

1.直接new
    Dog dog = new Dog();

2.通过create()方法
    Dog dog = realm.create(Dog.class)

3.通过create()+预设主键(PrimaryKey)的方法
    Dog dog =realm.create(Dog.class,1)

添加Bean进Database

Dog dog = new Dog();
dog.name = "Rex";
dog.age = 1;
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealm(dog)
realm.commitTransaction();

查询

RealmResults<Dog> pups = realm.where(Dog.class)
                               .lessThan("age", 2)
                               .findAll();

添加数据监听

// Listeners will be notified when data changes
pups.addChangeListener(new RealmChangeListener<RealmResults<Dog>>() {
    @Override
    public void onChange(RealmResults<Dog> results) {
        // Query results are updated in real time
        puppies.size(); // => 1
    }
});

支持异步任务

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.
            }
        });

Realm的异步操作

在子线程执行任务,在主线程发布onSuccess回调

Realm.getDefaultInstance().executeTransactionAsync(new Realm.Transaction() {

    @Override
    public void execute(Realm realm) {
        //此方法在子线程
        realm.copyToRealmOrUpdate(userBean);
        KLog.i("execute...." + Thread.currentThread().getName() + "..." + (Looper.myLooper() == Looper.getMainLooper()));
    }
}, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {
        //此方法在子线程
        KLog.i("onSuccess...." + Thread.currentThread().getName() + "..." + (Looper.myLooper() == Looper.getMainLooper()));
    }
});

Log输出:

execute....pool-8-thread-1...false
onSuccess....main...true

其他基础操作只是在此基础上简单的换下api而已,不再记录.

⬆️