Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a val in Kotlin without initialization that can be reached from any fun in the class?

Tags:

android

kotlin

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.
}

}

like image 748
Eduardo Corona Avatar asked Nov 30 '22 14:11

Eduardo Corona


1 Answers

You can also use lazy delegate, which will create your dbHelper object on first access

val dbHelper by lazy { mmrbd(context) }
like image 136
Pawel Avatar answered Dec 03 '22 04:12

Pawel