Updating Checkbox value in Preference Screen upon changing the value in SharedPreferences in Android

StackOverflow https://stackoverflow.com/questions/8384385

Pergunta


I have an app which uses the user's location. I have a dialog(pic below) asking user's permission to "Allow" or "Disallow" the app to use the user's location ( dialog pops up the first time users opens the app after installation OR when user tries to use the location based service while using user location is "Disallow"-ed by the user).
dialog

I also use preference item(a checkbox)(pic below) in PreferenceActivity where the user can the toggle his preference.
prefs item

To change the value of the sharedpreference I have use this code

    public void onClick(DialogInterface dialog, int id)
    {
        sharedPrefs =getSharedPreferences("prefs",MODE_WORLD_WRITEABLE);
        Editor editor = sharedPrefs.edit();
        editor.putBoolean("locationPermission", true);
        editor.commit();
}

I had expected the checkbox value to change automatically depending on the dialog selection as the key "locationPermission" holds the value to the checkbox. But it is not so.

Now how do I map the dialog(pic 1) selection to the checkbox value(pic 2)?

Foi útil?

Solução

The issue was solved by using

sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

instead of

sharedPrefs = getSharedPreferences("prefs", MODE_WORLD_WRITEABLE);

Outras dicas

You can call addPreferencesFromResource in the onCreate of your PreferenceActivity so that your UI is populated from the preferences. Also, you may want to make sure that your CheckBoxPreference has android:persistent-"true" in its XML definition.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top