导入依赖:
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation 'androidx.recyclerview:recyclerview:1.2.1'
/**
* entities 数据库里存入的表,可是多个
* version 数据库的版本号
* exportSchema 是否生成json文件,用于查看数据库的结构
*/
@Database(entities = [User::class],version = 1,exportSchema = false)
abstract class AppDataBase : RoomDatabase() {
abstract fun UserDao():UserDao //Dao 对象
companion object{
private var instance:AppDataBase?=null
fun getInstance(context:Context):AppDataBase{
//对象锁
return instance?: synchronized(this) {
//上下文 数据库名字
Room.databaseBuilder(context,AppDataBase::class.java,"user_db")
.build().also { instance=it }
}
}
}
}
数据库dataBase文件
@Dao //Dao 类声明
interface UserDao {
//这里设置了一下冲突, 如果两条记录相同则会替换
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: User)
//这里不需要挂起(返回flow或livedata都不需要)
@Query("SELECT * FROM user")
fun getAll(): Flow<List<User>>
}
数据库Dao类
//Room实体类声明
@Entity
data class User(
//主键
@PrimaryKey val uid:Int,
//数据库里存入的字段名
@ColumnInfo(name = "first_name")val firstName:String,
//数据库里存入的字段名
@ColumnInfo(name = "last_name") val lastName :String
)
数据库实体类
class UserViewModel(app: Application) :AndroidViewModel(app) {
fun insert(uid:String,firstName:String,lastName:String){
//协程
viewModelScope.launch {
AppDataBase.getInstance(getApplication()).UserDao()
//插入数据
.insert(User(uid.toInt(),firstName,lastName))
Log.d("ning","insert user:$uid")
}
}
fun getAll(): Flow<List<User>>{
return AppDataBase.getInstance(getApplication())
.UserDao().getAll().catch {
e-> //上游有异常,在保证不打破flow涉及原则的情况下推荐使用catch函数
e.printStackTrace()
}.flowOn(Dispatchers.IO)//切换线程
}
}
class BindingViewHolder (val binding:ViewBinding):RecyclerView.ViewHolder(binding.root){
}
封装的ViewHolder
class UserAdapter(private val context: Context) : RecyclerView.Adapter<BindingViewHolder>() {
private val data=ArrayList<User>()
fun setData(data:List<User>){
this.data.clear();
this.data.addAll(data)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BindingViewHolder {
val inflate = ItemUserBinding.inflate(LayoutInflater.from(context), parent, false)
return BindingViewHolder(inflate)
}
override fun onBindViewHolder(holder: BindingViewHolder, position: Int) {
val item=data[position]
val itemUserBinding = holder.binding as ItemUserBinding
itemUserBinding.text.text="${item.uid},${item.firstName},${item.lastName}"
}
override fun getItemCount(): Int {
return data?.size
}
}
class UserFragment :Fragment() {
//这里直接创建了个对象
private val viewModel by viewModels<UserViewModel> ()
private val mBinding: FragmentUserBinding by lazy {
FragmentUserBinding.inflate(layoutInflater)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return mBinding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mBinding.apply {
btnAddUser.setOnClickListener {
viewModel.insert(
etUserId.text.toString(),
etFirstName.text.toString(),
etLastName.text.toString()
)
}
}
context?.also {
val adapter=UserAdapter(it)
mBinding.recyclerView.adapter=adapter
//协程
lifecycleScope.launchWhenCreated {
//flow取出
viewModel.getAll().collect {
value ->
adapter.setData(value)
}
}
}
}
}
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".fragment.UserFragment"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dip">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/et_user_id"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="USER ID" />
<EditText
android:id="@+id/et_first_name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="FIRST NAME" />
<EditText
android:id="@+id/et_last_name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="LAST NAME" />
</LinearLayout>
<Button
android:id="@+id/btn_add_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ADD USER" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</LinearLayout>
</layout>
这个是主XML文件
效果展示:
?
|