Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of Android preference

How do you get the default value of an Android preference defined in XML? I don't want to repeat the definition of the default value in both the code and the preferences XML.

like image 516
hpique Avatar asked May 04 '10 17:05

hpique


People also ask

What is Android preference?

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)

How do I set custom preferences on Android?

It's still possible to customise the appearance of a Preference item though. In your XML you have to declare the root element as android:id="@android:id/widget_frame , and then declare TextView as android:title and android:summary . You can then declare other elements you want to appear in the layout.

What is Android shared preference?

A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. Each SharedPreferences file is managed by the framework and can be private or shared. This page shows you how to use the SharedPreferences APIs to store and retrieve simple values.

How do I turn off preferences on Android?

Programmatically: getPreferenceScreen(). findPreference("yourpref"). setEnabled(false);


2 Answers

You can define default value in resources (/values/bool.xml):

<resources>     <bool name="mypreference_default">true</bool> </resources> 

Use the value in the preferences.xml:

<CheckBoxPreference     android:defaultValue="@bool/mypreference_default"     android:key="mypreference"     android:title="@string/mypreference_title" /> 

Then use in code:

SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context); Boolean value = context.getResources().getBoolean(R.bool.mypreference_default); Boolean b = p.getBoolean("mypreference", value); 
like image 108
Paweł Nadolski Avatar answered Sep 22 '22 02:09

Paweł Nadolski


First you need to define default values in your preference XML file. Then you can populate preferences with default values in your main Activity by calling:

PreferenceManager.setDefaultValues(this, R.xml.preference, false); 

When you need to retrieve a some preference just call:

int value = prefs.getInt("key", null); 

Since your preferences are populated you won't get null value.

like image 40
pixel Avatar answered Sep 23 '22 02:09

pixel