ListPreference only returns Default Value - android

I have setup ability for a user to specify some settings using the in-built preference system. My preference.xml is simple, with only a ListPreference:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android" android:persistent="true">
<PreferenceCategory android:title="Your nuSTOCK Settings" android:persistent="true">
<ListPreference android:key="operation_section" android:entries="#array/array_nustock_section_values" android:summary="What's your operational section in nuSTOCK?" android:entryValues="#array/array_nustock_section_keys" android:title="Operation Section" android:negativeButtonText="Cancel" android:positiveButtonText="OK" android:persistent="true" android:enabled="true"/>
</PreferenceCategory>
</PreferenceScreen>
That references my Arrays, which are:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="array_nustock_section_keys">
<item>store</item>
<item>branch</item>
</string-array>
<string-array name="array_nustock_section_values">
<item>Store</item>
<item>Branch</item>
</string-array>
</resources>
And then I load it (the Preference Module) into my Activity Like this:
nustock_preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
After which I then prompt the user to set the values (select from only two options), by invoking the preference activity via an Intent:
Intent settingsActivity = new Intent(this,
MyPreferenceActivity.class);
startActivity(settingsActivity);
The Preference Activity is like so:
public class MyPreferenceActivity extends PreferenceActivity {
private static final String PREF_FILENAME = "nustock_preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(PREF_FILENAME);
addPreferencesFromResource(R.xml.preferences);
}
}
And I then try to read the preference value set by the user like this:
nustock_preferences = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String op = nustock_preferences.getString(PREF_OPERATION_SECTION,"none");
Log.d(Tag,String.format("Operation Section : %s", op));
PROBLEM:
No matter what value of the preference I select, only value I get is the default "none" (which I've actually added as different from the actual values in the list, just to highlight the problem -- selected value never gets returned!).
So, What Am I doing wrong? I've tried many variations of this approach, but I can't get the user's selected preference! Even tried restarting the app (hoping that the preferences get set at start-up, nothing!)
But, interestingly, whenever I load the preference screen, the correct value is still selected under the ListPreference dialog!

I believe you specify a particular preference file name with getPreferenceManager().setSharedPreferencesName(PREF_FILENAME);
but later you are trying to get preference value from default preferences .getDefaultSharedPreferences(getBaseContext());
It's like writing data to table PERSON, but later trying to find it in the table DEFAULT
Either remove the setting for preference file name, or get your value from the preference file you specified

Related

What is the name of SharedPreferences file name?

I am new to Android and I am kind of stuck for 6 hours straight.
The problem is I don't know the name of the preferences file, and I need to get values from preferences file. I am using Android Studio and created a "Settings Activity". All the way I had not given name to any file except SettingsActivity.java.
So my question is what is the name of the Shared Preferences file (cause the application is keeping the values). Or otherwise if there is a way to find out.
Or perhaps I am missing something obvious in code. Following is my relevant code.
String key = "example_text";
final String PREF_FILE_NAME = "SettingsActivity";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
String value = preferences.getString(key, " null");
EDIT 1: I have an activity named RemoteDevice.java, within this activity I have a Async Task subclass for internet usage. Now I have stored IP address through the above mentioned PreferencesActivity and now want to retrieve it. But am unable to find it.
EDIT 2: In the following code I am trying to get value from edit text.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:key="example_text"
android:title="#string/pref_host_ip_address"
android:defaultValue="#string/pref_default_host_address"
android:selectAllOnFocus="true"
android:inputType="numberDecimal"
android:digits="123456789."
android:capitalize="words"
android:singleLine="true"
android:maxLines="1" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:key="example_list"
android:title="#string/pref_title_add_friends_to_messages"
android:defaultValue="-1"
android:entries="#array/pref_example_list_titles"
android:entryValues="#array/pref_example_list_values"
android:negativeButtonText="#null"
android:positiveButtonText="#null" />
And I am guessing here android:key is the key to be passed as arguments in
String value = preferences.getString(key, " null");
I am using Android Studio and created a "Settings Activity".
Then you get your SharedPreferences via PreferenceManager.getDefaultSharedPreferences(). Replace:
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
with:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
You can use this:
String key = "example_text";
final String PREF_FILE_NAME = "SettingsActivity";
shared = getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
String value = preferences.getString(key, " null");
But first you have to save some value with your key like:
shared.edit().putString(key,"MY_VALUE").commit();
Run your project on a real device and if a SharedPreferences file (it has .xml extension) is created you can find it in the root catalog of the device, here to be more exact:
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml
or
/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml
By the way, you may just use getPreferences() method. Change your
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
into
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
Your SharedPreferences file will get a default name. But keep in mind that it is worth using getPreferences() instead of getSharedPreferences() only if you won't need more than one SharedPreferences file in your project.

Android : Set a preference's summary in a main preference screen to the values selected in a sub preference screen

My requirement
Have a main screen full of preferences (main_screen)
One preference (pref1) in this main_screen when clicked upon opens a
sub screen of settings (sub_screen)
In this sub_screen, there are 2 ListPreferences, when the user
selects a value from these lists, the summary for that ListPreference
is updated to contain the value the user selected
in the main_screen, the summary for pref1 should show the values
selected in the subscreen's listPreferences (i.e. the summary has
List1SelectedValue, List2SelectedValue)
On going into the main_screen for the first time, the summary for
pref1 should be populated
On going to the sub_screen and changing the values, and then
returning to the main_screen the summary should be updated to reflect
the newly selected values in sub_screen.
I have searched around and i can not work out how to set the summary of the pref1 on the main screen to the values selected in the sub_screen.
Sample main_screen xml
<PreferenceScreen>
<PreferenceCategory
style="#style/settings_category_text"
android:title="Section 1 Heading" >
<Preference
android:key="section1_key1"
android:title="Pref 1">
</Preference>
</PreferenceCategory>
<PreferenceCategory
style="#style/settings_category_text"
android:key="extra_settings_category"
android:title="Section 2 Heading" >
<PreferenceScreen
android:key="sub_screen"
android:title="Sub screen of settings"
android:summary="">
<intent
android:targetPackage="com.my.test"
android:targetClass="com.my.test.SubScreenPreferenceActivity" />
</PreferenceScreen>
</PreferenceCategory>
</PreferenceScreen>
Sample sub_screen xml
<PreferenceScreen>
<PreferenceCategory
style="#style/settings_category_text"
android:title="Additional Settings" >
<ListPreference
android:key="list_pref1"
android:title="List Pref 1"
android:defaultValue="1"
android:entries="#array/list_pref1_titles"
android:entryValues="#array/list_pref1_values"
android:summary="%s"
/>
<ListPreference
android:key="list_pref2"
android:title="List Pref 2"
android:defaultValue="1"
android:entries="#array/list_pref2_titles"
android:entryValues="#array/list_pref2_values"
android:summary="%s"
/>
</PreferenceCategory>
</PreferenceScreen>
Sample arrays for list values in sub_screen
<string-array name="list_pref1_titles">
<item>Apples</item>
<item>Pears</item>
<item>Bananas</item>
</string-array>
<string-array name="list_pref1_values">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
<string-array name="list_pref2_titles">
<item>Cream</item>
<item>Ice Cream</item>
<item>Custard</item>
</string-array>
<string-array name="list_pref2_values">
<item>1</item>
<item>2</item>
<item>3</item>
</string-array>
My classes
com.my.test.MainPreferenceActivity : code for this main screen of
preferences
com.my.test.SubScreenPreferenceActivity : code for this sub screen
of preferences
What the screens look like
When the settings are displayed the user will see
Section 1 Heading
-----------------
Pref 1
Section 2 Heading
-----------------
Sub screen of settings
Clicking on "Sub screen of settings" will take you to a second settings screen that looks like the following
Additional Settings
-------------------
List Pref 1
Apples
List Pref 2
Cream
Clicking on "List Pref 1" will show a popup for the user to select Apples/Pears/Bananas
Clicking on "List Pref 2" will show a popup for the user to select Cream/Ice cream/Custard
In SubScreenPreferenceActivity i have registered an OnSharedPreferenceChangeListener so that when the user selects a value from one of the options popped up the summary for the the ListPreferences is updated with the value the user has selected.
What I am completely stuck on
I would like the main_screen to also contain a summary of the values that have been set in the sub_screen, for example, in the main screen i would like it to render like the following
Section 1 Heading
----------------
Pref 1
Section 2 Heading
------------------
Sub screen of settings
Apples, Cream
I would like it that when i go into the main_screen initially, the "Sub screen of settings" preference's summary is already set to the currently stored values for the preferences in the sub-screen (using the display values not the actual values).
Also when the user goes to the sub screen and changes the values, on returning to the main_screen the "Sub screen of settings" preference's summary is updated to show the new values of the settings.
How do i set the summary in the main_screen (MainPreferenceActivity) to the values selected in the sub_screen?
How do i update the main_screen when the preferences in the sub_screen (SubScreenPreferenceActivity) change?
Why I have the sub_screen xml in its own file and activity
By the way, I have the sub-screen in a separate XML file and with its own Activity class as I need to call it from the Android settings screens.
In the Android settings, when you click on the Account for my application it shows the "Account & Settings | Sync Settings" screen. In this screen i have it displaying the "Section 2 Heading" PreferenceCategory section (just like in my applications settings screen), clicking on "Account & Settings | Sync Settings" screen takes you to the sub-section preferences screen in my application.
Account & Settings | Sync Settings
AppIcon myAccount
appName
Section 2 Heading
-----------------
Sub screen of settings
Apples, Cream
DATA & SYNCHRONIZATION
----------------------
account_authenticator.xml
<account-authenticator xmlns:android="http://schemas.android.com/apk/res/android"
android:accountType="myAccount"
android:icon="#drawable/launcher"
android:label="#string/app_name"
android:smallIcon="#drawable/launcher"
android:accountPreferences="#xml/account_preferences"/>
account_preferences.xml
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceCategory
style="#style/settings_category_text"
android:key="extra_settings_category"
android:title="Section 2 Heading" />
<PreferenceScreen
android:key="sub_screen"
android:title="Sub screen of settings"
android:summary="">
<intent
android:targetPackage="com.my.test"
android:targetClass="com.my.test.SubScreenPreferenceActivity" />
</PreferenceScreen>
</PreferenceScreen>
I have resolved this myself. It turned out to not be too complex.
In the "onResume" of the activity for the first preference screen, I simply call a utility method to generate the summary string for the preference whose summary is to contain the values of all selected values in the second screen. This utility method queries the stored preferences to get the preference values and then makes up a suitable string. As this utility method checks the values of the stored preference the summary will be accurate when you first go into the activity as well as when you return to the activity from the sub-screen.
For example
in "com.my.test.MainPreferenceActivity" "onResume" method i have the following
// update the preference's summary to a string containing the values selected in the sub-screen
Preference syncPref = findPreference(SUB_SCREN_OF_SETTINGS);
syncPref.setSummary(getSubScreenSummary(....));
public String getSubScreenSummary(){
// get the value of list_pref_1
// get the value of list_pref_2
String s = ...... // build up the string based on values of list_pref_1/list_pref_2
return s;
}

Preferences don't show up in data/data nor can i access them with code

I'm trying to create a game. Now for some data i need to keep(music, effects, background on/of) i would like to use preferences.
I create new xml file named preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<EditTextPreference android:key="music" android:title="Some title" android:defaultValue="true"/>
</PreferenceScreen>
Then i go to the location(with root privileges) and there is only lib folder in data/data/my.app.folder/. No shared_prefs folder.
When i try to access the preferences it is null. I tried with getSharedPreferences() and with PreferenceManager.getDefaultSharedPreferences(). What could be the reason?
Also i don't have activity for the preferences, I want to manage them manually.
How can I get over this problem?
To use shared preferences you will have to create it first. Like this:
SharedPreferences prefs = getApplicationContext().getSharedPreferences(
"music", Context.MODE_PRIVATE);
To create preferences in first time in it:
final String BACKGROUND_DEFAULT_VALUE = "on";
final String DEFAULT_TITILE = "";
final String TITILE_KEY = "title";
final String BACKGROUND_KEY = "background_key";
Editor editor= prefs.edit();
editor.putString(TITILE_KEY, DEFAULT_TITILE);
editor.putString(BACKGROUND_KEY, BACKGROUND_DEFAULT_VALUE);
editor.commit();
Than to edit/and save preferences in it:
Editor editor= prefs.edit();
editor.putString(TITILE_KEY, "new title");
editor.putString(BACKGROUND_KEY, "new background value i.e on/off");
editor.commit();
Than To read preferences:
String background_value = prefs.getString(BACKGROUND_KEY);
String title_value = prefs.getString(TITILE_KEY );
And you can see your shared preference file at location, it will be there after the creation.
/data/data/<packagename>/shared_prefs/music.xml
For more details and help, The android sdk's sample directory contains an example of retrieving and stroing shared preferences. Its located in the:
<android-sdk-home>/samples/android-<platformversion>/ApiDemos directory
Hope it helps.
There are two different types of xml files related to preferences.
The one you are showing is the xml resource file representing the preference hierarchy (screen representation).
The second one is the file containing the actual key value pairs.
Creating the first one doesn't create the second one. You'll actually need to display the file using a PreferenceActivity (or the Fragment equivalent or your own display method which - as I understand - you intend to do) or you'll have to create the preferences in code.

read from android SharedPreference

I know it's been asked before, but it doesn't seem to work for me.
I have an XML file preferences.xml in the folder res\xml. It contains an optionscreen like so:
<PreferenceScreen>
<EditTextPreference
android:name="prfEmail"
android:summary="Your account's e-mail address"
android:title="E-mail"
android:key="prfEmail" />
</PreferenceScreen>
I can make an activity from it and it shows fine. Now I'd like to read values from these preferences, but I can't seem to find it. In another activity I do:
SharedPreferences appSharedPrefs;
appSharedPrefs = getSharedPreferences("preferences",Activity.MODE_PRIVATE);
String restoredText = appSharedPrefs.getString("prfEmail",null);
Whan I'd like to print this value it gives null back. What am I doing wrong?
The app preferences are stored in the default SharedPreferences. You can access them with :
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

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.
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);
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.
Create integer.xml under res/values to store integer constants.
In prefereces.xml reference "#integer/default_brightness"
In code context.getResources().getInteger(R.integer.default_brightness)

Categories

Resources