Android数据库新王者-Realm入门教程
好長時間沒有寫關于Android方面的學習文章了,今天給大家帶來的是堪稱是一個可以替代SQLite以及ORMlibraries的輕量級數據庫—Realm移動端數據庫。
相比SQLite,Realm更快并且具有很多現代數據庫的特性,比如支持JSON,流式api,數據變更通知,以及加密支持,這些都為安卓開發者帶來了方便。
Ream提供了五種編程方式的實現。分別是Java,Objective C,Swift,React-Native,tamarin。在這里我著重介紹在Android中的使用。后面也會介紹在Swift中得使用。
1.先介紹一下打開數據Realm數據庫的工具:Realm Browser可視化工具
Realm資源包中包含了一個很有用的實用工具,可以幫助我們更好地管理Realm數據庫,那就是Realm Browser。Realm Browser可以讓您輕松地讀寫Realm數據庫(以.realm結尾),因此我們無需頭疼如何去查看Realm專有數據庫的邏輯結構以及其中的數據,可視化的操作就如同SQLite的其他數據庫查看工具一樣,十分簡單、易用(雖然Realm Browser的功能還十分簡陋,真的只能讀寫而已)。
2.Realm支持的數據類型
- 支持基本數據結構:boolean, byte, short, ìnt, long, float, double, String, Dateand byte[]
- 支持JSON等復雜的數據類型
3.Realm的官方名詞
- Realm:Realm是框架的核心所在,是我們構建數據庫的訪問點,使用建造者模式構建對象。
- RealmObject:這是我們自定義的realm數據模型。創建數據模型的行為將會影響到數據庫的結構。要創建一個數據模型,我們只需要繼承RealmObject,然后設計我們想要存儲的屬性即可。
- RealmQuery(查詢):要在數據庫中檢索信息,我們需要用到“檢索”操作。如果需要檢索更復雜的數據,那么還可以使用復合查詢以及結果排序等等操作。
- RealmResults:這個類是執行任何查詢請求后所返回的類,其中包含了一系列的Object對象。和List類似,我們可以用下標語法來對其進行訪問,并且還可以決定它們之間的關系。不僅如此,它還擁有許多更強大的功能,包括排序、查找等等操作。
4、Realm在Android中的使用
4.1在項目的build.grade中配置下載庫文件
在本案例中我使用的最新版本的1.0.0版本。
apply plugin: 'realm-android'buildscript {repositories {jcenter()maven { url 'https://jitpack.io' }}dependencies {classpath "io.realm:realm-gradle-plugin:1.0.0"} }4.2創建數據庫,獲取去Realm
package com.lidong.demo.realm;import android.content.Context;import io.realm.Realm; import io.realm.RealmConfiguration; /** * *@className:RealmUtil *@desc:RealmUtil工具類 *@author:lidong *@datetime:16/6/10 下午9:55*/ public class RealmUtil {private static RealmUtil sIntance;public final Context mContext;private String realmName = "realm_demo.realm";public RealmUtil(Context mContext) {this.mContext = mContext;}/*** 雙檢索單例* @param context* @return*/public static RealmUtil getIntance(Context context){if (sIntance == null) {synchronized (RealmUtil.class) {if (sIntance == null) {sIntance = new RealmUtil(context);}}}return sIntance;}/*** 獲取realm對象* @return*/public Realm getRealm(){ Realm realm =Realm.getInstancenew RealmConfiguration.Builder(mContext) .name(realmName) .build());return realm;} }4.3創建一個RealmObject
只要繼承了RealmObject類,任意JavaBean都能存儲在Realm中。必須有一個默認構造器,成員變量有相應的getter/setter方法
package com.lidong.demo.realm;import io.realm.RealmObject; import io.realm.annotations.PrimaryKey;/*** Person*/ public class Person extends RealmObject {@PrimaryKeyprivate String code;//編號private String name;//姓名private int age;//年齡public Person() {}public Person(int age, String code, String name) {this.age = age;this.code = code;this.name = name;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}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;}@Overridepublic String toString() {return "Person{" +"code='" + code + '\'' +", name='" + name + '\'' +", age=" + age +'}';} }4.4對數據Person進行增刪改查操作
PersonDao.java
package com.lidong.demo.realm;import java.util.List;/*** Created by lidong on 16/6/9.*/ public interface PersonDao {/*** 插入Person* @param person* @throws Exception*/void insert(Person person)throws Exception;/*** 獲取所有的用戶* @return* @throws Exception*/List<Person> getAllPerson()throws Exception;/*** 更新用戶* @throws Exception*/Person updatePerson(Person person)throws Exception;/*** 刪除用戶* @param code* @throws Exception*/void deletePerson(String code)throws Exception;/*** 異步插入Person* @param person* @throws Exception*/void insertPersonAsync(Person person)throws Exception;}PersonDaoImp.java
package com.lidong.demo.realm;import android.content.Context;import java.util.List;import io.realm.Realm;/** * *@className:PersonDaoImpl *@desc: *@author:lidong *@datetime:16/6/10 下午10:01*/ public class PersonDaoImpl implements PersonDao {private Context context;private Realm mRealm;public PersonDaoImpl(Context context){mRealm = RealmUtil.getIntance(context).getRealm();}/*** @同步插入用戶* @param person* @throws Exception*/@Overridepublic void insert(Person person) throws Exception {mRealm.beginTransaction();Person person1 = mRealm.copyToRealm(person);mRealm.commitTransaction();mRealm.close();}/*** 獲取所有的用戶** @return* @throws Exception*/@Overridepublic List<Person> getAllPerson() throws Exception {List<Person> mlist = null;mlist = mRealm.where(Person.class).findAll();mRealm.close();return mlist;}/*** @param person* @throws Exception*/@Overridepublic Person updatePerson(Person person) throws Exception {mRealm.beginTransaction();Person person1 = mRealm.copyToRealmOrUpdate(person);mRealm.commitTransaction();mRealm.close();return person1;}@Overridepublic void deletePerson(String code) throws Exception {Person person = mRealm.where(Person.class).equalTo("code",code).findFirst();mRealm.beginTransaction();person.deleteFromRealm();mRealm.commitTransaction();}/*** 異步插入Person** @param person* @throws Exception*/@Overridepublic void insertPersonAsync(final Person person) throws Exception {//一個Realm只能在同一個線程中訪問,在子線程中進行數據庫操作必須重新獲取Realm對象:mRealm.executeTransaction(new Realm.Transaction() {@Overridepublic void execute(Realm realm) {realm.beginTransaction();Person person1 = realm.copyToRealm(person);realm.commitTransaction();realm.close();//并且要記得在離開線程時要關閉 realm.close(); }});mRealm.close();//關閉Realm對象} }4.5在Activity中簡單調用
package com.lidong.demo.realm;import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log;import com.lidong.demo.R;import java.util.List;import io.realm.Realm;public class DemoRealmActivity extends AppCompatActivity {static final String TAG = DemoRealmActivity.class.getSimpleName();Realm mRealm;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_demo_realm);// mRealm= RealmUtil.getIntance(this).getRealm(); // // // mRealm.executeTransaction(new Realm.Transaction() { // @Override // public void execute(Realm realm) { // Person person = realm.createObject(Person.class); // person.setName("李東"); // person.setAge(24); // person.setCode(UUID.randomUUID().toString()); // } // });Person person = new Person();person.setName("李東1");person.setAge(28);person.setCode("6e56d3aa-7119-429e-8c59-7ad8241e838d");PersonDao dao = new PersonDaoImpl(this); // try { // dao.insert(person); // } catch (Exception e) { // e.printStackTrace(); // }try {dao.deletePerson("6e56d3aa-7119-429e-8c59-7ad8241e838d");} catch (Exception e) {e.printStackTrace();}try {List<Person> persons = dao.getAllPerson();Log.d(TAG, "onCreate: "+persons);} catch (Exception e) {e.printStackTrace();}}@Overrideprotected void onDestroy() {super.onDestroy();} }總結:Android中使用Realm數據庫基本上就這幾點步驟,這是個入門,更加復雜的操作,我在后面會慢慢的深入。
代碼地址
總結
以上是生活随笔為你收集整理的Android数据库新王者-Realm入门教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 理解 Cinder 架构 - 每天5分钟
- 下一篇: qt连接mysql