views:

338

answers:

4

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)?

+1  A: 

As far as I know there's now better way of referencing preference keys (aside from maybe used a static final String to store the string on the class).

The example given in the SDK docs does the same as what you've given in your example, http://developer.android.com/intl/fr/guide/topics/data/data-storage.html#pref.

Adrian
This is how I like to do it. This way when you create a new key, in the same file you created it in, theres a public static final String reference to it that's readily available to any class that might need to reference it.
Scienceprodigy
+2  A: 

Try getString(R.string.key_defined_in_xml).

molnarm
A: 

Even if you define a resoure in /res/values/string.xml to hold this key name you can not use that in the android:key="key_name". Also it doesn't make scene to define a final String in your class unless you would like all your keys defined in your class at the top of the file. So you will still have two places at least where you need to change it if you do. Most likely you shouldn't need to change a key.

ddcruver
+2  A: 

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_key".

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

pixel
This is the best way because it allows you to change the key in one place and it will propagate to both the settings page and anywhere you reference it in code.
Austyn Mahoney