Room 增删改查,真香!,android 编程实战 pdf
fun updateBookPrice(name:String,id:Long){bookDao.updateBookPrice(name,id)}
//添加图书 fun insertBook(book: Book):Long{return bookDao.insertBook(book)}
//根据 id 删除 fun deleteBookById(id:Long):Int{return bookDao.deleteBookById(id)}
}
MainViewModel
class MainViewModel :ViewModel() {
//查询所有的 bookfun getAll():LiveData<List<Book>>{return Repository.loadAllBook()}}
MainActivity
这里要注意数据库操作是属于耗时的操作,Room 默认是不允许放在主线程中进行数据库操作,所以我们把对数据库增删改的操作放到了子线程中。
class MainActivity : AppCompatActivity() {private lateinit var binding:ActivityMainBindingprivate val list=ArrayList<Book>()private lateinit var adapter: BookAdapterprivate val mainViewModel by lazy {ViewModelProvider(this).get(MainViewModel::class.java)}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)
binding= ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)//初始化适配器 adapter=BookAdapter(R.layout.item_book,list)binding.rvBook.adapter=adapter
//viewModel+liveData 监听数据变化---数据库数据一旦发生变化 这里就会收到通知 mainViewModel.getAll().observe(this, Observer {list.clear()Log.d(TAG, "onCreate: ${it.size}")list.addAll(it)adapter.notifyDataSetChanged()})//注册点击事件 adapter.addChildClickViewIds(R.id.btnDelete,R.id.btnUpdate)
//item 子控件点击事件 adapter.setOnItemChildClickListener(object :OnItemChildClickListener{override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>,view: View,position: Int) {if(view.id==R.id.btnDelete){//删除按钮 thread {Repository.deleteBookById(list[position].id)}}else if(view.id==R.id.btnUpdate){//修改按钮 thread
{Repository.updateBookPrice("我被修改了!!",list[position].id)}}
}})
//添加 binding.btnAdd.setOnClickListener {val name = binding.edtBook.text.toString().trim()val price = binding.edtPrice.text.toString()if(name==""||price==""){Toast.makeText(this, "请填写完整", Toast.LENGTH_SHORT).show()}else{val book=Book(name,price.toInt())thread {val id=Repository.insertBook(book)Log.d(TAG, "onCreate: ${id}")}}
}}
companion object {private const val TAG = "MainActivity"}}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout 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"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context=".MainActivity">
<LinearLayoutandroid:id="@+id/ll_edt"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"
<EditTextandroid:id="@+id/edt_book"android:layout_width="wrap_content"android:layout_height="50dp"android:layout_weight="1"android:hint="输入名称"/><Viewandroid:layout_width="1dp"android:layout_height="match_parent"android:layout_marginLeft="20dp"android:layout_marginRight="20dp"android:background="#000000"/><EditTextandroid:id="@+id/edt_price"android:layout_width="wrap_content"android:layout_height="50dp"android:layout_weight="1"android:hint="输入价格"/><Buttonandroid:id="@+id/btn_add"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="添加"/></LinearLayout>
<androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/rv_book"android:layout_width="match_parent"android:layout_height="match_parent"app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
</LinearLayout>
BookAdapter
class BookAdapter(layoutId:Int,list:ArrayList<Book>):BaseQuickAdapter<Book,BaseViewHolder>(layoutId,list){override fun convert(holder: BaseViewHolder, item: Book) {holder.setText(R.id.tv_name,item.name.toString())holder.setText(R.id.tv_price,item.price.toString())}
}
item_book.xml
这里的 item 父布局我们用到了 SwipeMenuLayout,这里是使用一个支持侧滑的依赖库实现,前面添加依赖的操作已作说明。
<?xml version="1.0" encoding="utf-8"?><com.mcxtzhang.swipemenulib.SwipeMenuLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="60dp"android:layout_marginBottom="5dp"
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="59dp"><TextViewandroid:id="@+id/tv_name"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:gravity="center"android:text="活着"/><TextViewandroid:id="@+id/tv_price"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:gravity="center"android:text="12"/></LinearLayout><Viewandroid:layout_width="match_parent"android:layout_height="1dp"android:background="#d0d0d0"/></LinearLayout><Buttonandroid:id="@+id/btnUpdate"android:layout_width="60dp"android:layout_height="match_parent"android:background="#BEBEBE"android:text="修改"android:textColor="@android:color/white"/><Buttonandroid:id="@+id/btnDelete"android:layout_width="60dp"android:layout_height="match_parent"android:background="#ff0000"android:text="删除"android:textColor="@android:color/white"/>
</com.mcxtzhang.swipemenulib.SwipeMenuLayout>
评论