根据第一行代码,activity中对数据库的创建操作如下:
新建MyDatabaseHelper类继承自SQLiteOpenHelper。
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)"
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(createBook)
Toast.makeText(context, "Create succeeded", Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
}
布局中就一个android:id="@+id/createDatabase"的按钮
然后修改MainActivity中的代码如下
```kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbHelper = MyDatabaseHelper(this, "BookStore.db", 1)
createDatabase.setOnClickListener {
dbHelper.writableDatabase
}
}
}
以上是在activity中的操作,那么在fragment中该如何修改呢?
我还是和activity创建一样的SQLiteOpenHelper,布局也一样。那么问题来了,activity中是在onCreate()方法中构建了一个MyDatabaseHelper对象,那么在fragment中该如何操作?我创建了如下基于fragment的构建方法:
class RightFragRSC1 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.rightfrag_rsc1, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val rscdbHelper = DatabaseHelper(this, "RSC_DataBase.db", 1)//这里this出现报错
RSC1_Save.setOnClickListener {
rscdbHelper.writableDatabase
}
}
}
以上代码中构建对象的过程中出现了问题,在.onActivityCreated()后的rscdbHelper对象参数中的this出现了问题,报错内容如下,现在不知道该如何处理了?