I've got a preferences.xml stored in my res/xml folder:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory>
<Preference android:key="units_length" android:title="imperial"></Preference>
</PreferenceCategory>
</PreferenceScreen>
Here is how the onCreate method looks like in my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
// Get preferences
SharedPreferences preferences = getSharedPreferences("preferences", 0);
// Fetch the text view
TextView text = (TextView) findViewById(R.id.textView1);
// Set new text
text.setText(preferences.getString("units_length", "nothing"));
}
My application just says "nothing". What am I doing wrong here?
Try setting android:defaultValue attribute in your preference xml definition to whatever appropriate. It seems that property have never been initialized.
Related
In my app I have a PreferenceScreen which looks like this:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:key="state"
android:title="#string/stateTitle"
android:summary="#string/stateSummary"
android:defaultValue="false" />
<Preference
android:key="test"
android:layout="#layout/pref_control"
android:dependency="state" />
</PreferenceScreen>
Now my question is how can I get the views which are in my pref_control.xml from the PreferenceActivity? I tried with normal findViewById() but that ends in a NullPointerException. Here is my code that causes the exception:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
((Button) findViewById(R.id.startTime)).setText("bla");
((Button) findViewById(R.id.endTime)).setText("bla");
}
You can get the Preference by using Preference p = findPrefences("test") from the Activity (or better the PreferenceFragment, if you are using newer versions of Android).
On that object you can call .getView(convertView, parent). For your purposes, it should be ok to call that method with null as paramters: findPreferences("test").getView(null, null).
HTH
Since you're using PreferenceActivity, you can use:
final CheckBoxPreference stateCheckBox = (CheckBoxPreference)findPreference("state");
and presumably:
final Preference testPreference = (Preference)findPreference("test");
It's deprecated but it should work.
I'm trying to programmatically create a ListPreference, which I can do but when I select it, it's list of entries is empty. I believe I am correctly setting the setEntries() and setEntryValues() with CharSequence arrays, but it's just empty when I select it.
Please find below the ActivitySetting class. Please note I'm using PreferenceFragments as to not use deprecated methods. But I only have one PreferenceFragment which is currently set as default
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Display the fragment as the main content.
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.settings);
// Create the new ListPref
ListPreference customListPref = new ListPreference(getActivity());
// Get the Preference Category which we want to add the ListPreference to
PreferenceCategory targetCategory = (PreferenceCategory) findPreference("TARGET_CATEGORY");
CharSequence[] entries = new CharSequence[]{"One", "Two", "Three"};
CharSequence[] entryValues = new CharSequence[]{ "1", "2", "3" };
// IMPORTANT - This is where set entries...looks OK to me
customListPref.setEntries(entries);
customListPref.setEntryValues(entryValues);
customListPref.setTitle("Title");
customListPref.setSummary("This is the summary");
customListPref.setDialogMessage("Dialog Message");
customListPref.setPersistent(true);
// Add the ListPref to the Pref category
targetCategory.addPreference(customListPref);
}
}
}
Here is the Setting.xml it just has the single PreferenceCategory which the ListPreference is added to:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="Some Options" android:key="TARGET_CATEGORY">
</PreferenceCategory>
</PreferenceScreen>
Here is what I get. The ListPreference has been successfully but when I select it.... No entries :( I'm expecting the options: "One", "Two", "Three"
Found it if you set the setDialogMessage() then this overwrites the contents so by removing this line, it works now.
You might want to replace setDialogMessage() by setDialogTitle() to get the title back.
How do I update my PreferenceActivity?
I've saved in the SharedPreferences the value of my CheckBox in an activity (in that case, true). And even if I go to other activities I can see that it's true. But, when I go to my PreferenceActivity, the checkbox is not checked, it's false. So what I want to know is, how do I load my SharedPreferences in my PreferenceActivity, and how do I update the CheckBox (load the value, and if it's true, set the CheckBox as checked).
Should I load it like this?
Shared Preferences SP = getSharedPreferences(DATA, MODE_PRIVATE);
fw = SP.getBoolean("fw", false);
But, how do I set the CheckBox true or false since I can't use findViewById?
EDIT:
Activity where I save the CheckBox value:
Editor edit = SP.edit();
edit.putBoolean("fw", fwbt.isChecked());
edit.commit();
My preference xml file:
<CheckBoxPreference
android:title="CheckBox FW"
android:key="fw"
android:summary="Estado do CheckBox" />
My preference Activity:
public class Prefs extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
//Don't know what to do here...
}
}
You need to create an Editor to modify the SharedPreferences.
Example
getSharedPreferences(DATA, MODE_PRIVATE).edit().putBoolean("fw", true).commit();
Update
You need to define the used SharedPreferences in the Activity, too.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(DATA);
addPreferencesFromResource(R.xml.prefs);
}
I have not use PreferenceActivity before but I think you simply need to implement it like any other activity.
public class PreferenceWithHeaders extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CheckBox cb = (CheckBox)this.findViewById(IDOFBUTTON);
... do whatever on checkbox
}
I can't find a solution, so I gave up. I've just created created a custom Preferences, it's way easier.
Anyway, I'll keep looking for a solution for this later.
You've mess it up - the PreferenceActivity writes/reads from the SharedPreferences. So in your activity do
Shared Preferences SP = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = SP.edit();
edit.putBoolean("fw", fwbt.isChecked());
edit.commit();
and the change should be there in your PreferenceActivity.
Also :
SP.edit().putBoolean("fw", fwbt.isChecked()).commit();
will do
I have made 4 radio buttons and want to save the state when any of them is clicked and then want to use that saved state in the application.How can i do that?
myOption1.setChecked(true);
myOption2.setChecked(true);
myOption3.setChecked(true);
myOption4.setChecked(true);
Override onSaveInstanceState() and onRestoreInstanceState() in your activity.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("myOption1", myOption1.isChecked());
savedInstanceState.putBoolean("myOption2", myOption2.isChecked());
savedInstanceState.putBoolean("myOption3", myOption3.isChecked());
savedInstanceState.putBoolean("myOption4", myOption4.isChecked());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
myOption1.setChecked(savedInstanceState.getBoolean("myOption1"));
myOption2.setChecked(savedInstanceState.getBoolean("myOption2"));
myOption3.setChecked(savedInstanceState.getBoolean("myOption3"));
myOption4.setChecked(savedInstanceState.getBoolean("myOption4"));
}
If you're only going to have 4 radio buttons all in all, you might as well store their "values" in SharedPreferences (persistant storage).
Example:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor shEditor = sharedPreferences.edit();
shEditor.putBoolean("checkbox_1", myOptionOne.isChecked());
shEditor.putBoolean("checkbox_2", myOptionTwo.isChecked());
shEditor.putBoolean("checkbox_3", myOptionThree.isChecked());
shEditor.putBoolean("checkbox_4", myOptionFour.isChecked());
shEditor.commit();
Use it by doing the following:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
myOptionOne.setChecked(sharedPreferences.getBoolean("checkbox_1", false));
myOptionTwo.setChecked(sharedPreferences.getBoolean("checkbox_2", false));
myOptionThree.setChecked(sharedPreferences.getBoolean("checkbox_3", false));
myOptionFour.setChecked(sharedPreferences.getBoolean("checkbox_4", false));
Save that value in sharedPreferences Concept. Sample Example has been placed here that uses predefined method called addPreferencesFromResource() that will get the state of checkbox value automatically and saved in the preferences.
public class EditPreference extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.checkboxpref);
addPreferencesFromResource(R.layout.checkboxpref);
}
}
And layout Code should be this :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="#string/checkbox_pref"
android:title="#string/eidt_preferences">
<CheckBoxPreference
android:key="#string/pref_12_time_format"
android:title="#string/time_formats"
android:summary="#string/twelve_hour"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="#string/pref_show_current_location"
android:title="#string/show_current_location"
android:summary="#string/using_gps_network"
android:defaultValue="true"/>
<CheckBoxPreference
android:key="#string/pref_display_date"
android:title="#string/display_date"
android:defaultValue="true"/>
</PreferenceScreen>
Now you have retreive this stored checkbox value has follows :
SharedPreferences sharedPreference = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
mTimeFormat = sharedPreference.getBoolean("pref_12_time_format", false);
mServiceType = sharedPreference.getBoolean(
"pref_show_current_location", false);
mDisplayDate = sharedPreference.getBoolean("pref_display_date", false);
How can I change the view of a CheckBoxPreference at runtime?
Specifically, I'd like to change a CheckBoxPreference summary depending on whether the user has checked the box or not.
If it were a normal view, I could do something like:
view1 = (TextView)findViewById(R.id.idView1);
view1.setText("some text");
But a CheckBoxPreference has no id, so I don't know how to get a "handle" to it.
I have an answer to my own question. The key is to use findPreference in a PreferenceActivity, as follows:
public class MyPreferenceActivity extends PreferenceActivity{
private SharedPreferences preferences;
private SharedPreferences.OnSharedPreferenceChangeListener prefListener;
private CheckBoxPreference pref;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
pref = (CheckBoxPreference) findPreference(res.getString(R.string.keyAccount));
pref.setSummary("something");
//-- preference change listener
prefListener = new SharedPreferences.OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences prefs, String key){
if (key.equals(somekey)){
pref.setSummary("something new");
}
}
};
preferences.registerOnSharedPreferenceChangeListener(prefListener);
}
This is tested and works.
You should use (in XML layout file):
android:summaryOff
android:summaryOn
You can set id to CheckBoxPreference using android:id in xml like code below
<CheckBoxPreference
android:key="pref_boot_startup"
android:title="Auto start"
android:defaultValue="true"
android:id="#+id/my_CheckBoxPref"
/>
To retrieve you can use
CheckBoxPreference check = (CheckBoxPreference)findViewById(R.id.my_CheckBoxPref);