Reputation: 59
I'm trying to pass through variables from a child class to the parent's constructor.
The parent class' constructor consists of (Context!, String!, SQLiteDatabase.CursorFactory!, Int)
.
I can easily do
class TodoListDBHandler(context: Context, databaseName: String, factory: SQLiteDatabase.CursorFactory, databaseVersion: Int):
SQLiteOpenHelper(context, databaseName, factory, databaseVersion)
but I would like to specify the database name and version directly inside the class instead of specifying it every time I call the constructor as I might make mistakes.
My current code:
class TodoListDBHandler(context: Context, databaseName: String, factory: SQLiteDatabase.CursorFactory, databaseVersion: Int):
SQLiteOpenHelper(context, databaseName, factory, databaseVersion) {
val databaseFileName = "todoList.db"
val databaseVersion = 1
override fun onCreate(db: SQLiteDatabase?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
As stated above, I would like to be able to pass in the variable I have specified to the parent's constructor.
EDIT: This is the desired code, but in Java
public TodoListDBHandler(Context context, SQLiteDatabase.CursorFactory factory) {
// databaseFileName and databaseVersion are already specified inside the class
super(context, databaseFileName, factory, databaseVersion)
}
Upvotes: 2
Views: 2995
Reputation: 170723
@farhanjk gives a good solution, but you can also put them into the companion object:
class TodoListDBHandler(context: Context, factory: SQLiteDatabase.CursorFactory):
SQLiteOpenHelper(context, TodoListDBHandler.databaseName, factory, TodoListDBHandler.databaseVersion) {
companion object {
val databaseFileName = "todoList.db"
val databaseVersion = 1
}
...
}
This can be useful e.g. if there is non-trivial initialization or to create a list just once, etc.
Upvotes: 2
Reputation: 1762
You can pass the constant arguments directly in the super class constructor.
class TodoListDBHandler(context: Context, factory: SQLiteDatabase.CursorFactory)
: SQLiteOpenHelper(context, "todoList.db", factory, 1) {
override fun onCreate(db: SQLiteDatabase) {
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
}
Upvotes: 3