一、Room是什么?
Room是Jetpack组件中一个对象关系映射(ORM)库。可以很容易将 SQLite 表数据转换为 Java 对象。
Room 在 SQLite 上提供了一个抽象层,以便在充分利用 SQLite 的强大功能的同时,能够流畅地访问数据库。
支持与LiveData、RxJava、Kotlin协成组合使用。
Google 官方强烈推荐使用Room。
二、使用步骤
1.引入库
代码如下(示例):
plugins {
id 'com.android.application'
id 'kotlin-android'
//下面这两句不要忘记加不然会报错
id 'kotlin-kapt'
id 'kotlin-android-extensions'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.practice"
minSdkVersion 25
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//下面的库根据自己需求添加
def room_version = "2.3.0"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor "androidx.room:room-compiler:$room_version"
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$room_version")
// To use Kotlin Symbolic Processing (KSP)
kapt("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$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"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// optional - Test helpers
testImplementation("androidx.room:room-testing:$room_version")
}
[email protected] 数据库中表对应的实体
代码如下(示例):
package com.example.practice;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
/**
* @description:
* @author: 黄剑桥
* @email: [email protected]
* @date : 2021/8/12 11:45
*/
@Entity
public class Table {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "work")
private String work;
@ColumnInfo(name = "attendance")
private int attendance;
@ColumnInfo(name = "pay")
private int pay;
public Table(String name, String work, int attendance, int pay) {
this.name = name;
this.work = work;
this.attendance = attendance;
this.pay = pay;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWork() {
return work;
}
public void setWork(String work) {
this.work = work;
}
public int getAttendance() {
return attendance;
}
public void setAttendance(int attendance) {
this.attendance = attendance;
}
public int getPay() {
return pay;
}
public void setPay(int pay) {
this.pay = pay;
}
}
我以一个员工的工资单为例子。
3.Dao: 操作数据库的方法
package com.example.practice;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;
import java.util.List;
/**
* @author 黄剑桥
*/
@Dao //database access object
public interface WordDao {
//插入 参数Table代表上面自己创建的数据库中表对应的实体 参数中间三个 ... 代表可以加很多
@Insert
void insertWord(Table...tables);
//更新
@Update
void updateWord(Table...tables);
//删除指定的
@Delete
void deleteWord(Table...tables);
//删除所有
@Query("DELETE FROM `Table`")
void deleteAllWord();
//就是从名字叫做jdal的表里面选出所有信息,并且把选出来的信息按照id降序排列的顺序排列出来
@Query("SELECT * FROM `Table` ORDER BY ID DESC")
List<Table> getAllWords();
}
4. 创建Database
package com.example.practice;
import androidx.room.Database;
import androidx.room.RoomDatabase;
/**
* @author 黄剑桥
*/ //singleton
@Database(entities = {Table.class}, version = 1, exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
public abstract WordDao getWordDao();
}
5. 简单的操作
package com.example.practice;
import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
/**
* @author 黄剑桥
*/
public class MainActivity2 extends AppCompatActivity {
WordDatabase wordDatabase;
WordDao wordDao;
private TextView showTv;
private Button clearBtn;
private Button insertBtn;
private Button deleteBtn;
private Button updateBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//初始化
wordDatabase=Room.databaseBuilder(this,WordDatabase.class,"word")
//数据库操作比较耗时主要目的是熟悉数据库Room这句话代替了切换线程问题
.allowMainThreadQueries()
.build();
wordDao = wordDatabase.getWordDao();
showTv = (TextView)findViewById(R.id.textView2);
clearBtn = (Button)findViewById(R.id.button);
insertBtn = (Button)findViewById(R.id.button2);
deleteBtn = (Button)findViewById(R.id.button3);
updateBtn = (Button)findViewById(R.id.button5);
updateView();
event();
}
private void event() {
//插入
insertBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//传入对应数据
Table table = new Table("张三", "web工程师", 25, 30000);
wordDao.insertWord(table);
updateView();
}
});
//清除
clearBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//清除所有数据
wordDao.deleteAllWord();
updateView();
}
});
//修改
updateBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
修改第20条数据为
Table table = new Table("张三", "web工程师",1,20);
table.setId(20);
wordDao.updateWord(table);
updateView();
}
});
//删除指定
deleteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
删除第6条数据
Table table = new Table("张三", "web工程师",1,20);
table.setId(6);
wordDao.deleteWord(table);
updateView();
}
});
}
void updateView(){
List<Table> list = wordDao.getAllWords();
String text="";
for (int i=0;i<list.size();i++){
Table table = list.get(i);
//这种方式这是简单演示字符串拼接不建议这样搞 建议StringBuilder()
text +=table.getId()+":"+"姓名:"+table.getName()+"\t"+"职位:"+table.getWork()+"\t"+"出勤天数:"+table.getAttendance()+"\t"+"工资:"+table.getPay()+"\n";
}
showTv.setText(text);
}
}
总结
提示:这里对文章进行总结:
多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲、多敲