1. 程式人生 > >使用Realm進行資料操作(一)

使用Realm進行資料操作(一)

初探Realm的基本使用

一、新增外掛

  • 第一步:新增classpath “io.realm:realm-gradle-plugin:2.3.1”
    classpath

  • 第二步:新增apply plugin: ‘realm-android’
    applyplugin

二、配置Realm資料庫

  在自定義的Aplication中對Realm進行配置。

/**
 * Author LYJ
 * Created on 2017/2/9.
 * Time 11:35
 */

public class App extends Application{
    @Override
    public void onCreate() {
        super
.onCreate(); Realm.init(this);//初始化Realm RealmConfiguration configuration = new RealmConfiguration.Builder() .name("mineRealm.realm")//設定資料庫名稱 .schemaVersion(0)//設定版本號 .build(); Realm.setDefaultConfiguration(configuration);//設定配置 } }

三、建立Person資料表

  建立Person類並繼承RealmObject。使用@PrimaryKey修飾的變數為主鍵。

/**
 * Author LYJ
 * Created on 2017/2/9.
 * Time 11:49
 * 這就相當於一張表,Person表
 */

public class Person extends RealmObject{
    @PrimaryKey
    private String id;//主鍵ID
    private String name;//姓名
    private int age;//年齡

    public String getId(
) { return id; } public void setId(String id) { this.id = id; } 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; } }

四、在Activity中獲取和關閉Realm

  • 獲取Realm物件
realm = Realm.getDefaultInstance();
  • 關閉Realm
    /**
     * 銷燬介面
     */
    @Override
    protected void onDestroy() {
        realm.close();
        super.onDestroy();
    }

五、增加資料

  使用事務向Person表中增加資料。在Realm中主鍵不能自增。這裡將使用UUID來為Person表設定主鍵的ID。

    Person person = new Person();//要插入的資料
    person.setId(UUID.randomUUID().toString());//設定ID
    person.setName(inputName);//設定插入資料的名字
    person.setAge(Integer.parseInt(inputAge.trim()));//設定插入資料的年齡
    realm.beginTransaction();//開啟事務
    realm.copyToRealmOrUpdate(person);//傳入物件
    realm.commitTransaction();//提交事務

【向Person資料表中新增3條資料。】
插入資料
【通過上圖中的操作,成功向資料庫中插入了3條資料。】
查詢結果

六、修改資料

  使用事務修改Person表中的資料。這裡先使用條件查詢,獲取到查詢結果後會得到一個Person物件,該物件就對應著表中的一條資料。隨後直接對物件的修改在提交事務,就可以將資料更新了。

    Person result = selectResult(inputName);//查詢結果
    realm.beginTransaction();//開啟事務
    result.setAge(Integer.parseInt(inputAge.trim()));//設定年齡
    realm.commitTransaction();//提交事務

【將Person表中名為Make的年齡改為21。】
修改資料
【成功的將Make的年齡改為了21。】
查詢結果

七、刪除資料

  使用事務刪除Person表中的資料

    Person result = selectResult(inputName);//查詢結果
    realm.beginTransaction();//開啟事務
    result.deleteFromRealm();//刪除資料
    realm.commitTransaction();//提交事務

【因為Make的存在影響了Jack與Rose的感情,所以Make決定離開】
刪除
【從此Jake與Rose幸福的生活在了一起】
查詢

八、查詢資料

  • 全部查詢
    RealmResults<Person> results = realm.where(Person.class).findAll();//查詢結果
    List<Person> personList = realm.copyFromRealm(results);
  • 條件查詢
    /**
     * 條件查詢
     * @param name
     */
    private Person selectResult(String name){
        //條件查詢
        Person person = realm.where(Person.class).equalTo("name",name).findFirst();
        return person;//查詢結果
    }

參考資料