配置项目build.gradle文件
buildscript {
dependencies {
classpath "io.realm:realm-gradle-plugin:3.1.3"
}
}
配置app模块build.gradle文件
apply plugin: 'realm-android'
初始化Realm
创建自定义Application
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
}
}
并在manifest
中设置
<application
android:name=".MainApplication"
...
>
创建Realm对象
package me.zongren.realmdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import io.realm.Realm;
import io.realm.RealmConfiguration;
public class MainActivity extends AppCompatActivity {
private Realm realm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RealmConfiguration configuration = new RealmConfiguration.Builder().build();
Realm.deleteRealm(configuration);
realm = Realm.getInstance(configuration);
}
}
关闭Realm
在onDestroy方法中移除Notification Listener,并关闭realm
@Override
protected void onDestroy() {
realm.removeAllChangeListeners();
realm.close();
super.onDestroy();
}
官方文档
Demo
A demo of realm in android:GitHub