0

I hope to set a value for var isBackgroundWindow, but private var isBackgroundWindow: Boolean by PreferenceTool(this@UIHome, getString(R.string.IsBackgroundName) , false) cause null error, why?

BTW, the Code 0 and Code 1 are wrong.

Code 0

   private lateinit  var isBackgroundWindow: Boolean

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_home)  

        isBackgroundWindow= PreferenceTool(this, getString(R.string.IsBackgroundName) , false)
    }

Code 1

private var isBackgroundWindow: Boolean by lazy {
        PreferenceTool<Boolean>(this@UIHome, getString(R.string.IsBackgroundName), false)
    }

Code A

class UIHome : AppCompatActivity() {
    private var isBackgroundWindow: Boolean by PreferenceTool(this@UIHome, getString(R.string.IsBackgroundName) , false)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_home)
        isBackgroundWindow=true
    }
}

Code B

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()
    }
}
HelloCW
  • 843
  • 22
  • 125
  • 310

0 Answers0