Save multiple checkbox states - android

I've used this code to get one checkbox saved for when the user returns, but I need to have many checkboxes throughout the application. I'm sure the best way isn't to copy and paste this code, but can't seem to find what it is.
What would I add or change to make this work with say 10 or more checkboxes?
#Override
public void onPause() {
super.onPause();
save(mCheckBox.isChecked());
}
#Override
public void onResume() {
super.onResume();
mCheckBox.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}

private void save (final String checkboxId, final boolean isChecked) {
// shared prefs yadda
editor.putBoolean(checkboxId, isChecked).commit();
}
Or create a schema of your own (SQLite, etc) and persist that way. In any case, every unique checkbox needs to have a unique id in the persistent store.

You could store your CheckBoxes in an array.
#Override
public void onPause() {
for (int i = 0; i < checkBoxArr.length; i++) {
save(i, checkBoxArr[i].isChecked());
}
}
private void save(int index, boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check" + index, isChecked);
editor.commit();
}
// etc...

Related

How saving the state of a switch

I am developing a game on Android, I have a background music that stop with a switch and that is in an other activity, that of the parameters. The music is in the main menu.
I would like to know how to save the state of the switch (checked or not checked) by going from the main menu to the parameters
This the code for my switch :
buttonmusique = (Switch) findViewById(R.id.switchMusique);
buttonmusique.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("bouton", String.valueOf(buttonmusique.isChecked()));
// If the music is playing
if (isChecked) {
Intent music = new Intent();
music.setClass(Parametres.this, BackgroundMusic.class);
startService(music);
musicBoolean = true;
buttonmusique.setText("Musique On"); //To change the text near to switch
Log.d("You are :", "Checked");
} else {
Intent music = new Intent();
music.setClass(Parametres.this, BackgroundMusic.class);
stopService(music);
musicBoolean = false;
// Resume the music player
buttonmusique.setText("Musique OFF"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
Put it in your create method: (+adapt to your situation)
final SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
CheckBox checkbox = (CheckBox) findViewById(R.id.myCheckBox);
checkbox.setChecked(sharedPreferences.getBoolean("mycheckbox", true));
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
sharedPreferences.edit().putBoolean("mycheckbox", b).apply();
}
});
You can save it in SharedPreferences.
SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
Save sound settings
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(getString(R.string.sound_enabled), isChecked);
editor.commit();
To get sound settings use:
boolean soundEnabled = prefs.getBoolean(getString(R.string.sound_enabled), false);
// Set switch state
buttonmusique.setChecked(soundEnabled);
Load status:
boolean switch_status = PreferenceManager.getDefaultSharedPreferences(ctx).getBoolean("switch_status", false);
Save status:
SharedPreferences.Editor sped = PreferenceManager.getDefaultSharedPreferences(ctx).edit();
sped.putBoolean("switch_status", value);
sped.commit();
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("state_to_save", true);
editor.commit();
}
else
{
SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
editor.putBoolean("state_to_save", false);
editor.commit();
}
}
The final Code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
.......
......
SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
toggle.setChecked(sharedPrefs.getBoolean("state_to_save", true));
}

How to apply shared preference to checkbox

I am new to android development I created a checkbox and how to save check/uncheck using share preference
final Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
addNewBubble();
add.setEnabled(false);
}
});
CheckBox checkBox = (CheckBox)findViewById(R.id.add_fb);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
}
});
}
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
There are two Check boxes in this code add and add_fb I want to make the app remember if the checkbox are checked or unchecked
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CheckBox checkBox = (CheckBox)findViewById(R.id.checkBox);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
if(preferences.contains("checked") && preferences.getBoolean("checked",false) == true) {
checkBox.setChecked(true);
}else {
checkBox.setChecked(false);
}
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(checkBox.isChecked()) {
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
});
}
final String FILE_NAME = "com.myproject.prefs";
final Boolean ADD = "add";
final Boolean ADD_FB = "add_fb";
// prefs file..
SharedPreferences prefs = getSharedPreferences(FILE_NAME, Activity.PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
// by default both will be unchecked..
checkBoxAdd.setChecked(prefs.getBoolean(ADD, false);
checkBoxAddFb.setChecked(prefs.getBoolean(ADD_FB, false);
// now on checkedchancedEvent update the preferences
checkBoxAdd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean(ADD, isChecked);
editor.apply();
}
});
// similary the second one...
checkBoxAddFb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean(ADD_FB, isChecked);
editor.apply();
}
});
Updated
Here we store our preferences in a file of name "com.myproject.prefs". We need to store two preferences values of Boolean data type (one is add, another one is add_fb, as given in the Q).
Now get SharePreferences and its editor objects.
Set values of checkBoxes from stored preferences, if the preferences were not added before then set these to false. So, on the very first time when you run your app, these will get false values as there aren't any values added before.
Whenever you want to get these preferences values
pass your preferences file_name and mode to getSharedPreferences();
// then use those objects to get any specific value like
prefs.getBoolean(your_value_name, default_value); Already mentioned above
Whenever you want to change these preferences values use SharedPreferences.Editor object. Pass your value name and it's new value to
putBoolean().
like
editor.putBoolean(your_value_name, true/false);
then apply the editing.
Hope, it helps

Boolean Shared Preference is not storing

I am working on an Android game, in which in settings there is an option to turn off/on the sound of game.
I want to store these settings for the game, for this i am using shared preference to store a boolean value.
but issue is Boolean variable is not saving after app is closed.
here is my Code
Button Click Listener which is setting the SharedPreference
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check == false) {
check = true;
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF, Constants.FIRSTTIME, true);
volume.setBackgroundResource(R.drawable.mute);
Log.e("Check is True", "Preference is True");
} else if (check == true) {
check = false;
volume.setBackgroundResource(R.drawable.volume);
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF,Constants.FIRSTTIME, false);
Log.e("Check is false", "Preference is false");
}
Toast.makeText(getApplicationContext(), "Volume is Clicked",
Toast.LENGTH_SHORT).show();
}
});
My function to set the boolean SharedPreference
public static final void setBoolPreference(Context base, String prefName,
String key, boolean value) {
SharedPreferences userPref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userPref.edit();
editor.putBoolean(key, value);
editor.commit();
}
This is how i am getting the SharedPreference
public static final boolean getBoolPreference(Context base,
String prefName, String key) {
SharedPreferences usePref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
boolean value = usePref.getBoolean(key, false);
return value;
}
and this is the code where i need to use the sharedpreference saved state to play sound or not
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.stronghold);
if (PrefrencesClass.getBoolPreference(context, Constants.APPSPREF,
Constants.FIRSTTIME) == false) {
mPlayer.start();
mPlayer.setLooping(true);
}
Boolean state is not saving Please Help
Try this
public static void saveBooleanToSharedPref(Context context, String key, boolean value){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.commit();
}//saveBooleanToSharedPref
public static boolean getBooleanBySharedPref(Context context, String key){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean value = settings.getBoolean(key, true);
return value;
}//getStringBySharedPref
Your set is wrong, because you use putInt method.
You should be able to say:
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = !check // avoids if statements, same below
SharedPreferences prefsget = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor prefset = prefsget.edit();
prefset.putBoolean(yourBoolVar, !prefsget.getBoolean(yourBoolVar, false));
prefset.commit();
}
});
You can still put an if statement for setting image background. But the what I have above should cut down on a lot of your code. Remember to replace the activity I typed above with your own activity and also for the boolean variable too.

Sharedpreferences doesnt work, checkbox should stay in the same state when I am closing/opening the app

Hey guys I want to make my checkbox stay in the same state every time I open my app.. I get this with the 'ja/nein' string, the string states when i close and open again my application... but my checkbox.setchecked(true/false) doesnt work.. please help
public void changeVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
SharedPreferences.Editor editor = visitStatus.edit();
if(visitStatus.getString(mData.getVisitKey(), "nein").equals("nein")){
editor.putString(mData.mVisitKey, "ja");
editor.commit();
mGUI.mBtnVisit.setChecked(true);
}
else{
editor.putString(mData.mVisitKey, "nein");
editor.commit();
mGUI.mBtnVisit.setChecked(false);
}
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}
EDIT: I tried it another way.. I thought it would be better but doesnt work as well..
public void changeVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
SharedPreferences.Editor editor = visitStatus.edit();
if(visitStatus.getString(mData.getVisitKey(), "nein").equals("nein")){
editor.putString(mData.mVisitKey, "ja");
editor.putBoolean("isChecked", true);
editor.commit();
}
else{
editor.putString(mData.mVisitKey, "nein");
editor.putBoolean("isChecked", false);
editor.commit();
}
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}
and put this one into my onCreate(Bundle savedInstanceState) in my Activity
mGUI.mBtnVisit.setChecked(mData.getVisitStatus().getBoolean("isChecked", false));
Try like this:
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;
}
and in onCreate()
CheckBox checkBox = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBox = (CheckBox) findViewById(R.id.my_check_box);
boolean isChecked = getBooleanFromPreferences("isChecked");
Log.i("start",""+isChecked);
checkBox.setChecked(isChecked);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
Log.i("boolean",""+isChecked);
TestActivity.this.putBooleanInPreferences(isChecked,"isChecked");
}
});
}
Hope this may help you!
You're showing us only the code for changing the status, probably called from OnClick listener for the check box.
You should also add code that only reads status from SharedPreferences and sets check box state according to that (could be same code, but the if condition negated).
You need to call that code from OnCreate event.
public void setVisitStatus(){
SharedPreferences visitStatus = mData.getVisitStatus();
mGUI.getVisitStatus().setText(visitStatus.getString(mData.mVisitKey, "Nein"));
}

maintain check and uncheck mark even app get closed

i want to make 4 different button as check and un check even after the app get closed,i am using shared preferences for that but i cant able to maintain the state,its confusing me.can anyone help me.
Thank you
preferences1 = PreferenceManager
.getDefaultSharedPreferences(Notification_Dashboard.this);
Boolean state_chk = preferences1.getBoolean("key", false);
System.out.println("state_chk" + state_chk);
if (state_chk == true) {
msg_viewed = "0";
message_view.setBackgroundResource(R.drawable.notif_uncheck);
preferences1.edit().putBoolean("key", false).commit();
}
else {
msg_viewed = "1";
message_view.setBackgroundResource(R.drawable.notif_checked);
preferences1.edit().putBoolean("key", true).commit();
}
You could try something like this :
For your checkbox define the checkedchanged listner as below:
yourcheckbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
saveCheckBox("First",true);
} else {
saveCheckBox("First",false);
}
}
});
Save checkbox value in sharedpreference
public void saveCheckBox(String key, boolean isChecked){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key,isChecked);
editor.commit();
}
Get the preference values
public boolean getCheckBoxState(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();
prefs.getBoolean(key, false);
}
In your activity onCreate() method try to get sharedpreference value and set the checkbox checked or uncheck as below:
Boolean isCheck=getCheckBoxState("First");
if(isCheck)
{
yourcheckbox.setChecked(true);
}
else
{
yourcheckbox.setChecked(false);
}
I hope this will help you.
Thanks.

Categories

Resources