button click save sharedPreferences

304 views Asked by At

I am trying to implement a save button that saves shared preferences from several editText inputs.

I am trying to implement a button function that when pressed saves the values from multiple editTexts, into sharedPreference keys. After some research i have set what is in the editText fields as variables, which i will then write into shared preferences.

fun onClick() {

        var str = editText2.text.toString()
        var dex = editText.text.toString()
        var int = editText4.text.toString()

        when () {
            R.id.button -> {
                //add write sharedPreferences
            }
        }
}

I am getting an expecting an expression error when i try and compile it, in the when brackets.

1

There are 1 answers

8
P.Juni On

when needs an argument which will be compared to the cases like the case R.id.button.

So you can implement the onClickListener interface like

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //setSupportActionBar(findViewById(R.id.my_toolbar))

        button.setOnClikListener(this)

        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onClick(v: View?) {
        var str = editText2.text.toString()
        var dex = editText.text.toString()
        var int = editText4.text.toString()

        when (v.id) {
            R.id.button -> {
                //add write sharedPreferences
            }
        }
    }
}