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
Related
I have a textview that when user clicks it, I want it to be invisible. But I want it to stay invisible, even after user has reloaded the app, using "sharedpreferences". How to get shared preferences working and then recalled correctly?
This is my code for storing the preference when user clicks the textview:
textView.setVisibility(View.INVISIBLE);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("was_clicked", true);
editor.commit(); // commit changes
So I understand this will store a true/false boolean in shared preferences called" was_clicked".
But now how do I have it checked for "true" in the onCreate method of the activity and then have it set TextView to view.INVISIBLE if was_clicked = true?
Check out this article. But to answer your question specifically
if (getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE).getBoolean("was_clicked", false))
textView.setVisibility(View.INVISIBLE);
You can check the value using this method:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean wasClicked = pref.getBoolean("was_clicked",false);
if (wasClicked){
textView.setVisibility(View.INVISIBLE);
}else {
textView.setVisibility(View.VISIBLE);
}
In your onCreate method you should create preferences and read from them like this:
static final String PREFERENCES_NAME = "MyPref";
static final String WAS_CLICKED_NAME = "was_clicked";
#Override
void onCreate()
{
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
boolean invisible = preferences.getBoolean(WAS_CLICKED_NAME, false); // 2nd argument is the default value
if (invisible)
{
textView.setVisibility(View.INVISIBLE);
}
}
getBoolean method will read value of "was_clicked" preference. 2nd argument will be returned if you haven't yet put value "was_clicked" to shared preferences, so you can return false if you haven't put this preference to show the textView.
I am currently able to create a preference screen with a PreferenceFragment, in which I assign my preferences using:
addPreferencesFromResource(R.xml.preferences);
Instead of using the resource 'R.xml.preferences', I would like to use my SharedPreferences i have already saved, for example:
SharedPreferences prefs = this.getActivity().getSharedPreferences("preferences", 0);
addPreferencesFromResource(prefs);
However, this does not work. Is it possible to do this? If so, How? Or is it required that I use an xml document?
I happen to had exactly the same problem but I figured it out, hope this helps.
You need to do the following steps in order to add a Custom Preference without using an XML Reouser
First:
You need to create a Preference Screen, this is as it says a "screen" which can containt several Preferences and must be linked to your PreferenceFragment or PreferenceActivity.
Consider the Following PreferenceFragment for example (and consider it is contained in a superior Activity..)
public static class YourPreferenceFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceScreen p = createPreferences();
this.setPreferenceScreen(p);//Set the PreferenceScreen as the current one on this fragment
//now bind values, notice we use p.findPreference which means whe look into the preferenceScreen Associated with the PreferenceFragment/Activity
bindPreferenceSummaryToValue(p.findPreference("some_key"));
}
}
Now Consider that createPreferences is a method that will return a PreferenceScreen with your custom preferences such as a ListPreference or CheckboxPreference. This is how you really create the preferences and add them into a PreferenceScreen
private PreferenceScreen createPreferences()
{
PreferenceScreen p =
getPreferenceManager().createPreferenceScreen(getActivity());
ListPreference listPref = new ListPreference(getActivity());
listPref.setKey("some_key"); //Refer to get the pref value
CharSequence[] csEntries = new String[]{"Item1","Item2"};
CharSequence[] csValues = new String[]{"1","2"};
listPref.setDefaultValue(-1);
listPref.setEntries(csEntries); //Entries(how you display them)
listPref.setEntryValues(csValues);//actual values
listPref.setDialogTitle("Dialog title");
listPref.setTitle("Title");
listPref.setSummary("Some summary");
p.addPreference(listPref);
return p;
}
Please let me know if this helps
best,
EDIT: Code for bindPreferenceSummaryToValue
private static void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
// Trigger the listener immediately with the preference's
// current value.
if (preference instanceof CheckBoxPreference) {
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.
getDefaultSharedPreferences(preference.getContext()).
getBoolean(preference.getKey(),false));
} else {
sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.
getDefaultSharedPreferences(preference.getContext()).
getString(preference.getKey(),""));
}
}
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);
I want to change the background of a layout through what the user selects from a ListPreference in the preferences. I am having a little bit of trouble doing this. I have set up the preferences in my Java:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
and have an array set up for the ListPreference.
This is where I get the string from the preferences to change the background based on what is selected:
SharedPreferences SP = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
String strFavTeam = SP.getString("keyFavTeam", "0");
LinearLayout linearLayout = (LinearLayout) this.findViewById(R.layout.main);
if(strFavTeam.equals("0")){
linearLayout.setBackgroundResource(R.drawable.first_screen);
}
if(strFavTeam.equals("73")){
linearLayout.setBackgroundResource(R.drawable.tennessee_screen);
}
if(strFavTeam.equals("67")){
linearLayout.setBackgroundResource(R.drawable.georgia_screen);
}
I get a force close every time I choose Tennessee (which has a value of 73) from the ListPreference.
Please help!
Thanks!!
You're searching for a view using a layout id. That's never going to return anything except null. You need to search for the id of the LinearLayout view you want to change. It will be something like R.id.? where ? is whatever id you assigned to the view in main.xml.