1

I'm new to android studio and I just can't figure out how to save the checkbox state using sharedpreference. If someone can help me I would greatly appreciate the assistance.

class SelectAlertSettings : AppCompatActivity() {

    private lateinit var mp : MediaPlayer

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


    }

    fun onCheckboxClicked(view: View) {
        if (view is CheckBox) {
            val checked: Boolean = view.isChecked

            when (view.id) {
                R.id.checkbox_proximity_alert -> {
                    if (checked) {

                        val proximityAlert = R.raw.proximity_alert
                        mp = MediaPlayer.create(this, proximityAlert)
                        mp.start()

                    } else {

                        mp.stop()
                    }

                }

            }

        }

        val btnCancel : Button = findViewById(R.id.btnDone)
        btnCancel.setOnClickListener{
            finish()
        }
    }
}
tomerpacific
  • 4,704
  • 13
  • 34
  • 52

2 Answers2

2

To save a value to shared preferences, you need to do the following things:

  1. Get a reference to the shared preferences object
  2. Create a SharedPreferences.Editor instance
  3. Choose the type you want to save in your shared preferences
  4. Save the changes using commit or apply

You can read more about it here.

val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
    with (sharedPref.edit()) {
        putBoolean("YOUR_CHECKBOX_KEY", checkboxState)
        apply()
    }
tomerpacific
  • 4,704
  • 13
  • 34
  • 52
1

To save the check box state as a boolean in shared preferences do the following:

1 - Get a handle to shared preferences:

val sharedPref = activity?.getSharedPreferences("preferences file key",Context.MODE_PRIVATE)

2 - Write to shared preferences:

sharedPref.edit().putBoolean("key", value).apply()

3 - Read from shared preferences:

val value = sharedPref.getBoolean("key", defaultValue)

Read the documentation to learn more.

I also I recommend using DataStore instead of SharedPreferences. DataStore uses Kotlin coroutines and Flow to store data and it's the recommended way to save key-value pairs.

ameencarpenter
  • 2,059
  • 1
  • 11
  • 20