Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store Android preference keys?

When I create preference activity I define all preferences in xml file. Every preference has a key defined in this xml. But when I access preference I write:

SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this); boolean foo_value = appPreferences.getBoolean("foo_key_defined_in_xml", false); 

Is there any way to avoid referencing "foo_key_defined_in_xml" in hard-coded way? Maybe there is a possibility to reference it in R style way (not to refer to string)?

like image 306
pixel Avatar asked May 18 '10 12:05

pixel


People also ask

Where are SharedPreferences stored in Android?

Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.

Where can I find preference in Android Studio?

The preference option doesn't exist anymore. You will need to right click the res -> new -> Android resource file and choose the resource type as xml in the dropdown. Then you will manually need to add the layout for preference xml.

What are Android preferences?

Preferences in Android are used to keep track of application and user preferences. In any application, there are default preferences that can accessed through the PreferenceManager instance and its related method getDefaultSharedPreferences(Context)


2 Answers

I've found that it's possible to store keys in strings.xml and refer to them from preferences.xml just like all other values android:key="@string/preference_enable".

In code you can refer to key by typing getString(R.string.preference_enable)

You can mark the string to not be translated using a <xliff:g> tag. See Localization Checklist

<string name="preference_enable"><xliff:g id="preference_key">enable</xliff:g></string> 
like image 104
pixel Avatar answered Sep 20 '22 17:09

pixel


You could use a "keys.xml" files in "res/values", but should put something like this, this way you should dont have problem when you are using multiple languages:

    <resources     xmlns:tools="http://schemas.android.com/tools"     tools:ignore="MissingTranslation">      <string name="key1">key1</string>     <string name="key2">key2</string> ... </resources> 

Then you could reference it like a normal string in xml:

.... android:key="@string/key1" .... 

or in your java code for example:

SwitchPreference Pref1= (SwitchPreference) getPreferenceScreen().findPreference(getString(R.string.key1)); 
like image 34
Nico Pedraza Avatar answered Sep 21 '22 17:09

Nico Pedraza