pi_hobbyist
pi_hobbyist

Reputation: 11

How to save a Checkbox state in android studio?

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()
        }
    }
}

Upvotes: 1

Views: 539

Answers (2)

ameencarpenter
ameencarpenter

Reputation: 2579

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.

Upvotes: 1

tomerpacific
tomerpacific

Reputation: 6475

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()
    }

Upvotes: 2

Related Questions