Getting the Value of a CheckBoxPreference

1.2k views Asked by At

I want to get the value from a CheckBoxPreference, I have defined it in Convert/res/xml/settings.xml, here is how it looks:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    <CheckBoxPreference 
        android:key="allow_internet"
        android:title="@string/internet_label"
        android:summaryOn="@string/internet_on"
        android:summaryOff="@string/internet_off"
        android:defaultValue="true" />
    <CheckBoxPreference 
        android:key="decimal_output"
        android:title="@string/decimal_title"
        android:summaryOn="@string/decimal_summary_on"
        android:summaryOff="@string/decimal_summary_off" />
</PreferenceScreen>

My question is how do I get the value of the CheckBoxPreference in my MainActivity.java file, because there is no android:id attribute for CheckBoxPreference, there is also a Settings.java file in my Convert/scr/.../Settings.java, it looks like:

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class Settings extends PreferenceActivity {

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}
2

There are 2 answers

1
Tina Roh On BEST ANSWER

CheckboxPreferences are stored in SharedPreferences. In your MainActivity, you can use:

PreferenceManager.setDefaultValues(this, R.xml.settings, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean allowInternet = sharedPreferences.getBoolean("allow_internet", true);
0
yonce On

I also get only TRUE when in settings.xmluse defaultValue=false.

I resolved use bool.xml. But it's good practice use https://developer.android.com/guide/topics/ui/settings instead PreferenceManager