I am trying to implement the integration of a Dialogflow (previously api.ai) agent with my Android app, using Kotlin. I checked other Q&A about kotlin lateinit
and the onCreate() lifecycle in Android is ideal for late-init implementations, to avoid writing dirty code with null objects and corresponding !!
and ?
accesses in Kotlin. But I am running into the error of 'Property getter or setter expected' when trying to lateinint
instances of self-defined class. Here is the code:
class AIApplication : Application() {
private var activitiesCount: Int = 0
var lateinit settingsManager: SettingsManager
//private set
private val isInForeground: Boolean
get() = activitiesCount > 0
override fun onCreate() {
super.onCreate()
settingsManager = SettingsManager(this)
}
Which gives me the error of 'Property getter or setter expected' on the lateinit settingsManager
line. Here is the SettingsManager
definition:
class SettingsManager(private val context: Context) {
private val prefs: SharedPreferences
private var useBluetooth: Boolean = false
var isUseBluetooth: Boolean
get() = useBluetooth
set(useBluetooth) {
this.useBluetooth = useBluetooth
prefs.edit().putBoolean(PREF_USE_BLUETOOTH, useBluetooth).commit()
val controller = (context.applicationContext as AIApplication).getBluetoothController()
if (useBluetooth) {
controller!!.start()
} else {
controller!!.stop()
}
}
init {
prefs = context.getSharedPreferences(SETTINGS_PREFS_NAME, Context.MODE_PRIVATE)
useBluetooth = prefs.getBoolean(PREF_USE_BLUETOOTH, true)
}
companion object {
private val SETTINGS_PREFS_NAME = "ai.api.APP_SETTINGS"
private val PREF_USE_BLUETOOTH = "USE_BLUETOOTH"
}
}
So what is the proper way to do this? Do I need to make some changes to the SettingsManager class? Please explain the whole concept clearly.
The lateinit declaration of the SettingsManager is wrong. Try this :
lateinit var settingsManager: SettingsManager
instead of
var lateinit settingsManager: SettingsManager
Hope this helps.