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();
Related
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
how does one save a clicked state in android listview after exiting the app and restore state on app launch.The app should be able to listen to click event on listview and save the state and when the app is closed it saves the clicked state and then restore it on relaunch.
i have tried using getView but it doesnt seem to work as expected. please help
What you have to do is, you have to override the below method in your Activity,
#Override
public void onBackPressed() {
super.onBackPressed();
}
And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.
Example,
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
onCreate(Bundle savedInstanceState){
LoadPreferences();
//just a rough sketch of where you should load the data
}
I am currently working with SharedPreferences in Android, and I encountered a weird behavior I cannot explain. This is my code:
SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
appPreferences.edit().putBoolean("launched_before", true);
appPreferences.edit().apply();
appPreferences = null;
appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean test = appPreferences.getBoolean("launched_before", false); //this is false
The value that I write to my SharedPreferences is not being saved. I know I could use getDefaultSharedPreferences(), but I do not want to do this here, as the default file stores other values.
When I use commit() instead of apply(), the return value of commit() is true, but I still cannot load the file correctly.
This happens because your code doesn't do what you think. When you call edit(), it does not start an "edit transaction". Instead it returns a new instance of Editor object each time you call it. So let's look at this code:
SharedPreferences appPreferences = getSharedPreferences("settings", Context.MODE_PRIVATE);
// Here you create a FIRST Editor object, which stores the modification
// You never call apply() on this object, and thus your changes are dropped.
appPreferences.edit().putBoolean("launched_before", true);
// Here you create a SECOND Editor object (which has no modifications)
// and you call apply() on it, thus changing nothing.
appPreferences.edit().apply();
You created the first editor object which you put settings in, but you called apply on the second editor object which had no changes. Since you never called apply() on the editor object which had modification, your change was never saved.
The fix is obvious - use a single instance of Editor for your modification, and call apply/commit on this instance:
SharedPreferences appPreferences = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = appPreferences.edit();
ed.putBoolean("launched_before", true);
ed.apply();
Here you can use as key "com.yourdomain.yourapp.your_key_name" and for each value use another key...try this
private SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(appContext);
public void putBoolean(String key, boolean value) {
checkForNullKey(key);
preferences.edit().putBoolean(key, value).apply();
}
public boolean getBoolean(String key) {
return preferences.getBoolean(key, false);
}
public void checkForNullKey(String key){
if (key == null){
throw new NullPointerException();
}
}
My question is "Is there any way to save state of activity, that can be used when application has been restart.".
In my application, I had been override onSaveInstanceState and onRestoreInstanceState to save and restore my instance state.
I also used SharedPreferences to save the state. But I found that SharedPreference has been clear when I pressed Back Buttaon and restart my application.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(USER_NAME, name.getText().toString());
editor.putInt(COUNT_STATE, count);
editor.commit();
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
name.setText(pref.getString(USER_NAME, ""));
count = pref.getInt(COUNT_STATE, 0);
}
I also know that this problem has been solved if I used external or local storage.
I want to know that can I persist application state without using file or database.
at onBackPressed() you need to store your state
and when activity created onCreate() you need to restore it
private void saveMyState(){
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(USER_NAME, name.getText().toString());
editor.putInt(COUNT_STATE, count);
editor.commit();
}
private restoreMyState(){
SharedPreferences pref = getSharedPreferences(MY_APP, MODE_PRIVATE);
name.setText(pref.getString(USER_NAME, ""));
count = pref.getInt(COUNT_STATE, 0);
}
#Override
public void onBackPressed() {
saveMyState();
super.onBackPressed();
}
#Override
public void onCreate(Bundle savedInstanceState){
//init views, buttons, textViews (findViewById)...
//do other works ...
//:
//:
//then try to restore state (if saved)
restoreMyState();
}
if you want you can do the same call saveMyState() and restoreMyState() at
onSaveInstanceState() and onRestoreInstanceState() in case of orientation changed
i think this will cover all the cases you want.
PS: using SharedPreferences will write/read to a file, under the hood so you are already using file if you are using SharedPreferences
For my question, I try to change behavior of Pressed Back Button by overring onBackPressed.
In this method I write moveToBackTask(true).
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
My application state has been restored when I pressed back button and restart application.
But I think that this state can't be restored when I restart my device.
Do I need to store my state in a file?
how do i save a checkbox state in activity B so that when i go back to activity A , it will show an appropriate response?
I am trying to make a function such that when a checkbox state in Activity B is checked , it will go back to A and play music , and this preference will be saved so that when the app is killed and relaunched , the preference stays.
You can save a boolean in SharedPreferences. It's clearly explained here: http://developer.android.com/training/basics/data-storage/shared-preferences.html
On Activity B you need to set preference depends on the CheckBox state
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences("mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("checked", isChecked);
editor.commit();
}
});
On Activity A you need to get the preference value as follow
SharedPreferences sharedPref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
boolean isChecked = sharedPref.getBoolean("checked", false); // false if it's not exist
Implement OnSharedPreferenceChangeListener in your activity B and override onSharedPreferenceChanged method
Here's my code
#Override
public void onSharedPreferenceChanged(SharedPreferences preferences,String arg1) {
// TODO Auto-generated method stub
preferences = PreferenceManager.getDefaultSharedPreferences(this);
checkbox = preferences.getBoolean("checkbox", false);
if(checkbox){
//Do your stuff here like playing music
Log.d("checkbox", "check enabled");
Intent myIntent = new Intent(ActivityB.this, ActivityA.class);
startActivity(myIntent);
}