Search code examples
androidandroid-studiokotlinanko

Location of code so that 'SharedPreferences' works with 'onOptionsItemSelected'


I've been trying to get these two to work but no matter how I rearrange the code, there is always something complaining: either a var that has not been initialized or a fun.

This are the offending snippet:

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

    var sp : SharedPreferences = this.getSharedPreferences("com.example.downloadtest",0 )

    fun storeUnits(unit:String){
        sp.edit().putString("units", unit).apply()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        super.onOptionsItemSelected(item)
        if (item.itemId == R.id.settings){
            //toast("Settings clicked")
            alert("Choose Units") {
                title = "Units"
                positiveButton("Imperial") {
                    toast("Imperial Measurements Chosen")
                    storeUnits("imperial")
                    
                }
                negativeButton("Metric") {
                    toast("Metric Measurements Chosen")
                    storeUnits("metric")
                    
                }

The var 'sp' needs to be where it's at (right?). The fun 'store units' is also placed ok. However, I cannot place the 'override fun onOptionsItemSelected' inside another override function; but if I place it outside it doesn't work with the other two. Please help..


Solution

  • Both onOptionsItemSelected method and your storeUnits method should be outside of the onCreate method. You can instead make sp a global variable:

    Declared this as a global variable before your onCreate method(inside the activity class but outside onCreate):

    lateinit var sp : SharedPreferences
    

    Then initialize it inside onCreate method:

    sp = this.getSharedPreferences("com.example.downloadtest",0 )