Android Realm(数据库)

Realm

1. build.gradle配置

1). 项目根目录下的build.gradle,在dependencies中添加

      // 最新版
       classpath "io.realm:realm-gradle-plugin:4.3.1"
      // 备用 
      // classpath "io.realm:realm-gradle-plugin:2.2.1"

2). 在主Module的build.gradle文件中添加

      apply plugin: 'realm-android'
      realm {
          syncEnabled = true;
      }

2. 初始化Realm并配置

1). 初始化

public class MyApplication extends Application {
  @Override
  public void onCreate() {
    super.onCreate();
    Realm.init(this);
  }
}

2). 获取Realm

// 默认配置
Realm realm = Realm.getDefaultInstance();
// 自定义配置

        RealmConfiguration config =
                new RealmConfiguration.Builder()
                        // 文件名
                        .name("test.realm")
                        // 版本号
                        .schemaVersion(1)
                        .build();
        Realm realm = Realm.getInstance(config);

3. 数据库查看工具

1). 使用Stetho并使用stetho_realm共同在chrome中查看数据库

    // 调试工具--chrome://inspect/#devices
    debugCompile 'com.facebook.stetho:stetho:1.5.0'
    debugCompile 'com.uphyca:stetho_realm:2.1.0'

2). 项目的根目录下的build.gradle文件中

allprojects {
    repositories {
        jcenter()
        // 添加,下载stetho_realm
        maven {
            url 'https://github.com/uPhyca/stetho-realm/raw/master/maven-repo'
        }
    }
}

3). 在MyApplication中初始化

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Realm.init(this);

        Stetho.initialize(
                Stetho.newInitializerBuilder(this)
                        .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
                        .enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
                        .build());
    }
}

4. 具体使用

你可能感兴趣的:(Android Realm(数据库))