Android开发经验笔记安卓 完美收藏首页投稿(暂停使用,暂停投稿)

Android中数据持久化方案之一:javabean和Dao模式

2016-04-20  本文已影响1150人  陈利健

数据库是Android 数据持久化操作的解决方案之一。
以保存User信息为例,需要用到3个类:

JavaBean是最标准的POJO,里面有一个无参构造方法、纯粹的get/set方法、实现Serializable接口可序列化,没有业务逻辑。

即SQL语句操作

DAO提供了和数据库打交互的方法,这里通常写获取连接、关闭连接、增删改查的方法。

总结:


例子:

public class UserBean{
    private String name;
    private String pass;
    private String userID;
    private boolean infoCompleted;
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public String getPass(){
        return pass;
    }
    public void setPass(String pass){
        this.pass = pass;
    }
    public String getUserID(){
        return userID;
    }
    public void setUserID(String userID){
        this.userID = userID;
    }
    public boolean isInfoCompleted(){
        return infoCompleted;
    }
    public void setInfoCompleted(boolean infoCompleted){
        this.infoCompleted = infoCompleted;
    }   
}

public class UserDB extends SQLiteOpenHelper{
    private static final String DB_NAME = "test";
    private static final int version = 1;
    public String TABLE_NAME_USER = "users";
    private String CREATE_TABLE_USER = "create table if not exists "
            + TABLE_NAME_USER
            + "(_id integer primary key autoincrement," +
            "userid varchar(30),name varchar(30),pass varchar(30), is_complete int);";
    
    public UserDB(Context context) {
        super(context, DB_NAME, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREATE_TABLE_USER); 
    }
    
    @Override
    public void onOpen(SQLiteDatabase db){
        db.execSQL(CREATE_TABLE_USER);
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2){

    }
}

public class UserDBDao{

    private UserDB helper;

    public UserDBDao(Context context) {
        helper = new UserDB(context);
    }

    /**
     * 添加用户
     */
    public long add(UserBean user){
        if (isUserExist(user.getUserID())) { return -1; }
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("userid", user.getUserID());
        values.put("name", user.getName());
        values.put("pass", user.getPass());
        values.put("is_complete", user.isInfoCompleted()?1:0);
        long rowID = db.insert(helper.TABLE_NAME_USER, null, values);
        db.close();
        return rowID;
    }

    /**
     * 查询某个用户是否存在
     */
    public boolean isUserExist(String userid){
        boolean result = false;
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.query(helper.TABLE_NAME_USER, null, "userid=?",
                                    new String[] { userid }, null, null, null);
        if (cursor.moveToNext()){
            result = true;
        }
        cursor.close();
        db.close();
        return result;
    }

    /**
     * 查询某个用户
     */
    public UserBean getUser(String userid){
        if (!CommonUtil.isNotEmpty(userid)) { return null; }
        UserBean bean = new UserBean();
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query(helper.TABLE_NAME_USER, new String[] { "name", "pass", "is_complete" }, "userid=?", new String[] { userid }, null, null, null);
        if (cursor.moveToNext()){
            bean.setName(cursor.getString(0));
            bean.setPass(cursor.getString(1));
            bean.setInfoCompleted(cursor.getInt(2) == 0);
        }
        cursor.close();
        db.close();
        return bean;
    }

    /**
     * 返回所有的用户信息
     */
    public List<UserBean> findAllUser(){
        List<UserBean> allUsers = new ArrayList<UserBean>();
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.query(helper.TABLE_NAME_USER, new String[] { "userid", "name", "pass", "is_complete" }, null, null, null, null, null);
        while (cursor.moveToNext()){
            UserBean bean = new UserBean();
            bean.setUserID(cursor.getString(0));
            bean.setName(cursor.getString(1));
            bean.setPass(cursor.getString(2));
            bean.setInfoCompleted(cursor.getInt(3) == 0);
            allUsers.add(bean);
        }
        cursor.close();
        db.close();
        return allUsers;
    }

    /**
     * 删除一条用户的记录
     */
    public boolean delete(String userId){
        SQLiteDatabase db = helper.getWritableDatabase();
        int result = db.delete(helper.TABLE_NAME_USER, "userid=?", new String[] { userId });
        db.close();
        if (result > 0){
            return true;
        }
        else{
            return false;
        }
    }

    /**
     * 修改密码
     */
    public boolean updatePass(String userid, String pass){
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("pass", pass);
        int result = db.update(helper.TABLE_NAME_USER, values, "userid=?", new String[] { userid });
        db.close();
        if (result > 0){
            return true;
        }
        else{
            return false;
        }
    }
}

以上。
UserDBDao提供了对外操作数据的方法,外部只需要通过UserDBDao对象来对数据进行存取及其他操作即可。
如果你以前习惯用sharedpreferences来进行数据持久化操作的话,UserDBDao在某些方面也可以等价于其功能。
与sharedpreferences不同的是,sharedpreferences常用于轻量级的、单个类型的数据存取,而DBDao则更倾向于整张表结构数据的存取操作。

上一篇下一篇

猜你喜欢

热点阅读