I need to define a property isBackgroundWindow
by delegate class PreferenceTool
, but the following code will cause NullPointerException error.
I know that private val prefs: SharedPreferences by lazy { }
in PreferenceTool<T>
is lazy, so the object this is not initialized when system invoke PreferenceTool(this, getString(R.string.IsBackgroundName) , false),
it will cause null error.
I hope to use the code private lateinit var isBackgroundWindow: Boolean by PreferenceTool(this, getString(R.string.IsBackgroundName) , false)
, but
'lateinit' modifier is not allowed on delegated properties .
How can I do?
Main
class UIHome : AppCompatActivity() {
//I think the object this is not initialized, it will cause null error.
private var isBackgroundWindow: Boolean by PreferenceTool(this, getString(R.string.IsBackgroundName) , false)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_home)
isBackgroundWindow=false
}
}
Delegate Class
class PreferenceTool<T>(private val context: Context, private val name: String, private val default: T) {
private val prefs: SharedPreferences by lazy {
context.defaultSharedPreferences
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): T = findPreference(name, default)
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
putPreference(name, value)
}
@Suppress("UNCHECKED_CAST")
private fun findPreference(name: String, default: T): T = with(prefs) {
val res: Any = when (default) {
is Long -> getLong(name, default)
is String -> getString(name, default)
is Int -> getInt(name, default)
is Boolean -> getBoolean(name, default)
is Float -> getFloat(name, default)
else -> throw IllegalArgumentException("This type can be saved into Preferences")
}
res as T
}
@SuppressLint("CommitPrefEdits")
private fun putPreference(name: String, value: T) = with(prefs.edit()) {
when (value) {
is Long -> putLong(name, value)
is String -> putString(name, value)
is Int -> putInt(name, value)
is Boolean -> putBoolean(name, value)
is Float -> putFloat(name, value)
else -> throw IllegalArgumentException("This type can't be saved into Preferences")
}.apply()
}
}
import org.jetbrains.anko.*
for context.defaultSharedPreferences – HelloCWNullPointerException
on this line:context.defaultSharedPreferences
within thelazy
? – Roland