JetPack之Room的学习
1.正题
2020年学习计划就是学习jetpack:lifecycle,room,viewModel,liveData
基本上就是这四个组件。今天学习room,结果在学习的时候就环境搭建这块,遇到种种不利,出师不利。让我深感 还不如用GreenDao。不过room能和LiveData搭配,所以在项目中假如用到viewModel+LiveData的时候,还是会选择用Room 而不是GreenDao。
2.正言
2.1 定义
Room 在 SQLite 上提供了一个抽象层,以便在充分利用 SQLite 的强大功能的同时,能够流畅地访问数据库。
2.2 集成到 android studio
dependencies {
def room_version = "2.2.3"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - RxJava support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
记录下 集成Room过程中的问题:
问题1:
Process: com.yunfan.jetpacktest1, PID: 4336
java.lang.RuntimeException: cannot find implementation for com.yunfan.jetpacktest1.room.UserRoomDatabase. UserRoomDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:94)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:952)
at com.yunfan.jetpacktest1.room.SingletonRoom.getInstance(SingletonRoom.java:24)
at com.yunfan.jetpacktest1.MainActivity$1.onClick(MainActivity.java:70)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
2020-05-03 15:19:54.709 1343-1343/? E/EGL_emulation: tid 1343: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
主要是没加入:annotationProcessor 依赖。导致make project 或者rebuild 无法自动生成java代码。于是提示这个问题
问题2:
错误: Not sure how to handle insert method's return type.
该错误指:Dao 里面执行sql 返回的参数错误。像添加操作,返回的是long,假如你写的是int 则就会报错。
问题3:
警告: Schema export directory is not provided to the annotation processor so we cannot
export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false.
添加schemalocation
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.yunfan.jetpacktest1"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// 指定room.schemaLocation生成的文件路径
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
2.3 组成
Room 有三个组件组成
- 数据库
- Entry:数据库的表
- Dao 访问数据库的方法
1.1 数据库的定义
//可以多个entry
@Database(entities = {UserInfo.class}, version = 1)
public abstract class UserRoomDatabase extends RoomDatabase {
public abstract MyDao getUserDao();
}
ps:每次更改数据库得更改version;改类的是抽象类,具体实现由注解去实现
之后再代码中初始化DataBase:
mUserRoomDatabase= Room.databaseBuilder(JetpackApplication.mJetpackApplication,
UserRoomDatabase.class, "database-name")
.allowMainThreadQueries()//允许在主线程/不加上会报错 要求在子线程中执行
.build();
UserRoomDataBase实例 new的成本比较高,应该以全局单例封装起来访问。默认是只能在子线程中执行sql操作。
2.1 定义表结构:
@Entry
@Entity(tableName = "user")
public class UserInfo {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "iphone")
public String userName;
@ColumnInfo(name = "pwd")
public String pwd;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
具体哪个注解 有哪些属性可以选择。需要查看注解源码
3.1 Dao
Dao 定义了访问数据库的方法,Dao本身是一个接口。在接口中定义了许多访问数据的方法,如 增,删,改
对应到的注解就是@Inset @Update @Delete 。每种注解对应着 单个插入/多个插入。
@Dao
public interface MyDao {
@Query("SELECT * FROM user")
List<UserInfo> getAll();
@Query("SELECT * FROM user WHERE iphone=:phone")
UserInfo getUserByIphone(String phone);
@Insert()
long insertData(UserInfo mUserInfo);
@Insert()
List<Long>insertDataAll(List<UserInfo>userInfos);
##2.4 加载已经存在的数据库
@Update
void updateAdd(UserInfo userInfo);
@Update
void updateList(List<UserInfo>userInfos);
@Query("delete from user where iphone=:userName")
void deleteUserInfor(String userName);
@Delete
void deleteByName(UserInfo userInfo);
}
@Query注解 代表的是 执行原生的sql语句,并不是指的是查询。