zoukankan      html  css  js  c++  java
  • xUTils框架的学习(二)

    这章讲的是框架的DbUtils模块的学习

    三 xUtils框架的DButils模块

      最开始接触这个框架就是从数据库模块开始的。当时的需求是需要记录用户的登录数据,保存在本地以便进行离线登录。首先想到的是用sharedpreference存储,但是后面说要支持多用户同设备登录,所以就想到了数据库保存信息。于是就用到了dbutils,当时由于项目比较紧就没过多研究,用了比较简洁的方法,在开始的时候用sqlite的可视化数据库操作工具创建了数据库直接放到asset文件夹下面的。至于如何在项目中直接创建数据库,后面部分会陆续提到。

      3.1 用sqlite expert profession3 软件创建数据库

      首先声明一下sqlite的数据存储类型和MySQL以及其他数据库的数据存储类型不一样,主要有null(空值)、INTERGER(有符号整数类型)、REAL(浮点数类型)、TEXT(字符串)、BLOB(二进制表示)。用sqliteExpert 创建表 user_info ,并在表里面增加column,把ID作为primaryKey,并设置为自增长。仔添加其他字段,数据库表创建完成后将数据库拷贝到工程的asset文件夹下。

    sqliteExpert工具的使用会在另外一篇文章里面讲解。详情见sqliteE软件使用(创建数据库和表) 

    3.2  在工程 下创建service 包,并在该包下创建DBService.class文件用来进行数据库的初始化。下面是DBService的代码。

     
    public class DbService {
        private Context context;
        private static DbService instance;
        /***
         * userInfoDbUtils:人员登录数据库(将用户登录信息保存在本地数据库)
         */
        private DbUtils userInfoUtils;
        public DbUtils getDbUtils() {
            if (dbUtils == null) {
                openBaseDb();
            }
            return dbUtils;
        }
        private DbService(Context context) {
            this.context = context;
        }
        public static DbService getInstance(Context context) {
            if (instance == null) {
                instance = new DbService(context);
            }
            return instance;
        }
        /**
         * @Method :初始化打开数据库
         */
        public void initAllDbs() {
    
            openUserInfoDB();
        }
        private void openUserInfoDB(){
            userInfoUtils = DbUtils.create(context,
                    Constants.getLocalDefaultPath(),
                    Constants.USER_INFO);
            userInfoUtils.configAllowTransaction(true);
            userInfoUtils.configDebug(true);
        }
        /**
         * @Method :关闭所有数据库
         */
        public void closeAllDbs() {     
            if(null != userInfoUtils){
                userInfoUtils.close();
            }
        }
        public DbUtils getUserInfoUtils() {
            if(null == userInfoUtils){
                openUserInfoDB();
            }
            return userInfoUtils;
        }
    }
     

      3.3 在工程下创建entity包 ,并在该包内创建UserEntity.class文件,与表的字段对应,下面是UserEntity的代码,可以看到表里的每一个字段都有
    一个属性与之对应。这样在用到DbUtils的时候才能将数据准确的与对象属性对应。这个对象类与普通的对象类不同的是就是在前面加了xutils框架里面的数据库的表注解@Table以及字段的注解@Column。

     
    @Table(name = "user_info")
    public class UserInfo {
        /***
         * id
         */
        @Column(column = "id")
        private int id;
        /***
         * 用户名
         */
        @Column(column = "USER_NAME")
        private String username;
        /***
         * 密码
         */
        @Column(column = "PASSWORD")
        private String password;
    
        /***
         * 查询范围(用json字串存起来,在读取的时候再进行对象转换)
         */
        @Column(column = "MODULE_QUERY")
        private String muduleList;
    
        public String getMuduleList() {
            return muduleList;
        }
        public void setMuduleList(String muduleList) {
            this.muduleList = muduleList;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    }
     

      3.4 在工程开始启动的时候就创建数据库,项目中是在启动的时候有一个开始动画,所以就在这个动画的页面里面进行了数据库的初始化。具体代码如下
      

     
    private static final String[] FILE_NAME_ASSETS = { "USER_INFO.db"};//由于考虑到会有其他的数据库要进行加载,所以就用一个字节数组保存
    private class SplashRunnable implements Runnable { @Override public void run() { String sdCardStatus =Environment.getExternalStorageState(); if (sdCardStatus.equals(Environment.MEDIA_MOUNTED)) { FileUtils.makeDirs(Constants.getLocalDefaultPath()); for (String fileName : FILE_NAME_ASSETS) { if (!FileUtils.isFileExist(Constants.getLocalDefaultPath() .concat("/").concat(fileName))) { appService.copyApkFromAssets(mContext,fileName, Constants.getLocalDefaultPath().concat("/") .concat(fileName)); } } startActivity(loginIntent); finish(); } } }
     

      在这里我起了一个线程去做这件事情,这个线程做的事情是先检测是否存在SD卡,如果存在就检测数据库文件是否存在,不存在的话就将数据库拷贝到指定的文件夹下面。然后再跳转到下一个页面。这就完成了数据库的初始化。注:appService是我在项目里面创建的一个服务类。
      下面是拷贝的方法

     
    public boolean copyApkFromAssets(Context context, String fileName,
                String path) {
            boolean copyIsFinish = false;
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = context.getAssets().open(fileName);
                File file = new File(path);
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                fos = new FileOutputStream(file);
                byte[] temp = new byte[1024];
                int i = 0;
                while ((i = is.read(temp)) > 0) {
                    fos.write(temp, 0, i);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                copyIsFinish = true;
            }
            return copyIsFinish;
        }
     

      3.5 接下来是在项目里面使用数据库里面的数据。
      首先创建一个LoginService类来操作数据库,比如数据的存储,数据的保存,删除。我在这个类里面只用到了数据的读取和保存。

     
    public class LoginService {
        private DbUtils dbUtils;
        private static  LoginService loginService;
        private Context mContext;
        private LoginService(Context context){
            this.mContext = context;
            dbUtils = DbService.getInstance(context).getUserInfoUtils();
        }
        public static LoginService getInstance(Context context){
            if(null == loginService)
                loginService = new LoginService(context);
                return loginService;
        }
    //根据用户名得到用户的信息
        public UserInfo getUserInfoByUserName(String userName){
            try{
                UserInfo userInfo = dbUtils.findFirst(Selector.from(UserInfo.class).where("USER_NAME","=",userName));
                if(null != userInfo){
                    return userInfo;
                }
            }catch (DbException e){
                e.printStackTrace();
            }
            return null;
        }
    //保存用户信息
        public void saveUserInfo(UserInfo userInfo){
            try {
                dbUtils.save(userInfo);
            }catch (DbException e){
                e.printStackTrace();
            }
        }
    }
     

    然后就是使用了

     
    UserInfo userInfo = new UserInfo();
                userInfo.setUsername(userName);
                userInfo.setPassword(password);
                //先检查数据库是否已经保存用户数据,如果没有再去进行数据插入
                UserInfo pUserInfo = LoginService.getInstance(mContext).getUserInfoByUserName(userName);
                if(null == pUserInfo){
                LoginService.getInstance(mContext).saveUserInfo(userInfo);
                }
     

    至此,DbUtils模块的使用就完成了,虽然有点繁琐,但是只要按照要求一步步去写完的话,后面的实现和使用还是很简单的。

    至于数据库的更新以及创建,后续会陆陆续续的补上的。

  • 相关阅读:
    微信 token ticket jsapi_ticket access_token 获取 getAccessToken get_jsapi_ticket方法
    PHP 日志 记录 函数 支持 数组 对象 新浪 sae 环境 去掉 空格 换行 格式化 输出 数组转字符串
    原生 原始 PHP连接MySQL 代码 参考mysqli pdo
    PHP 数字金额转换成中文大写金额的函数 数字转中文
    使用PHPMailer发送带附件并支持HTML内容的邮件
    设置输出编码格式 header 重定向 执行时间 set_time_limit 错误 报告 级别 error_reporting
    html5 bootstrap pannel table 协议 公告 声明 文书 模板
    指向指针的指针
    二级指针
    c语言:当指针成为参数后
  • 原文地址:https://www.cnblogs.com/android-blogs/p/5590740.html
Copyright © 2011-2022 走看看