Is there only one shared preferences object per application? - android

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.

Related

Muting Sounds in Android App with Shared Preferences Not Working

I'm building my first Android app, so apologies in advance for my lack of expertise. I've been banging away at this issue for 2 days so far. When I set the sound to mute in my Settings Activity via Shared Preferences, the setting does not 'stick'. Here is the code from my Main Activity:
SharedPreferences settingsSP;
boolean muteSound;
Then in onCreate:
settingsSP = getApplicationContext().getSharedPreferences("PlayerPreferences", Context.MODE_PRIVATE);
muteSound = settingsSP.getBoolean("muteSound", false);
Then I obviously use the muteSound variable to determine whether or not to play sounds within the MainActivity. Now when I go the Settings activity I have this code:
SharedPreferences settingsSP;
boolean muteSound;
Then in onCreate I have this:
settingsSP = getApplicationContext().getSharedPreferences("PlayerPreferences", Context.MODE_PRIVATE);
if (muteSound) {
activitySettingsBinding.displayMuteCheckBox.setChecked(true);
} else {
activitySettingsBinding.displayMuteCheckBox.setChecked(false);
}
activitySettingsBinding.displayMuteCheckBox.setOnClickListener(v -> {
if (activitySettingsBinding.displayMuteCheckBox.isChecked()) {
muteSound = true;
SharedPreferences.Editor editor = settingsSP.edit();
editor.putBoolean("muteSound", muteSound);
editor.apply();
} else {
muteSound = false;
SharedPreferences.Editor editor = settingsSP.edit();
editor.putBoolean("muteSound", muteSound);
editor.apply();
soundPool.play(bubble, 1, 1, 1, 0, 1);
}
The xml code:
<CheckBox
android:id="#+id/displayMuteCheckBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:gravity="center_vertical"
android:layoutDirection="rtl"
android:paddingLeft="40dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
android:text="Mute Sound"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold"
android:theme="#style/CheckBoxStyle" />
I placed a number of log.d tags throughout the code so that I observe what was happening. For example after I cold booted the app in Android Studio:
Open MainActivity, onCreate muteSound = false
Tap Settings button and the Settings onCreate lists muteSound = false
I check the checkbox to set it to muteSounds = true
I tap return button within Settings to return to MainActivity
MainActivity onCreate muteSound = true
Tap Settings button and the Settings onCreate lists muteSound = false
And the checkbox is unchecked - because muteSound = false
I can't figure out why the settings is not sticking. When I checked to set the muteSound to be true, that settings is lost when I return to the Settings Activity. I've searched the code to see if I set muteSound = true on accident somewhere else, but when searching the usages I did not find any. Is my assumption about sharePreferences incorrect. It doesn't appear to hold the settings. Or perhaps am I using the checkbox incorrectly, maybe I should be using another type of button here. I would like to use checkboxes to control the display of the score, time and other items on the MainActivity and throughout other app Activities, but if I can't figure this gap in my knowledge I won't be able to. What am I doing incorrectly?
For displayMuteCheckBox, use setOnCheckedChangeListener instead of setOnClickListener and use settingsSP variable to store value in SharedPreferences instead of creating new object of SharedPreferences.Editor:
activitySettingsBinding.displayMuteCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
settingsSP.edit().putBoolean("muteSound", isChecked).apply();
if (isChecked)
soundPool.play(bubble, 1, 1, 1, 0, 1);
}
});

How to modify preferences from a CheckBox view?

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
}
});

Saving checkbox status as SharedPreference unsuccessful

I am trying to set up a profile where a user selects male or female via a checkbox representing each. I then try to save this data using SharedPreference object. Have added a onClickListener to both checkboxes and if checked a boolean value is set to true.
But no matter what i have tried (and i have tried this for 4 hours!!!!!) when i refresh the activity both boxes are checked and both boolean values are true! Any ideas would be great.
// check box initialisation male and female
male = (CheckBox) this.findViewById(R.id.cb_MalePrfofile);
male.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// when male is checked
if (((CheckBox) v).isChecked()) {
sex = "Male";
//malePref=true;
//femalePref=false;
female.setChecked(false);
Toast.makeText(getBaseContext(), "malePref=true", Toast.LENGTH_SHORT).show();
}
}
});// end on click for male
// if female check box is checked
female = (CheckBox) this.findViewById(R.id.cb_FemalePrfofile);
female.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// when male is checked
if (((CheckBox) v).isChecked()) {
sex = "Female";
//femalePref=true;
//malePref=false;
male.setChecked(false);
Toast.makeText(getBaseContext(), "feamlePref=true", Toast.LENGTH_SHORT).show();
}
}// end onClick/if
});// end on click call for male
}// end intilize widgets
Setting the SharedPref editor:
//Checkboxes
if(male.isChecked()){
//boolean maleValue=true;
editor.putBoolean("maleValue", true);
}else if(female.isChecked()){
//boolean femaleValue=true;
editor.putBoolean("femaleValue", true);
}//end else
the onCreate method to set data according to saved preferences:
male.setChecked(prefs.getBoolean("maleValue", false));
female.setChecked(prefs.getBoolean("femaleValue", false));
The XML:
<CheckBox
android:id="#+id/cb_MalePrfofile"
android:text="Male"
android:typeface="serif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
></CheckBox>
<CheckBox
android:id="#+id/cb_FemalePrfofile"
android:layout_width="wrap_content"
android:text="Female"
android:typeface="serif"
android:layout_height="wrap_content"></CheckBox>
Answering comments:
I have the editor.commit() in place already and all other data from spinners, edit texts etc saved fine.
Also have tried adding a Radiogoup but no matter which i select the Male is selected by default overtime activity reloads. Sorry about the long code here but am posting the onCreate method as maybe missing something here:
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setContentView(R.layout.profile);
intilizeWidgets();
//load teh sahred prefs object
prefs = this.getSharedPreferences(prefFilename, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
//save teh sored values in the Edittexts
firstName.setText(prefs.getString("firstName", null));
lastName.setText(prefs.getString("lastName", null));
insuranceNo.setText(prefs.getString("insuranceNumber", null));
padiNumber.setText(prefs.getString("padiNum", null));
aboutMe.setText(prefs.getString("aboutMe", null));
boolean maleBoo = prefs.getBoolean("maleValue", false);
Toast.makeText(getBaseContext(), "Male checked is " + maleBoo, Toast.LENGTH_SHORT).show();
male.setChecked(prefs.getBoolean("maleValue", false));
female.setChecked(prefs.getBoolean("femaleValue", false));
boolean femaleBoo = prefs.getBoolean("femaleValue", false);
Toast.makeText(getBaseContext(), "FeMale checked is " + femaleBoo, Toast.LENGTH_SHORT).show();
certLevel.setSelection(prefs.getInt("certLevel", 0));
yearsExperince.setSelection(prefs.getInt("yearsExp", 0));
//radiobuttons
isMaleButton.setChecked(prefs.getBoolean("maleButton", false));
isFemaleButton.setChecked(prefs.getBoolean("femaleButton", false));
}// end onctreate
When the Save button is clicked I get the Shared pref object and Editor
public void onClick(View arg0) {
//get the sahred pref object and its editor to accept values
this.prefs = this.getSharedPreferences(prefFilename, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
if(isMaleButton.isChecked()){
editor.putBoolean("maleButton", true);
}else if(isFemaleButton.isChecked()){
editor.putBoolean("femaleButton", true);
}
it seems you're missing editor.commit().
On an unrelated note, why do you use checkboxes? radiobuttons seem more apt

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 :)

Categories

Resources