Save SWITCH button state, and recover state with SharedPrefs - android

I have a Settings class so the user can decide to subscribe/unsubscribe to channels in Parse Push.
I think I got it all figure out except for the part to recover, and maintain the switch state next time user open the app or changes the state.
Can someone please help me on how to save the state, and switch the SWITCH to what the user selected?
public class Settings extends Activity {
/**
* Called when the activity is first created.
*/
private Switch krspush, egspush;
public static final String PREFS_NAME = "SwitchButton";
krspush = (Switch) findViewById(R.id.krspush);
egspush = (Switch) findViewById(R.id.egspush);
SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE);
// How?
public void onKrsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onKrsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}
public void onEgsClick (View view) {
boolean on = ((Switch) view).isChecked();
if (on) {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", true);
editor.commit();
ParsePush.subscribeInBackground("egersund");
} else {
SharedPreferences.Editor editor = getSharedPreferences("SwitchButton", MODE_PRIVATE).edit();
editor.putBoolean("onEgsClick", false);
editor.commit();
ParsePush.unsubscribeInBackground("egersund");
}
}

Override the onCreate method of that activity class and attempt to load the values you saved in SharedPreferences.
krspush.setChecked(sharedPrefs.getBoolean("onKrsClick",false));

findviewbyid will crash unless called after the view is created ie, in the oncreate method.
Consider using click listener on your switches.
I don't see the point of this line of code "SharedPreferences sharedPrefs = getSharedPreferences("SwitchButton", MODE_PRIVATE)"
Here is how you use shared preferences : https://stackoverflow.com/a/23024962/2590252
You better look into some samples to learn about best coding practices http://developer.android.com/samples/index.html

Related

How to save (switch) button state in android?

I am using SWITCH (like android toggle button ) instead of normal buttons in my andorid app.
The code works fine while enabling and disabling switches.
But i want to store the state of the switch.
Suppose i enable the switch and close my application the background code will run fine but the switch state will change to disabled.
Every time when i close the application the switch state becomes disabled.
Is there any way to store the switch State??
Use shared preferences or a database to store the state of your switch. It is essential that you depend on the lifecycle methods of Activity/fragment.
The following might help you:
#Override
public void onClick(View v)
{
if (toggle.isChecked())
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("NameOfThingToSave", false);
editor.commit();
}
}
The final nail:
#Override
protected void onCreate(Bundle savedInstanceState)
{
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));
}
Edit:
The above code is working, however I feel it is a bad practice to get the shared preference values in onCreate, its better to make a loader class which inits your app variables well beforehand in a separate thread.
Update: Wed 24 Jul; 2019:
Android has view model support now - this can be used to handle switch state and persist it across sessions or configuration changes.
SharedPreferences pref = getSharedPreferences("save",MODE_PRIVATE);
unit.setChecked(pref.getBoolean("first", false));
if(isChecked) {
SharedPreferences.Editor editor = getSharedPreferences("save"MODE_PRIVATE).edit();
editor.putBoolean("first", true);
editor.apply();
unit.setChecked(true);}
else
{
SharedPreferences.Editor editor = getSharedPreferences("save",MODE_PRIVATE).edit();
editor.putBoolean("first",false);
editor.apply();
kilometer.setText("Km/h");
unit.setChecked(false);`enter code here`
}

Saving checkbox state using SharedPreferences

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

android: Shared Preferences only for active session (until it will be destroyed)

I've a music service which is steering my music with a checkbox. The checkbox states will be saved in my shared preferences correctly! Basic config = music at app start ON and checkbox ON too. So long all works fine!
I want to save these states ONLY in the active app session. After restarting my app, it should be the basic state (music and checkbox ON). In this code he starts with this state which was the last one.
Thx for ur help!
Java Code:
chkBoxMusic = (CheckBox) findViewById(R.id.checkBoxMusic);
boolean isChecked = getBooleanFromPreferences("isChecked");
chkBoxMusic.setChecked(isChecked);
chkBoxMusic.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonview, boolean isChecked) {
Log.i("boolean",""+isChecked);
ActivitySound.this.putBooleanInPreferences(isChecked,"isChecked");
if (!isChecked) {
stopService(new Intent(ActivitySound.this, MusicService.class));
}
else {
startService(new Intent(ActivitySound.this, MusicService.class));
}
}
});
}
public void putBooleanInPreferences(boolean isChecked,String key) {
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.commit();
}
public boolean getBooleanFromPreferences(String key) {
SharedPreferences sharedPreferences = this.getPreferences(Activity.MODE_PRIVATE);
Boolean isChecked = sharedPreferences.getBoolean(key, false);
return isChecked;
}
To remove all shared preferences:
SharedPreferences myPrefs = getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();
But exactly when to do that is still under negotiation - see comments above! It's not entirely clear what you want even now. You could try putting this in the onStop method of your Activity and seeing if that gives the results you want.

How to save the state of the toogleButton on/off selection?

Hello i have implemented the application based on the toggleButton selection. but while i close that application and then reopen it, it will get in to its default selection that is "off".
So can any budy tell mw what should i have to save the state of the toogleButton selection and perform some action based on that toggleButton selection state. . .
Thanks.
Use SharedPreferences.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if((tg.isChecked()))
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
}
else
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", false); // value to store
editor.commit();
}
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
if (tgpref = true) //if (tgpref) may be enough, not sure
{
tg.setChecked(true);
}
else
{
tg.setChecked(false);
}
I did not verify this code, but look at some examples on the net, it is easy!
Use SharedPreferences like erdomester suggested, but I modified little bit his code. There's some unneeded conditions.
tg = (ToggleButton) findViewById(R.id.toggleButton1);
tg.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", tg.isChecked()); // value to store
editor.commit();
}
});
And this is how to retrieve the values:
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean tgpref = preferences.getBoolean("tgpref", true); //default is true
tg.setChecked(tgpref);
The best way, you can set tgbutton same
screen main
Intent intent = new Intent(this, Something.class);
intent.putExtra(BOOLEAN_VALUE, Boolean.valueOf((tvConfigBoolean.getText().toString())));
startActivity(intent);
screen something
Bundle bundle = getIntent().getExtras();
tbtConfigBoolean.setChecked((bundle
.getBoolean(MainActivity.BOOLEAN_VALUE)));
and save state
editor.putBoolean("BooleanKey", tbtConfigBoolean.isChecked());
editor.commit();
good luck

how to reset all stored data store using shared preferences

I have created an activity where i have used shared preferences for storing data..now in another activity i have an reset button..when i click on the reset button the data store will be lost..so how that can be done..my code is
code in activity1:
public void writeToRegister()
{
// Write history data to register
SharedPreferences preferences1 = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor1 = preferences1.edit();
editor1.putInt("iHistcount", CycleManager.getSingletonObject().iHistCount);
for(int i=0;i< CycleManager.getSingletonObject().iHistCount;i++)
{
editor1.putLong("dtHistoryDate"+Integer.toString(i), CycleManager.getSingletonObject().dtHistory[i].getTime());
}
editor1.commit();
}
public void readFromRegister()
{
// Read history data from register
SharedPreferences preferences1 = getPreferences(MODE_PRIVATE);
CycleManager.getSingletonObject().iHistCount=preferences1.getInt("iHistcount", 0);
for(int i=0;i< CycleManager.getSingletonObject().iHistCount;i++)
{
Long x=preferences1.getLong("dtHistoryDate"+Integer.toString(i), 0L);
CycleManager.getSingletonObject().dtHistory[i]=new Date(x);
}
}
code for Activity 2:
Button pBtnReset = new Button(this);
pBtnNextMonth.setOnClickListener(pBtnReset OnClickListener);
Button.OnClickListener pBtnReset OnClickListenernew Button.OnClickListener()
{
public void onClick(View arg0)
{
}
};
so what i have to write in second activity reset button so that it clear the stored data
Get your Editor and call clear() something like this:
Edit: as the user DDoSAttack mentioned.
There are two ways of getting SharedPreferences
1: getting default SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
2: getting specific SharedPreferences
SharedPreferences prefs = Context.getSharedPreferences("FileName", Context.MODE_PRIVATE);
and here is how you'll clear it.
public void clear()
{
SharedPreferences prefs; // here you get your prefrences by either of two methods
Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
its very easy..
yourEditor.remove(" thing you want to remove on start");
and then give must
yourEditor.commit();
If you want to wipe all the data in a preference file call clear() from the SharedPreferences.Editor instance
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear()
Use SharedPreferences.Editor clear() method.
See Documentation
SharedPreferences preferences = getPreferences(0);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();

Categories

Resources