How to modify preferences from a CheckBox view? - android

My app has 3 steps to set it up for the first time.
In each of these steps I want the user to be able to modify preferences, since it's not a PreferenceScreen I cannot add a CheckBoxPreference.
I tried using a CheckBox view, however I don't know how to make it affect preferences.
How can this be done?

You can write a boolean value to your preferences like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs == null)
return;
SharedPreferences.Editor editor = prefs.edit();
if(editor == null)
return;
editor.putBoolean("prefs_key_for_your_boolean", someBoolean);
editor.commit();
and load it like this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(prefs == null)
return;
someBoolean = prefs.getBoolean("prefs_key_for_your_boolean", defaultBooleanValue);
Read the value out of the checkbox view like this when you want to save it:
someBoolean = checkBoxView.isChecked();
And set it using the value you loaded from the prefs like this:
checkBoxView.setChecked(someBoolean);
You can listen for changes to the checkbox state like this:
checkBoxView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// add code here
}
});

Related

Is there only one shared preferences object per application?

My question is: If I call:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
in two different Activities in my application, does it refers to the same SharedPreferences file?
More concretely, I have a rememberMe check box in my SharedPreferences.
which I can change from two locations in my application. It looks like when I change it in one location it doesn't take effect in the second location.
Edit:
I have this code:
public View createSettingsOverlay(){
ViewGroup root = (ViewGroup)findViewById(R.id.absoluteOverlay);
LayoutInflater inflater = getLayoutInflater();
View result = inflater.inflate(R.layout.overlay_baloon_settings, root, false);
((TextView)result.findViewById(R.id.loginText)).setText(application.getCurrentlyLoggedUser());
((TextView)result.findViewById(R.id.passwordText)).setText(application.getCurrenlyLoggedPass());
((TextView)result.findViewById(R.id.loginTimeText)).setText(application.getTimeOfLogin().toString());
((TextView)result.findViewById(R.id.settings_popup_server_url)).setText(application.getCurrentUrl());
//Emil Edit
CheckBox rememberMe = (CheckBox)result.findViewById(R.id.cbRememberMe);
//boolean rememberMePreference = PreferenceManager.getDefaultSharedPreferences(DynamicDataActivity.this).getBoolean(SettingsActivity.REMEMBER_ME_CHECKBOX_KEY, false);
Log.d(TAG, "Remember Me set in the preference is: " + PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(SettingsActivity.REMEMBER_ME_CHECKBOX_KEY, false));
rememberMe.setChecked(PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).getBoolean(SettingsActivity.REMEMBER_ME_CHECKBOX_KEY, false));
rememberMe.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG, "boolean isChecked is: " + isChecked);
if (isChecked)
{
Log.d(TAG, "Remember me checkbox in setting overlay set to True");
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean(SettingsActivity.REMEMBER_ME_CHECKBOX_KEY, true);
application.setRememberMeChecked(true);
}
else
{
Log.d(TAG, "Remember me checkbox in setting overlay set to False");
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit().putBoolean(SettingsActivity.REMEMBER_ME_CHECKBOX_KEY, false);
application.setRememberMeChecked(false);
}
}
});
Which basically created a popup window with setting from SharedPreferences when I check the rememberMe checkbox in this popup window, close it and open it again. for some reason it is not checked again, in other Activity (Setting Activity), I can see that this change didn't took effect as well.
Uses this for get SharedPreferences (myPrefs is your file):
For save:
SharedPreferences prefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("rememberMe", yourState);
editor.commit();
For get:
SharedPreferences prefs = getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
boolean state = prefs.getBoolean("rememberMe", state_by_default);
Converting comments to answer,
Your problem is you haven't commit your preference. SharedPreference will update only after commit
Yes, default shared pref file is same for Application context.

Multiple saved preferences in android

I am very new to java and android but doing my best to make an app, basicaly I want a page with 6 text boxes on it, and each allows the user to type a 3 digit unique value into each, check a confirm box and then a button to save, then when the user revisits this part of the app the data will still be there, I managed to get it working for 1 box but if i add another it just duplicated box 1s value, here is my code for the class
public class Settings extends Activity implements OnClickListener {
CheckBox cb;
EditText et, et1;
Button b;
String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
cb = (CheckBox) findViewById(R.id.checkBox1);
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
loadPrefs();
cb.setChecked(false);
}
private void loadPrefs() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbValue = sp.getBoolean("CHECKBOX", false);
String name = sp.getString("NAME", "Kg");
if(cbValue){
cb.setChecked(true);
}else{
cb.setChecked(false);
}
et.setText(name + (" kg"));
}
private void savePrefs(String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
private void savePrefs(String key, String value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("CHECKBOX", cb.isChecked());
if (cb.isChecked())
savePrefs("NAME", et.getText().toString());
finish();
}
}
any help would be greatly appreciated as time is short :(
Read this.
What you're not coding is saving the data.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbValue = sp.getBoolean("CHECKBOX", false);
What the second line does is says, is "CHECKBOX" a saved sharedpreference? No, it isn't. Okay let's get the default value of false then.
What you need to do is save it using this:
SharedPreferences.editor Editor = sp.edit();
Editor.putBoolean("CHECKBOX",true);
Editor.commit();
The first line defines the sharedpreference editor. The next line saves the boolean value true under the in effect filename (key) of CHECKBOX and then the commit line says, okay do the above and finalise it so that now whenever I call:
sp.getBoolean("CHECKBOX",false);
I will get true because I won't have to use the default value of false.
Try to make this easy for you...
First, in your proferences xml, each text box and check box needs it's own key.
Secondly, to make it easy for you to read/understand you should assign a different name for the pref save method void savePrefs(String key, String value).
For example String: void savePrefsString(String key, String value)
For example boolean: void savePrefsBoolean(String key, boolean value)
Be sure each one is called appropriately (savePrefsBoolean for boolean and savePrefsString for edittext).
Then for each edit text you will want to retrieve the key from preferences for that edittext.
Example:
String name1 = sp.getString("NAME1", "Kg");
String name2 = sp.getString("NAME2", "Kg");
String name3 = sp.getString("NAME3", "Kg");
Then:
et1.setText(name1 + (" kg"));
et2.setText(name2 + (" kg"));
et3.setText(name1 + (" kg"));
Do the same for your checkboxes (they are actually true/false booleans).
Example:
boolean cb1 = sp.getBoolean("CHECKBOX1", false); //false is default value
boolean cb2 = sp.getBoolean("CHECKBOX1", false);
boolean cb3 = sp.getBoolean("CHECKBOX1", false);
Then to set value from prefs:
if(cb1){
cb1.setChecked(true);
}else{
cb1.setChecked(false);
}
and to save what the user has pressed:
savePrefsBoolean("CHECKBOX1", cb1.isChecked()); // get check value of checkbox
savePrefsBoolean("CHECKBOX2", cb2.isChecked());
savePrefsBoolean("CHECKBOX3", cb3.isChecked());

Create preferencefrom single checkbox with without extending preferenceactivity

In my app i just have one basic setting from using a checkbox and i would like to have it persist itself just like preferences do when extending preferenceactivity, except without doing that. All the preference examples i can find , extend preferenceactivity.
Is it possible to have the preference functionality with just a basic checkbox in, with logic for it in Main UI? Short examples would be appreciated.
You can just access the shared preferences in any activity...
SharedPreferences preferences = getSharedPreferences( NameAsString, Context.MODE_PRIVATE );
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean( keyAsString, value );
editor.apply();
note that editor.apply() is asynchronous and only available in GB and up, use editor.commit() for less than android 2.3
CheckBox checkBox = (CheckBox) findViewById(R.id.checkbox1);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkbox_key", isChecked);
editor.commit();
}
});
You can save preferences manually yourself using SharedPreferences. You could then save/load the setting once the checkbox is changed
CheckBox checkBox = ( CheckBox ) findViewById( R.id.checkbox );
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// get the preference manager
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// get the editor
SharedPreferences.Editor editor = prefs.edit();
// put the new setting
editor.putBoolean(PREF_NAME, true);
// IMPORTANT - save the new settings
editor.commit();
}
}
}
});
You can then retrieve you setting where ever you like using
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
if (prefs.getBoolean(PREF_NAME, false)) {
// setting dependent code goes here
}
Hope that helps :)

How save changed TextView with SharedPreferences?

OK here is my problem. I have a spinner and every option in spinner should edit textview in my layout (option in spinner you can see in position command), so I have made it with SharedPreferences, it is not problem, when I select some option in spinner, so the textview is changed, but when I kill my app and then re-open, the textview is default (the same as defined in my layout). So where is the problem?
First Activity:
if(position == 4){
SharedPreferences myPrefsUv = CPUActivity.this.getSharedPreferences("myPrefsUv", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorUv = myPrefsUv.edit();
prefsEditorUv.putString(maxUv, "1");
prefsEditorUv.commit();
}
if(position == 5){
SharedPreferences myPrefsUv = CPUActivity.this.getSharedPreferences("myPrefsUv", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorUv = myPrefsUv.edit();
prefsEditorUv.putString(maxUv, "2");
prefsEditorUv.commit();
}
if(position == 6){
SharedPreferences myPrefsUv = CPUActivity.this.getSharedPreferences("myPrefsUv", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorUv = myPrefsUv.edit();
prefsEditorUv.putString(maxUv, "3");
prefsEditorUv.commit();
}
if(position == 7){
SharedPreferences myPrefsUv = CPUActivity.this.getSharedPreferences("myPrefsUv", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorUv = myPrefsUv.edit();
prefsEditorUv.putString(maxUv, "4");
prefsEditorUv.commit();
}
Second Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
SharedPreferences myPrefsUv = UVActivity.this.getSharedPreferences("myPrefsUv", MODE_PRIVATE);
String prefNameUv = myPrefsUv.getString(maxUv, "");
if(prefNameUv == "1"){
final TextView textUv = (TextView)findViewById(R.id.text_max);
textUv.setText("100");
}
if(prefNameUv == "2"){
final TextView textUv = (TextView)findViewById(R.id.text_max);
textUv.setText("110");
}
if(prefNameUv == "3"){
final TextView textUv = (TextView)findViewById(R.id.text_max);
textUv.setText("120");
}
if(prefNameUv == "4"){
final TextView textUv = (TextView)findViewById(R.id.text_max);
textUv.setText("130");
}
}
Thank you.
You are adding the different values with the same key? This way I think it will always return the first match. I don't see in your code "maxUv" to be assigned different values, according to the different cases.
1) I suggest you move to if/else construct. This way, when you're in the right case, the remaining conditions are not evaluated.
2) call the following lines outside the if/else construct. You don't need to get the SharedPreferences Editor in every case.
SharedPreferences myPrefsUv = CPUActivity.this.getSharedPreferences("myPrefsUv", MODE_PRIVATE);
SharedPreferences.Editor prefsEditorUv = myPrefsUv.edit();
Same for the acquiring of TextView textUv in the second Activity. Just acquire reference once, and use the same reference in all cases.
3) In the second Activity, you're also comparing Strings with == operator, but Strings should be compared with equals().
The other guy beat me to it. the old equals stuff.
You're comparing a String using "==". You should compare using .equals:
if(prefNameUv.equals("1"))
This is what you need.
Besides, try not to declare the preferences file. In your case, you're not needing it, so there is no need to make it more complex. Use the following...
First activity:
SharedPreferences myPrefsUv = PreferenceManager.getDefaultSharedPreferences(CPUActivity.this);
Second activity:
SharedPreferences myPrefsUv = PreferenceManager.getDefaultSharedPreferences(UVActivity.this);

ListPreference no selection. How to?

I have a ListPreference and want to verify if there is no selection to make some code/treatement. How can i do this ?
I have this to verify the selection:
if (Integer.valueOf(choice) == 0) {
What code to verify if not selection?
Thank you for your help.
If there is a preference selected for this ListPreference, then it will be saved in your SharedPreferences. You can test against this value by doing something like this:
private Boolean prefHasSelection(String prefId){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String yourPref = sp.getString(prefId, null);
return (yourPref != null);
}
prefHasSelection("yourPrefId"); // returns true if something is set
You could call this method at any point in your application lifecycle to determine if the preference has been set.

Categories

Resources