I save the state of a boolean in onPause method. I have tried using both editor.apply() and editor.commit() but still the values are not saved.
Here is the onPause method:
#Override
protected void onPause() {
SharedPreferences.Editor editor = preferences.edit();
editor.clear(); //I have tried omitting it
editor.putBoolean(MUTE_TAG,mute);
editor.apply(); // I tried editor.commit() but with no effect
boolean mute1 = preferences.getBoolean(MUTE_TAG,false);
Log.d(TAG,"Values:\n"+ "mute1 " + mute1 + " mute);
super.onPause();
}
Note: When I try to access the value from the SharedPreferences again from different activity, it isn't updated. Here is the setup code
public static boolean mute;
public static final String PREFS = "prefs";
init(Context context) {
preferences = context.getSharedPreferences(PREFS,MODE_PRIVATE);
mute = preferences.getBoolean(MUTE_TAG,false);
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.d(TAG,"MUTE PRESSED");
mute = isChecked;
break;
}
What about after saving? Does the logcat show the current/expected value?
Here is what has worked for me:
Before : private boolean mute = true; but after sending the app to background. the result showed it true. While the default value is false;
COPIED YOUR CODE AS-IS
ONLY PROBLEM: Unclosed string literal
#Override
protected void onPause() {
SharedPreferences preferences = getSharedPreferences("SHARED_PREFERENCES_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
mute = !mute ;
Log.d(TAG, "UPDATED MUTE VALUE :: " + mute);
editor.clear(); //I have tried omitting it
editor.putBoolean(MUTE_TAG,mute);
editor.apply(); // I tried editor.commit() but with no effect
boolean mute1 = preferences.getBoolean(MUTE_TAG,false);
Log.d(TAG,"Values:\n"+ "mute: " + mute1 + " mute");
super.onPause();
}
SOLUTION #2
It is connected to this What's the difference between commit() and apply() in Shared Preference . Try using commit again, commit will block super.onPause from executing thus making sure it saves
SOLUTION #3
Your activities are calling onPause after onCreate thus saving back the default mute value. Therefore, Create a class & add STATIC PUBLIC /PUBLIC STATIC variables that will store the mute value & only save it when an activity is being destroyed. This static variable will not change it's value across activities
Related
I'm running to a really weird behavior with SharedPreferences. I'm wondering if I'm running into a synchronization issue.
It seems like the app can remember the preference changes in between activities but not when I restart the app. The state always returns back to the very first instance I created a preference. I've followed several examples, tutorials, and android documentation that all suggest similar code layout. I also watched how the preference.xml file changed while interacting with my code using the debugger and I confirmed it looked like the key value pair updated.
Could I be experiencing a synchronization issue with my emulator? I tried using both the editor.apply() method and editor.commit() method with the same results.
The only thing I've found that fixes my problem is using the editor.clear() method, but this feels a bit hacky...
note: please forgive the variable names, I'm making a pokedex...
public class SecondActivity extends AppCompatActivity {
private boolean caught;
private Set<String> pokemonCaught;
private String pokemonName;
public SharedPreferences sharedPreferences;
public static final String SHARED_PREFERENCES = "shared_preferences";
public static final String PREF_KEY = "inCaughtState";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
/*SKIPPING THE VIEW SETUP*/
/*SKIPPING BUTTON VIEW ATTRIBUTES*/
//variables required for changing button state
pokemonName = (String) nameTextView.getText();
caught = false;
//Loading in sharedPreferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
pokemonCaught = sharedPreferences.getStringSet(PREF_KEY, new HashSet<String>());
if (pokemonCaught.contains(pokemonName)) {
toggleCatch(catchButton);
}
}
public void toggleCatch (View view) {
//Editing and updating preferences
sharedPreferences =
getSharedPreferences(SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
if (caught == true) {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = false;
pokemonCaught.remove(pokemonName);
}
else {
/*SKIPPING BUTTON ATTRIBUTES*/
caught = true;
pokemonCaught.add(pokemonName);
}
editor.clear(); //This is my hacky solution...
editor.putStringSet(PREF_KEY, pokemonCaught);
editor.apply();
}
}
Try to use SharedPreferences this way:
To save data
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("stringName", "stringValue");
editor.apply();
To retrieve data
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PREFS", MODE_PRIVATE);
String name = preferences.getString("stringName", "none"));
Note that this "none" is in case to string "stringName" be null.
I'm trying to figure out why I can't have access to my SharedPreference file after an app restart.
In my Application class in the onCreate I define my SharedPreference once :
pref = getSharedPreferences(Util.PREF_FILE_NAME, Context.MODE_PRIVATE);
editor = pref.edit();
And then in the onResume of my activity I call:
String userName = MyApp.getApplication().pref.getString(Util.USER_NAME, "");
But at this point the user name is always empty after a restart.
-To save my value :
MyApp.getApplication().editor.putString(Util.USER_NAME,"name").commit();
-For MyApp.getApplication() I've defined in my Application class:
public MyApp() {
instance = this;
}
public static MyApp getApplication() {
if (instance == null) {
instance = new MyApp();
}
return instance;
}
From my device I run a terminal app and with a 'cat' command I can see the content of my sharedPreference XML file. Even when I kill my app I can see the sharedPreference file is still there with my correct value inside.
But when I restart my app this value can't be read. What is happening there ?
I've noticed on a tablet with android Lollipop I've no problem but with a tablet with android Kitkat I have this problem.
Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
So Dont forget to your editor.commit()
Best Way which I using :
Util.class
public static void saveIntToUserDefaults(Context c, String Key, int value) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(Key, value);
editor.commit();
Log.e("Saved:", "" + Key + "-" + value);
}
public static String getFromUserDefaults(Context c, String Key) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedpreferences.getString(Key, "");
}
public static void clearUserDefaults(Context c) {
SharedPreferences sharedpreferences = c.getSharedPreferences(Constant.PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.clear();
editor.commit();
}
I calling this wherever I need & its working superb
Got a problem with the Shared Preferences in Android - I want to be able to put some Strings (Save the IDs of a Picture) as favorite for the next launches - it works perfect, it recognizes if the ID is already inside the Shared Preferences and removes it if necessary, but when I stop the App by pressing the home button (without killing the app process) and then return to it, it doesn´t recognize it anymore. If I kill the process and restart the app, it works fine.
So here´s my code
MainActivity onCreate
preferences = getSharedPreferences("favo", MODE_PRIVATE);
edit = getSharedPreferences("favo", MODE_PRIVATE).edit();
MainActivity onResume
#Override
protected void onResume() {
preferences = getSharedPreferences("favo", MODE_PRIVATE);
edit = getSharedPreferences("favo", MODE_PRIVATE).edit();
super.onResume();
}
I´ve already tried to do it without onResume but it doesn´t change the result.
Method to change the Shared Preferences
if (checkTheSharedPreferences(numberFavo)){
v.setBackgroundResource(R.drawable.favo);
edit.putString(pref, pref);
edit.apply();
showIt = "Zu Favoriten hinzugefügt";
}else{
v.setBackgroundResource(R.drawable.favo2);
edit.remove(pref);
edit.apply();
showIt = "Aus Favoriten entfernt";
}
If my method to check if the SharedPreferences returns true it means that the String isn´t inside the SharedPrefs and can be added, otherwise it will be removed as the user wants to remove it from his favorites.
Method to check if the String is inside the Prefs
public Boolean checkTheSharedPreferences(int number) {
SharedPreferences preferences = getSharedPreferences("favo", MODE_PRIVATE);
Map<String, ?> map = preferences.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
if (entry.getValue().toString().equals(bilderIDs.get(number))) {
return false;
}
}
return true;
}
As mentioned above, it works perfect, unless the App gets invisible/into the background and is opened again without a restart.
Thanks in advance
EDIT
Seems like it works if I wait for about 30 seconds after onResume is called, but that´s not really a possibility to wait for so long as it is on the UI Thread and the User might presses the button to remove/add the SharedPref within the 30 seconds
SharedPreferences.Editor.apply() is a async method.It will store values in other thread.SharedPreferences.Editor.commit() is a sync method.
if (checkTheSharedPreferences(numberFavo)){
v.setBackgroundResource(R.drawable.favo);
edit.putBoolean("myfav" + numberFavo, true);
edit.commit();
showIt = "Zu Favoriten hinzugefügt";
}else{
v.setBackgroundResource(R.drawable.favo2);
edit.remove("myfav" + numberFavo);
edit.commit();
showIt = "Aus Favoriten entfernt";
}
public Boolean checkTheSharedPreferences(int number) {
SharedPreferences preferences = getSharedPreferences("favo", MODE_PRIVATE);
return preferences.getBoolean("myfav" + number,false);
}
#Override
protected void onResume() {
super.onResume();
preferences = getSharedPreferences("favo", MODE_PRIVATE);
edit = getSharedPreferences("favo", MODE_PRIVATE).edit();
}
Android issue with boolean on shared preferences
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSlide=spref.getBoolean("SLIDE_SHOW",false);
//in isSlide am getting the right value but the if statement is not working
if(isSlide==true){
//if true the page will slide but it works in false too
}
i tried in this link Issue with boolean on shared preferences but the answer is not clear
settings code:
<PreferenceCategory android:title="Slide Show" >
<CheckBoxPreference android:title="Slide Show" android:key="SLIDE_SHOW" />
</PreferenceCategory>
You may want to check if your SharedPreference variables are active. This is an example on how to set the SharedPreference.
To write into SharedPreference:
SharedPreferences prefs = getSharedPreferences("myPref", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("myBool", true);
editor.commit();
To read from SharedPreference:
SharedPreferences prefs = getSharedPreferences("myPref", 0);
if (prefs.getBoolean("myBool", false)) { //myBool is true; }
sorry i will not post the question correctly
The problem is not with preference it returns correct value the problem is in handler which is used to slide the viewpager based on the value which is returned by preference
the handler is running even though the activity is killed below the code solved my problem
SharedPreferences spref = PreferenceManager.getDefaultSharedPreferences(this);
boolean isSlide=spref.getBoolean("SLIDE_SHOW",false);
if(isSlide==true)
{
SlideShowTimer();
}
public void SlideShowTimer()
{
mFilterTask = new Runnable() {
#Override
public void run() {
int i=0;
itemPosition = viewPager.getCurrentItem() + 1;
if(itemPosition!=10)
{
if(i <= adapter.getCount()-1)
{
viewPager.setCurrentItem(itemPosition,true);
mHandler.postDelayed(mFilterTask, 3000);
i++;
}
}
else
{
//ViewPagerAdapter.mediaPlayer.stop();
ViewPagerActivity.this.finish();
}
}
};
mHandler.removeCallbacks(mFilterTask);
mHandler.postDelayed(mFilterTask,3000);
}
#Override
public void onDestroy(){
super.onDestroy();
mHandler.removeCallbacks(mFilterTask);
}
Hello I am writnig an Android app that has two preferences a checkbox and a preferencelist.
When the check box is marked as checked the preferencelist becomes enabled.
I have manage to save the checkbox "checked" status using putBoolean() method.
getPreferenceManager().getSharedPreferences().edit().putBoolean(key, boolean);
getPreferenceManager().getSharedPreferences().edit().commit();
But how do I save the isEnabled value so that when I leave and return it will not reset?
and how does putboolean knows to whice property to set the boolean anyway?
#Override
public void onPause() {
super.onPause();
save(l.isEnabled());
}
#Override
public void onResume() {
super.onResume();
l.setEnabled(load());
}
private void save(final boolean b) {
//what to put instead of key in order to save the preference list ENABLED sate??
getPreferenceManager().getSharedPreferences().edit().putBoolean(key, b);
getPreferenceManager().getSharedPreferences().edit().commit();
}
private boolean load(String key) {
return getPreferenceManager().getSharedPreferences().getBoolean(key, false);
}
The enabled state can be saved in the same way as you have saved the "checked" status, because isEnabled() returns a boolean.
SharedPreferences.Editor prefEditor = PreferenceManager.getDefaultSharedPreferences(this).edit();
prefEditor.putBoolean("prefs.preferenceList.enabled", preferenceList.isEnabled());
prefEditor.commit();
To then return the state you want to set the enabled state of the checkbox with setEnabled(). During onCreate you can do something like this.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
preferenceList.setEnabled(prefs.getBoolean("prefs.preferenceList.enabled", false);
getPreferenceManager().getSharedPreferences().edit().putBoolean(key, b);
getPreferenceManager().getSharedPreferences().edit().commit();
You should not be calling edit() a second time, as each time you call edit it creates a new instance of the preferenceEditor. Thus your putBoolean is never committed.
This should be
SharedPreferences.Editor prefs = getPreferenceManager()
.getSharedPreferences()
.edit();
prefs.putBoolean(key,b);
prefs.commit();