Room数据库是Google的JitPack组件中的一个,推出已经有一段时间了,现在的使用者也越来越多,Room是一个轻量级的ORM(Object Relational Mapping:对象关系映射)数据库。
添加依赖
implementation "androidx.room:room-runtime:2.4.0-alpha03"
annotationProcessor "androidx.room:room-compiler:2.4.0-alpha03"
啥也不说了,先上效果图,这里做了一个添加和删除记事本的功能:
各种注解含义:
@Entity(tableName = "tb_name")
表示根据该类创建名为tb_note的表@ColumnInfo(name = "title")
表示在表中创建名为title的字段@PrimaryKey(autoGenerate = true)
数据库自增长id
Room通过注解的方式来建立起与数据库的映射关系。
这里创建NoteBean:
@Entity(tableName = "notes")
public class NoteBean {
@PrimaryKey(autoGenerate = true)
@NonNull
public int id;
@ColumnInfo(name = "title")
public String title;
@ColumnInfo(name = "content")
public String content;
public NoteBean(String title, String content) {
this.title = title;
this.content = content;
}
}
创建增删查改的Dao类:
@Dao
public interface NoteDao {
@Insert()
void insertData(NoteBean noteBean);
@Query("SELECT * FROM notes")
List<NoteBean> queryAll();
@Query("DELETE FROM notes")
void clearAll();
}
创建对应的RoomDatabase:
@Database(entities = {NoteBean.class}, version = 1, exportSchema = false)
public abstract class NoteDataBase extends RoomDatabase {
public abstract NoteDao noteDao();
}
NoteDbManager管理类:
object NoteDbManager {
var noteDb: NoteDataBase? = null
fun initDb(context: Context) {
Thread {
initNoteDB(context)
}.start()
}
/**
* 初始化数据库
*/
private fun initNoteDB(context: Context) {
//本地持久化数据库
noteDb = Room.databaseBuilder(
context,
NoteDataBase::class.java,
"note.db"
) //是否允许在主线程上操作数据库,默认false。
.allowMainThreadQueries() //数据库创建和打开的事件会回调到这里,可以再次操作数据库
.addCallback(object: RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
}
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
}
})
.build()
}
fun queryAll(): List<NoteBean>? {
return noteDb?.noteDao()?.queryAll()
}
fun clearData() {
noteDb?.noteDao()?.clearAll()
}
}
MainActivity代码:
class MainActivity : AppCompatActivity() {
private var ivAdd: ImageView? = null
private var recyclerView: RecyclerView?= null
private var adapter: NoteAdapter?= null
private var tvNoData: TextView?= null
private var tvClear: TextView?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ivAdd = findViewById(R.id.iv_add)
recyclerView = findViewById(R.id.recyclerview)
tvNoData = findViewById(R.id.tv_no_data)
tvClear = findViewById(R.id.tv_clear)
ivAdd?.setOnClickListener {
startActivity(Intent(this, CreateNoteActivity::class.java))
}
tvClear?.setOnClickListener {
NoteDbManager.clearData()
refreshList()
}
NoteDbManager.initDb(applicationContext)
adapter = NoteAdapter(applicationContext)
recyclerView?.adapter = adapter
}
override fun onResume() {
super.onResume()
refreshList()
}
/**
* 刷新列表数据
*/
private fun refreshList() {
val datas = NoteDbManager.queryAll()
if (datas != null) {
adapter?.setDatas(datas as ArrayList<NoteBean>)
tvNoData?.visibility = if (datas.isNotEmpty()) View.GONE else View.VISIBLE
} else {
adapter?.clearDatas()
tvNoData?.visibility = View.VISIBLE
}
}
}
然后,其余就是调用数据库操作的事件以及列表展示。