I'm creating a content provider in Kotlin that uses a DB for store data and query them with a loaders, the problem is, that I need my DBHelper variable be reachable from any function: onCreate, query, update, etc... In java this is easy but in Kotlin the IDE tells me that I must initialize the val, I tried using init blocks but android studio says that the DBHelper must be initialized in onCreate()
So, How can I create a val in Kotlin that is reacheable for any function in the class and can be initialized in onCreate function like Java?
This is my code:
public class ProviderMMR : ContentProvider() {
var dbHelper
companion object Matcher{
var uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
init{
uriMatcher.addURI(MMDContract.columnas.AUTHORITY,MMDContract.columnas.TABLA_FARMACIA,1)
}
}
override fun onCreate(): Boolean {
dbHelper = mmrbd(context)
return true
}
override fun insert(uri: Uri?, values: ContentValues?): Uri {
val db = dbHelper.writableDatabase
val rowID = db.insert(MMDContract.columnas.TABLA_FARMACIA, null, values)
val uri_actividad = ContentUris.withAppendedId(MMDContract.columnas.CONTENT_BASE_URI, rowID)
return uri_actividad
}
override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun update(uri: Uri?, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getType(uri: Uri?): String {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
You can also use lazy delegate, which will create your dbHelper object on first access
val dbHelper by lazy { mmrbd(context) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With