第一个完整项目有感而发
1.一些奇淫巧技的记录
1.assets里预置数据库
把预装好数据的db文件放在assets文件夹里,然后写到/data/data/packagename/databases
里就能实现预装数据库
关键代码如下:
1 2 3
| val dbHelper = MyDatabaseHelper(this,"LearningData.db",1)
dbHelper.copyFileFromAssets(MyApplication.context,"LearningData.db","/data/data/com.lnm011223.learning_companion/databases","LearningData.db")
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| fun copyFileFromAssets( context: Context, assetName: String, savePath: String, saveName: String ) {
val filename = savePath + "/" + saveName val file = File(filename) if (!file.exists()) { try { val inStream: InputStream = context.assets.open(assetName) val fileOutputStream = FileOutputStream(filename) var byteread: Int val buffer = ByteArray(1024) while (inStream.read(buffer).also { byteread = it } != -1) { fileOutputStream.write(buffer, 0, byteread) } fileOutputStream.flush() inStream.close() fileOutputStream.close() } catch (e: IOException) { e.printStackTrace() } Log.d("FileUtils", "[copyFileFromAssets] copy asset file: $assetName to : $filename") Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show() } else { Log.d("FileUtils", "[copyFileFromAssets] file is exist: $filename") } }
|
2.数据库数据填充
可以用Excel填充数据然后导入进db文件的表里
3.广播用法
可以通过触发发送一个自定义广播,然后再接收这个广播,从而达到recycleview里的操作可以通知到fragment
关键代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| viewHolder.deleteerror_btn.setOnClickListener { val position = viewHolder.adapterPosition val errorBookQuestion = errorlist[position] AlertDialog.Builder(parent.context).apply { setTitle("确认:") setMessage("真的要删除这条记录吗?") setNegativeButton("否") { _, _ ->
} setPositiveButton("是") { _, _ -> db.delete("ErrorBook", "title = ?", arrayOf(errorBookQuestion.title)) val intent = Intent("ErrorBookDataChange")
context.sendBroadcast(intent)
}
show() } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| override fun onResume() { super.onResume() Log.d("aaa","resume") val intentFilter = IntentFilter() intentFilter.addAction("ErrorBookDataChange") receiver = ErrorBookChangeReceiver() activity?.registerReceiver(receiver,intentFilter) }
override fun onPause() { super.onPause() Log.d("aaa","pause") activity?.unregisterReceiver(receiver)
} inner class ErrorBookChangeReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { initErrorBookList() val layoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) errorbook_recycleview.layoutManager = layoutManager val adapter = ErrorBookAdapter(errorbooklist) errorbook_recycleview.adapter = adapter } }
|
2.一些感悟
先展示一下一些数据: