maintain check and uncheck mark even app get closed - android

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.

Related

checkboxes getting checked in android

I am trying to check a checkbox and keep its state to checked until it gets unchecked but as soon as I close the dialog containing the checkboxes and come back to it, all the checkboxes are checked instead of the selected one. I have tried the following way
private void saveCheckboxState(int index1, int index2, boolean isChecked)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkbox" + index1 + index2, isChecked);
editor.apply();
}
private boolean getCheckboxState(int index1, int index2)
{
SharedPreferences prefs = PreferenceManager. getDefaultSharedPreferences(this);
return prefs.getBoolean("checkbox" + index1 + index2, false);
}
boolean checkbox_success;
case R.id.menu_checkboxes:
Dialog s_dialog = new Dialog(this);
s_dialog.setContentView(R.layout.s_dialog);
checkbox_layout = s_dialog.findViewById(R.id.checkbox_layout);
layoutParams.setMargins(20,20,20,20);
s_dialog.show();
title = s_dialog.findViewById(R.id.dialog_title);
title.setText("select option ");
for (int i = 0; i < 5; i++) {
CheckBox checkBox = new CheckBox(this);
checkBox.setId(groupIndex);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
checkbox_success = true;
boolean success = db.update(String.valueOf(items.getId())
);
}
});
checkbox_layout.addView(checkBox);
}
}
Is there any way I can get it to check only the selected items? Thanks for help.
> This is what I suggest you do.
Create an Int variable and assign a value == 1 to it when checkBox is Checked, so when Dialog is recreated/created you check if isChecked == 0 or 1 and change the status of the checkBox based on the result, view the code below.
var isChecked: Int = 0
Dialog.....//isCreated
if(isChecked == 1)
//set checkBox isChecked = true
else //set checkBox isChecked = false
CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
boolean checked = PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("checkBox1", false);
checkBox1.setChecked(checked);
Try this method using sharedPreference.
Will give an example how to save checkbox states in shared preferences and to read them back.
Code is only for one loop.
You have to realise that if you have two loops you should use two indexes to store a state.
private void saveCheckboxState(int index, boolean isChecked)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkbox" + index, isChecked);
editor.commit();
}
private boolean getCheckboxState(int index)
{
SharedPreferences prefs = PreferenceManager. getDefaultSharedPreferences(context);
return prefs.getBoolean("checkbox" + index, false);
}
At building your dialog call getCheckboxState().
Call saveCheckboxState() in the on change handler.
For two loops you only have to adapt the functions with another index.
For instance it would become private void saveCheckboxState(int index1,int index2, boolean isChecked)` then.
I suggest you code the functions for two indexes and post your code here.

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

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

Save multiple checkbox states

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...

Categories

Resources