Realm的简单使用(单表_增删改查_包含异步操作)

来源:互联网 发布:常州口腔医院挂号软件 编辑:程序博客网 时间:2024/06/10 01:24

学习参考网址:

1.【Android】Realm详解 - 简书 http://www.jianshu.com/p/37af717761cc
2.Realm Java 原理介绍以及常见问题 - 作业部落 Cmd Markdown 编辑阅读器 https://www.zybuluo.com/pockry/note/453560
3.Realm For Android详细教程 - RaphetS - 博客园 http://www.cnblogs.com/RaphetS/p/5996265.html

具体操作根据Realm For Android详细教程 - RaphetS - 博客园 http://www.cnblogs.com/RaphetS/p/5996265.html上面写的来弄的,但发现帖子有些些地方代码不是很全,所以又自行添了一些。

具体代码:

由于互动的数据被我固定了,又为了防止因为数据是固定的而发生异常,所以写了些异常捕获,只要添上互动的数据,功能没有任何问题,就可以不用写这些异常捕获了。

前期准备:

1.在project的gradle里添加classpath “io.realm:realm-gradle-plugin:2.2.1”

buildscript {    repositories {        jcenter()    }    dependencies {        classpath 'com.android.tools.build:gradle:2.3.3'        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'        classpath "io.realm:realm-gradle-plugin:2.2.1"        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

2.在APP的gradle里添加apply plugin: ‘realm-android’

dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:26.+'    compile 'com.android.support.constraint:constraint-layout:1.0.2'    testCompile 'junit:junit:4.12'    compile 'com.jakewharton:butterknife:8.0.1'    apt 'com.jakewharton:butterknife-compiler:8.0.1'    apply plugin: 'realm-android'}

3.建立MyApplication:

public class MyApplication extends Application{    @Override    public void onCreate() {        super.onCreate();        Realm.init(this);        //默认配置//        RealmConfiguration config = new RealmConfiguration.Builder().build();        //自定义配置        RealmConfiguration config = new  RealmConfiguration.Builder()                .name("myRealm.realm")                .deleteRealmIfMigrationNeeded()                .build();        Realm.setDefaultConfiguration(config);    }}

4.修改配置文件:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.xxx.realmdemo">    <application        android:name=".MyApplication"       ...        <activity android:name=".HomeActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        ...    </application></manifest>

对象实体:

1.User:

/** * 创建实体 */public class User extends RealmObject {    @PrimaryKey    private String id;    private String name;    private String email;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }    public String toString() {        return "student:id="+ id +" name=" + name +"email=" + email + "\n";    }}

非异步操作:

1.home_activity的布局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center|top"    android:orientation="vertical"    tools:context="com.xxx.realmdemo.HomeActivity">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="right">        <TextView            android:id="@+id/tv_asy_function"            android:layout_marginTop="15dp"            android:layout_marginRight="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="异步操作" />    </LinearLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="15dp"        android:gravity="center"        android:orientation="horizontal">        <TextView            android:id="@+id/tv_custom_add"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="增" />        <TextView            android:id="@+id/tv_custom_delete"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="删" />        <TextView            android:id="@+id/tv_custom_update"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="改" />        <TextView            android:id="@+id/tv_custom_query"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="查" />    </LinearLayout>    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/tv_show_result"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"/>    </ScrollView></LinearLayout>

2.home_activity代码:

public class HomeActivity extends AppCompatActivity {    @BindView(R.id.tv_custom_add)    TextView tvCustomAdd;    @BindView(R.id.tv_custom_delete)    TextView tvCustomDelete;    @BindView(R.id.tv_custom_update)    TextView tvCustomUpdate;    @BindView(R.id.tv_custom_query)    TextView tvCustomQuery;    @BindView(R.id.tv_show_result)    TextView tvShowResult;    @BindView(R.id.tv_asy_function)    TextView tvAsyFunction;    private int number = 1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_home);        ButterKnife.bind(this);    }    @OnClick({R.id.tv_custom_add, R.id.tv_custom_delete, R.id.tv_custom_update, R.id.tv_custom_query, R.id.tv_asy_function})    public void onViewClicked(View view) {        switch (view.getId()) {            case R.id.tv_custom_add:                addObject();                break;            case R.id.tv_custom_delete:                deleteObject();                break;            case R.id.tv_custom_update:                updateObject();                break;            case R.id.tv_custom_query:                queryAllObject();                break;            case R.id.tv_asy_function:                Intent intent = new Intent( HomeActivity.this,ActAsyFunction.class);                startActivity( intent);                break;        }    }    /**     * 增加     */    public void addObject() {//        //实现方法一:事务操作//        //类型一 :新建一个对象,并进行存储//        Realm realm=Realm.getDefaultInstance();//        realm.beginTransaction();//        User user = realm.createObject(User.class); // Create a new object//        user.setName("John");//        user.setEmail("john@corporation.com");//        realm.commitTransaction();//        //类型二:复制一个对象到Realm数据库//        Realm realm=Realm.getDefaultInstance();//        User user = new User("John");//        user.setEmail("john@corporation.com");//        realm.beginTransaction();//        realm.copyToRealm(user);//        realm.commitTransaction();        //实现方法二:使用事务块        Realm mRealm = Realm.getDefaultInstance();        final User user = new User();        user.setEmail("john" + number + "@corporation.com");        user.setId(String.valueOf(number));        user.setName("John" + number);        try{            mRealm.executeTransaction(new Realm.Transaction() {                @Override                public void execute(Realm realm) {                    realm.copyToRealm(user);                    tvShowResult.setText(" 增加成功:" + user.toString());                }            });        }catch (Exception e){            number++;            e.printStackTrace();            tvShowResult.setText(" 增加失败");        }    }    /**     * 删除     * 同样也可以使用同addObject函数的beginTransaction和commitTransaction方法进行删除     */    public void deleteObject() {        final int positon = 1;        Realm mRealm = Realm.getDefaultInstance();        final RealmResults<User> users = mRealm.where(User.class).findAll();        try {            mRealm.executeTransaction(new Realm.Transaction() {                @Override                public void execute(Realm realm) {                    if (users.size() > 0) {                        User user = users.get(positon);                        String str = user.toString();                        user.deleteFromRealm();                        tvShowResult.setText("删除成功\n" + str);//                    //删除第一个数据//                    users.deleteFirstFromRealm();//                    //删除最后一个数据//                    users.deleteLastFromRealm();//                    //删除位置为1的数据//                    users.deleteFromRealm(1);//                    //删除所有数据//                    users.deleteAllFromRealm();                    } else {                        tvShowResult.setText("user表里无数据");                    }                }            });        }catch (Exception e){            e.printStackTrace();            tvShowResult.setText("删除失败");        }    }    /**     * 修改     */    public void updateObject() {       try{           String id = "1";           String newName = "玫玫";           Realm mRealm = Realm.getDefaultInstance();           User user = mRealm.where(User.class).equalTo("id", id).findFirst();           mRealm.beginTransaction();           user.setName(newName);           mRealm.commitTransaction();           tvShowResult.setText("更新\n" + user.toString());       }catch (Exception e){           e.printStackTrace();           tvShowResult.setText(" 更新失败");       }    }    /**     * 查询所有数据     */    public void queryAllObject() {        Realm mRealm = Realm.getDefaultInstance();        RealmResults<User> users = mRealm.where(User.class).findAll();        /**         * 对查询结果,按Id进行排序,只能对查询结果进行排序         *///        //增序排列//        users=users.sort("id");        //降序排列        users = users.sort("id", Sort.DESCENDING);        String str = "";        for (int i = 0; i < users.size(); i++) {            User user = users.get( i);            str = str + user.toString();        }        tvShowResult.setText("查询所有数据:\n" + str);    }}

异步操作

1.布局:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginTop="15dp"        android:gravity="center"        android:orientation="horizontal">        <TextView            android:id="@+id/tv_asy_add"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="异步增" />        <TextView            android:id="@+id/tv_asy_delete"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="异步删" />        <TextView            android:id="@+id/tv_asy_update"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="异步改" />        <TextView            android:id="@+id/tv_asy_query"            android:layout_marginLeft="15dp"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"            android:text="异步查" />    </LinearLayout>    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/tv_show_result"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:textSize="21sp"/>    </ScrollView></LinearLayout>

2.acitivty代码:

public class ActAsyFunction extends AppCompatActivity {    @BindView(R.id.tv_asy_add)    TextView tvAsyAdd;    @BindView(R.id.tv_asy_delete)    TextView tvAsyDelete;    @BindView(R.id.tv_asy_update)    TextView tvAsyUpdate;    @BindView(R.id.tv_asy_query)    TextView tvAsyQuery;    @BindView(R.id.tv_show_result)    TextView tvShowResult;    private RealmAsyncTask addTask;    private RealmAsyncTask  deleteTask;    private RealmAsyncTask  updateTask;    private RealmResults<User> users;    private int number = 1;    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_act_asyfunction);        ButterKnife.bind(this);    }    @OnClick({R.id.tv_asy_add, R.id.tv_asy_delete, R.id.tv_asy_update, R.id.tv_asy_query})    public void onViewClicked(View view) {        switch (view.getId()) {            case R.id.tv_asy_add:                User user = new User();                user.setEmail("john" + number + "@corporation.com");                user.setId(String.valueOf(number));                user.setName("John" + number);                addUser( user );                number++;                break;            case R.id.tv_asy_delete:                String id = "1";                deleteUser( id);                break;            case R.id.tv_asy_update:                String Id = "2";                String name = "玫玫";                updateUser( name,Id  );                break;            case R.id.tv_asy_query:                queryUser();                break;        }    }    /**     * 增加     * @param user     */    private void addUser(final User user) {        Realm mRealm = Realm.getDefaultInstance();        addTask=  mRealm.executeTransactionAsync(new Realm.Transaction() {            @Override            public void execute(Realm realm) {                realm.copyToRealm(user);            }        }, new Realm.Transaction.OnSuccess() {            @Override            public void onSuccess() {                tvShowResult.setText( "增加成功" + user.toString());            }        }, new Realm.Transaction.OnError() {            @Override            public void onError(Throwable error) {                tvShowResult.setText( "增加失败");            }        });    }    /**     * 删除     * @param id     */    private void deleteUser(final String id){        Realm mRealm = Realm.getDefaultInstance();        final String[] str = {""};        deleteTask=   mRealm.executeTransactionAsync(new Realm.Transaction() {            @Override            public void execute(Realm realm) {                User user=realm.where(User.class).equalTo("id",id).findFirst();                str[0] = user.toString();                user.deleteFromRealm();            }        }, new Realm.Transaction.OnSuccess() {            @Override            public void onSuccess() {                tvShowResult.setText( "删除成功" + str[0] );            }        }, new Realm.Transaction.OnError() {            @Override            public void onError(Throwable error) {                tvShowResult.setText( "删除失败" + str[0] );            }        });    }    /**     * 修改     * @param name     * @param id     */    private void updateUser(final String name, final String id){        Realm mRealm = Realm.getDefaultInstance();        final String[] oldStr = {""};        final String[] newStr = {""};        updateTask = mRealm.executeTransactionAsync(new Realm.Transaction() {            @Override            public void execute(Realm realm) {                User user=realm.where(User.class).equalTo("id",id).findFirst();                oldStr[0] = user.toString();                user.setName(name);                newStr[0] = user.toString();            }        }, new Realm.Transaction.OnSuccess() {            @Override            public void onSuccess() {                tvShowResult.setText( "旧信息:" + oldStr[0] + "\n修改成功\n" + newStr[0]);            }        }, new Realm.Transaction.OnError() {            @Override            public void onError(Throwable error) {                tvShowResult.setText( "旧信息:" + oldStr[0] + "\n修改失败");            }        });    }    /**     * 查询所有数据     */    private void queryUser(){        final Realm mRealm = Realm.getDefaultInstance();        users = mRealm.where(User.class).findAllAsync();        users.addChangeListener(new RealmChangeListener<RealmResults<User>>() {            @Override            public void onChange(RealmResults<User> element) {                element= element.sort("id");                List<User> datas=mRealm.copyFromRealm(element);                String str = "";                for (int i = 0; i <datas.size(); i++) {                    User user = datas.get( i);                    str = str + user.toString();                }                tvShowResult.setText("查询所有数据:\n" + str);            }        });    }    @Override    protected void onDestroy() {        super.onDestroy();        if (addTask != null && !addTask.isCancelled()){            addTask.cancel();        }        if (deleteTask != null && !deleteTask.isCancelled()){            deleteTask.cancel();        }        if (updateTask != null && !updateTask.isCancelled()){            updateTask.cancel();        }        if( users != null){            users.removeChangeListeners();        }    }}
阅读全文
0 0