val prefs = getSharedPreferences("jcData", Context.MODE_PRIVATE) val name = prefs.getString("name", "") val married = prefs.getBoolean("married", false) val age = prefs.getInt("age", 0)
val name = edit_name.checkBlack("书名不能为空") ?: return val author = edit_author.checkBlack("作者不能为空") ?: return val pages = (edit_pages.checkBlack("页数不能为空") ?: return).toInt() val price = (edit_price.checkBlack("") ?: "99999").toFloat()
val db = dbHelper.writableDatabase val values = ContentValues().apply { put("name", name) put("author", author) put("pages", pages) put("price", price) } db.insert("Book", null, values)
fun EditText.checkBlack(message: String): String? { val text = this.text.toString() if (text.isBlank()) { if(message.isNotEmpty()) { showError(message) } returnnull } return text }
funfindAllBooks(): ArrayList<Book> { val booklist = ArrayList<Book>()
val query = "select * from Book" val db = this.writableDatabase val cursor = db.rawQuery(query, null)
if(cursor.moveToFirst()) { do { val id = cursor.getString(cursor.getColumnIndexOrThrow("id")).toInt() val name = cursor.getString(cursor.getColumnIndexOrThrow("name")) val author = cursor.getString(cursor.getColumnIndexOrThrow("author")) val pages = cursor.getInt(cursor.getColumnIndexOrThrow("pages")).toInt() val price = cursor.getDouble(cursor.getColumnIndexOrThrow("price")).toDouble() booklist.add(Book(id, name, author, pages, price)) } while(cursor.moveToNext()) } cursor.close() return booklist }
rawQuery 的第二个参数是用于为查询语句 query 填充数据
1 2 3 4 5 6 7 8 9 10 11 12
funfindBookByID(book_id: Int): Book {
val db = this.writableDatabase val query = "select * from Book where id=?" val cursor = db.rawQuery(query, arrayOf(book_id.toString())) cursor.moveToFirst() val name = cursor.getString(cursor.getColumnIndexOrThrow("name")) val author = cursor.getString(cursor.getColumnIndexOrThrow("author")) val pages = cursor.getInt(cursor.getColumnIndexOrThrow("pages")).toInt() val price = cursor.getDouble(cursor.getColumnIndexOrThrow("price")).toDouble() return Book(book_id, name, author, pages, price) }
Update - update/execSQL
可以使用封装好的 update 方法或直接使用 execSQL 方法执行原生的 SQL 语句
update 方法参数为: 表名, 要更新的键值封装, where 语句的约束信息, 占位符内容
1 2 3 4 5 6 7 8 9 10 11
funupdateBookById(book: Book) { val db = this.writableDatabase val values = ContentValues().apply { put("name", book.name) put("author", book.author) put("pages", book.pages) put("price", book.price) }