这篇文章主要介绍了Android room数据库使用,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
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数据库使用内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:Android room数据库使用详解
基础教程推荐
猜你喜欢
- Flutter进阶之实现动画效果(三) 2022-10-28
- iOS开发 全机型适配解决方法 2023-01-14
- Android Compose自定义TextField实现自定义的输入框 2023-05-13
- IOS获取系统相册中照片的示例代码 2023-01-03
- iOS Crash常规跟踪方法及Bugly集成运用详细介绍 2023-01-18
- Android开发Compose集成高德地图实例 2023-06-15
- iOS中如何判断当前网络环境是2G/3G/4G/5G/WiFi 2023-06-18
- iOS开发使用XML解析网络数据 2022-11-12
- MVVMLight项目Model View结构及全局视图模型注入器 2023-05-07
- Android实现短信验证码输入框 2023-04-29