练习郭神的第一行代码3的SQLite部分,存储数据为空,请帮忙看看哪里出问题了
main activity 中的代码:
lass MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbHelper=MyDatabaseHelper(this,"BookStore.db",2)
val createDatabase:Button=findViewById(R.id.createDatabase)
val addData:Button=findViewById(R.id.addData)
createDatabase.setOnClickListener {
dbHelper.writableDatabase
}
addData.setOnClickListener {
val db=dbHelper.writableDatabase
val values1=ContentValues().apply {
//开始准备第一条数据
put("name","The Da Vinci Code")
put("author","Dan Brown")
put("pages",454)
put("price",163)
}
db.insert("Book",null,values1)//插入第一条数据
val values2=ContentValues().apply {
//开始准备第二条数据
put("name","good father")
put("author","Claus")
put("pages",454)
put("price",1)
}
db.insert("Book",null,values2)//插入第二条数据
}
}
}
mydatabase类中的代码:
class MyDatabaseHelper(val context: Context,name:String,version: Int):
SQLiteOpenHelper (context,name,null,version){
private val createBook="create table Book("+
"id integer primary key autoincrement,"+
"author text,"+
"price real"+
"pages integer,"+
"name text)"
private val createCategory="create table Category("+
"id integer primary key autoincrement,"+
"category_name text,"+
"category_code integer)"
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(createBook)
db.execSQL(createCategory)
Toast.makeText(context,"Create succeeded",Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("drop table if exists Book")
db.execSQL("drop table if exists Category")
onCreate(db)
}
}
页面布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/createDatabase"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Create Database"/>
<Button
android:id="@+id/addData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add Data"/>
</LinearLayout>
运行后不报错,BOOK创建成功,用DB navigator 测试后,没有数据