欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Android room数据库使用详解

程序员文章站 2022-03-02 21:01:31
1、引入库 def room_version = "2.3.0" implementation "androidx.room:room-runtime:$room_version" //...

1、引入库

 def room_version = "2.3.0"
    implementation "androidx.room:room-runtime:$room_version"
    // for kotlin use kapt instead of annotationprocessor
    annotationprocessor "androidx.room:room-compiler:$room_version"
    // optional - rxjava2 support for room
    implementation "androidx.room:room-rxjava2:$room_version"
    // optional - rxjava3 support for room
    implementation "androidx.room:room-rxjava3:$room_version"

2.appdatabase类

@database(entities = {
        //用户信息
        userinfo.class
        }, version = 1, exportschema = false)
public abstract class appdatabase extends roomdatabase {
    private static appdatabase instance;
 
    public static synchronized appdatabase getinstance(context context) {
        if (instance == null) {
            instance = room.databasebuilder(context, appdatabase.class, 
                      //数据库存放在sd卡
                     fileutils.getdatabasepath("test.db"))
                    //.addmigrations(migration_1_2)
                    .build();
        }
        return instance;
    }
 
    public abstract roomdao roomdao();
 
    //进行数据库升级
    static final migration migration_1_2 = new migration(1, 2) {
        @override
        public void migrate(@nonnull supportsqlitedatabase database) {
            //在这里用sql脚本完成
            database.execsql("alter table user add column flag integer not null default 1");
        }
    };
}
public class fileutils {
 
    public static void deletefile(string filename) {
        file file = new file(filename);
        if (file.exists())
            file.delete();
    }
 
    /**
     * 获得数据库路径,如果不存在,则创建对象对象
     *
     * @param name
     */
    public static string getdatabasepath(string name) {
        //判断是否存在sd卡
        boolean sdexist = android.os.environment.media_mounted.equals(android.os.environment.getexternalstoragestate());
        if (!sdexist) {//如果不存在,
            log.e("sd卡管理:", "sd卡不存在,请加载sd卡");
            return null;
        } else {//如果存在
            //获取sd卡路径
            string dbdir = android.os.environment.getexternalstoragedirectory().getabsolutepath();
            dbdir += "/database";//数据库所在目录
            string dbpath = dbdir + "/" + name;//数据库路径
            logutil.d("dbpath:" + dbpath);
            return dbpath;
        }
    }
}

3.用户表

@entity(tablename = "user")
public class userinfo extends basebean {
    @nonnull
    @primarykey
    private string userid;
    private string name;//用户名
    private string headimg;
    private string pwd;
    private string createtime;
    @ignore
    private boolean isselect;
 
    public userinfo() {
    }
 
    @ignore
    public userinfo(string userid, string name, string headimg, string pwd) {
        this.userid = userid;
        this.name = name;
        this.headimg = headimg;
        this.pwd = pwd;
    }
 
 
    public string getuserid() {
        return userid;
    }
 
    public void setuserid(string userid) {
        this.userid = userid;
    }
 
    public string getname() {
        return name;
    }
 
    public void setname(string name) {
        this.name = name;
    }
 
 
    public string getheadimg() {
        return headimg;
    }
 
    public void setheadimg(string headimg) {
        this.headimg = headimg;
    }
 
    public string getpwd() {
        return pwd;
    }
 
    public void setpwd(string pwd) {
        this.pwd = pwd;
    }
 
    public boolean isselect() {
        return isselect;
    }
 
    public void setselect(boolean select) {
        isselect = select;
    }
 
    public string getcreatetime() {
        return createtime;
    }
 
    public void setcreatetime(string createtime) {
        this.createtime = createtime;
    }
}

4.roomdao

@dao
public interface roomdao {
    /**
     * 插入用户
     *
     * @param user
     */
    @insert
    void insertuser(userinfo user);
 
    //如果插入的新数据在表中已经存在,即如果遇上数据冲突的情况,新数据直接替换旧数据;
    @insert(onconflict = onconflictstrategy.replace)
    void insertuser(userinfo... user);
 
    @update
    void updateuser(userinfo note);
 
    /**
     * 获取所有的用户
     *
     * @return
     */
    @query("select * from user")
    livedata<list<userinfo>> getuserlist();
 
    /**
     * 根据用户名查询用户
     *
     * @param username
     * @return
     *
    @query("select * from user where name = :username limit 1")
    livedata<userinfo> finduserbyname(string username);
    /**
     * 根据userid查询用户
     */
    @query("select * from user where userid = :userid limit 1")
    livedata<userinfo> finduserbyid(string userid);
}

5.repository 

public class repository {
 
    private final appdatabase appdb;
 
    public repository(context context) {
        appdb = appdatabase.getinstance(context);
    }
 
    /**
     * 插入用户
     *
     * @param user
     */
    public void insertuser(final userinfo user) {
        new asynctask<void, void, void>() {
            @override
            protected void doinbackground(void... voids) {
                appdb.roomdao().insertuser(user);
                return null;
            }
        }.execute();
    }
 
    /**
     * 获取所有的用户信息
     *
     * @return
     */
    public livedata<list<userinfo>> getuserlist() {
        return appdb.roomdao().getuserlist();
    }
 
    /**
     * 根据用户名查询用户
     */
    public livedata<userinfo> finduserbyname(string name) {
        return appdb.roomdao().finduserbyname(name);
    }
 
    /**
     * 根据userid查询用户
     */
    public livedata<userinfo> finduserbyid(string userid) {
        return appdb.roomdao().finduserbyid(userid);
    }
}

6.使用

repository repository = new repository(context);
 
 repository.getuserlist().observe(this, new observer<list<userinfo>>() {
            @override
            public void onchanged(list<userinfo> userlist) {
                muserlist = userlist;
                logutil.d("muserlist个数:" + muserlist.size());
                if (muserlist.size() > 0) {
                    madapter.setlist(userlist);
                }
            }
        });

到此这篇关于android room数据库使用的文章就介绍到这了,更多相关android room数据库使用内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!