Android数据库之Realm

  • Realm

  • 初始化
    // for realm
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
    .deleteRealmIfMigrationNeeded()
    .build();
    Realm.setDefaultConfiguration(realmConfiguration);


  • mRealm = Realm.getDefaultInstance();
    mRealm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(Realm bgRealm) {
    ArticleSave articleSave = bgRealm.createObject(ArticleSave.class);
    articleSave.setDetail(mArticle.getDetail());
    articleSave.setTitle(mArticle.getTitle());
    articleSave.setIntr(mArticle.getIntr());
    articleSave.setImg(mArticle.getImg());
    }
    }, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {
    Snackbar.with(getApplicationContext())
    .text(getString(R.string.save_ok))
    .show(ArtDetailActivity.this);
    }
    }, new Realm.Transaction.OnError() {
    @Override
    public void onError(Throwable error) {
    Snackbar.with(getApplicationContext())
    .text(getString(R.string.save_error))
    .show(ArtDetailActivity.this);
    }
    });


  • mRealm = Realm.getDefaultInstance();
    mRealm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
    RealmResults results = realm.where(ArticleSave.class)
    .equalTo("title",mSaveAdapter.getItem(position).getTitle())
    .findAll();
    results.deleteFirstFromRealm();
    Log.d(TAG,"delete success");
    }
    });


  • mRealm = Realm.getDefaultInstance();
    mRealm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
    RealmQuery query = realm.where(ArticleSave.class);
    RealmResults result1 = query.findAll();
    fillData(result1);
    }
    });

  • 关闭数据库
    if(mRealm != null)
    mRealm.close();

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