3
votes

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()
    }
}
1
what is context.defaultSharedPreferences ?? am getting exception heresasikumar
You should import org.jetbrains.anko.* for context.defaultSharedPreferencesHelloCW
ok.i will try with that ...sasikumar
check the edited answer .now app is not crashedsasikumar
do you get your NullPointerException on this line: context.defaultSharedPreferences within the lazy?Roland

1 Answers

2
votes

You can lateinit the variable isBackground like this way .Your UIHome class should be

 class UIHome : AppCompatActivity() {

 var isBackground: Boolean by Delegates.notNull<Boolean>()

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_uihome)
 isBackground = isBackgroundWindow()

}

fun isBackgroundWindow(): Boolean {
val isBackgroundWindow: Boolean by PreferenceTool(
    this, getString(R.string.IsBackgroundName), false
)
return isBackgroundWindow
}
}

This is avoid null pointer exception

isBackground?.let { 

  // your code
}