美文网首页
4.Android realm数据库

4.Android realm数据库

作者: 为梦想战斗 | 来源:发表于2017-10-15 18:39 被阅读0次

    1.在project的gradle里添加: classpath "io.realm:realm-gradle-plugin:3.0.0"
    2.在APP的gradle里添加: apply plugin: ‘realm-android’
    3.建立MyApplication,并在AndroidManifest.xml配置自定义的Application:

      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.新建一个类继承RealmObject:

    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";
        }
    }
    

    5.增删改查:

      /**
         * 增加
         */
        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);
        }
    
    }
    

    异步操作:

     @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();
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:4.Android realm数据库

          本文链接:https://www.haomeiwen.com/subject/vlbcuxtx.html