I am very new and would appreciate if someone could demonstrate the code required to save a number of checkbox states in java inside of an android application.
Say i have a list of tools (Ten or more) a user needs to complete a task and would like them to be able to check off each one and have that data saved (within the app, not sQlite) so that it is recorded when they return to the application.
I have some idea of how this is done but really feel like i need to see the code to understand correctly.
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.CheckBox;
public class CheckBoxTest extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.checkboxtest);
CheckBox cb1,cb2,cb3,cb4;
cb1 = (CheckBox)findViewById(R.id.checkBox1);
cb2 = (CheckBox)findViewById(R.id.checkBox2);
cb3 = (CheckBox)findViewById(R.id.checkBox3);
cb4 = (CheckBox)findViewById(R.id.checkBox4);
}
}
Use the below code to store and retrive the data in SharedPreference. Your save each check box state in SharedPreference
//To get value from SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
boolean value = preferences.getBoolean("KEY", false);
String value = preferences.getString("KEY");
//To Save value in SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KEY", value);
editor.putBoolean("KEY", value);
editor.commit();
look into it few minor changes::::
public class CheckBoxTest extends Activity implements OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_add_button);
CheckBox cb1,cb2,cb3,cb4;
cb1 = (CheckBox)findViewById(R.id.checkBox1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.checkBox2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.checkBox3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.checkBox4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
switch(buttonView.getId()){
case R.id.checkBox1:
saveInSp("cb1",isChecked);
break;
case R.id.checkBox2:
saveInSp("cb2",isChecked);
break;
case R.id.checkBox3:
saveInSp("cb3",isChecked);
break;
case R.id.checkBox4:
saveInSp("cb4",isChecked);
break;
}
}
}
Hi I tried the above but after rebooting or restarting my android device, I would lose the checked state of the options menu. I'd say, to solve the problem:
You have 2 options:
Get shared preference value during the life-cycle of the activity.
Call .clear before .commit
See my answer:
Android Persistent Checkable Menu in Custom Widget After Reboot Android
Related
I have a couple of check boxes that I need to save so that when the user opens the Application again, they can see the state that they left the application in. I have tried using the preferences but I can't seem to get the result correctly.
MainActivity.java
package com.example.android.documentchecklist;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
public class MainActivity extends AppCompatActivity {
CheckBox allotment, sscMarkList, hscMarkList, leaving, profomaCap, jeeScoreCard, gapCer, casteCer, casteVal, nonCreamyL, domicileCertificate, photograph, migration, adhaarCard, nationalityCertificate;
boolean hasAllotment, hasSscMarkList, hasHscMarkList, hasLeaving, hasProfoma, hasJeeScore, hasGapCertificate, hasCasteCertificate, hasCasteValidity, hasNonCreamyLayer, hasDomicileCertificate, hasPhoto, hasMigCertificate, hasadhaarCard, hasNationalityCertificate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
allotment = (CheckBox) findViewById(R.id.allot);
sscMarkList = (CheckBox) findViewById(R.id.ssc);
hscMarkList = (CheckBox) findViewById(R.id.hsc);
leaving = (CheckBox) findViewById(R.id.leaving);
profomaCap = (CheckBox) findViewById(R.id.profoma);
jeeScoreCard = (CheckBox) findViewById(R.id.jeeScore);
gapCer = (CheckBox) findViewById(R.id.gapCertificate);
casteCer = (CheckBox) findViewById(R.id.casteCertificate);
casteVal = (CheckBox) findViewById(R.id.casteValidity);
nonCreamyL = (CheckBox) findViewById(R.id.nonCreamyLayer);
adhaarCard = (CheckBox) findViewById(R.id.adhaarCard);
nationalityCertificate = (CheckBox) findViewById(R.id.nationalityCer);
domicileCertificate = (CheckBox) findViewById(R.id.domicile);
photograph = (CheckBox) findViewById(R.id.photo);
migration = (CheckBox) findViewById(R.id.migration);
}
public void checkBoxClicked(View view) {
int id = view.getId();
if (id == R.id.mahaState) {
migration.setVisibility(View.GONE);
allotment.setText(getString(R.string.allot));
allotment.setVisibility(View.VISIBLE);
hasAllotment = allotment.isChecked();
sscMarkList.setText(getString(R.string.ssc));
sscMarkList.setVisibility(View.VISIBLE);
hasSscMarkList = sscMarkList.isChecked();
hscMarkList.setText(getString(R.string.hsc));
hscMarkList.setVisibility(View.VISIBLE);
hasHscMarkList = hscMarkList.isChecked();
leaving.setText(getString(R.string.leaving));
leaving.setVisibility(View.VISIBLE);
hasLeaving = leaving.isChecked();
profomaCap.setText(getString(R.string.proforma));
profomaCap.setVisibility(View.VISIBLE);
hasProfoma = profomaCap.isChecked();
jeeScoreCard.setText(getString(R.string.jee));
jeeScoreCard.setVisibility(View.VISIBLE);
hasJeeScore = jeeScoreCard.isChecked();
gapCer.setText(getString(R.string.gap_cert));
gapCer.setVisibility(View.VISIBLE);
hasGapCertificate = gapCer.isChecked();
casteCer.setText(getString(R.string.caste_cert));
casteCer.setVisibility(View.VISIBLE);
hasCasteCertificate = casteCer.isChecked();
casteVal.setText(getString(R.string.caste_validity));
casteVal.setVisibility(View.VISIBLE);
hasCasteValidity = casteVal.isChecked();
nonCreamyL.setText(getString(R.string.non_creamy));
nonCreamyL.setVisibility(View.VISIBLE);
hasNonCreamyLayer = nonCreamyL.isChecked();
adhaarCard.setText(getString(R.string.aadhar));
adhaarCard.setVisibility(View.VISIBLE);
hasadhaarCard = adhaarCard.isChecked();
nationalityCertificate.setText(getString(R.string.nationality_cert));
nationalityCertificate.setVisibility(View.VISIBLE);
hasNationalityCertificate = nationalityCertificate.isChecked();
domicileCertificate.setText(getString(R.string.domicile));
domicileCertificate.setVisibility(View.VISIBLE);
hasDomicileCertificate = domicileCertificate.isChecked();
photograph.setText(getString(R.string.photos));
photograph.setVisibility(View.VISIBLE);
hasPhoto = photograph.isChecked();
}
}
#Override
public void onPause() {
super.onPause();
save(allotment.isChecked());
save(sscMarkList.isChecked());
save(hscMarkList.isChecked());
save(leaving.isChecked());
save(profomaCap.isChecked());
save(jeeScoreCard.isChecked());
save(gapCer.isChecked());
save(casteCer.isChecked());
save(casteVal.isChecked());
save(nonCreamyL.isChecked());
save(domicileCertificate.isChecked());
save(photograph.isChecked());
save(migration.isChecked());
save(adhaarCard.isChecked());
save(nationalityCertificate.isChecked());
}
#Override
public void onResume() {
super.onResume();
allotment.setChecked(load());
sscMarkList.setChecked(load());
sscMarkList.setChecked(load());
hscMarkList.setChecked(load());
leaving.setChecked(load());
profomaCap.setChecked(load());
jeeScoreCard.setChecked(load());
gapCer.setChecked(load());
casteCer.setChecked(load());
casteVal.setChecked(load());
nonCreamyL.setChecked(load());
domicileCertificate.setChecked(load());
photograph.setChecked(load());
migration.setChecked(load());
adhaarCard.setChecked(load());
nationalityCertificate.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.apply();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", false);
}
}
Thank You for your help.
you are using the single key i.e. check to store your all checkbox state so only the state of this call save(nationalityCertificate.isChecked()); will be saved ,so you need to use different keys for different checkboxes
for example
// use different keys to store state of different check boxes
save(allotment.isChecked(),"allotment");
save(sscMarkList.isChecked(),"sscMarkList");
// use same keys to fetch values which were used during save function call
allotment.setChecked(load("allotment"));
sscMarkList.setChecked(load("sscMarkList"));
private void save(final boolean isChecked, String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, isChecked);
editor.apply();
}
private boolean load(String key) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, false);
}
Note: you can also initialize your shared preference like your CheckBox views in onCreate or onStart only once instead of re-initializing it every time in save
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));
}
I have created a settings activity and I want to save the Switch Button with SharedPreferences, but I get a error (see title) when I start the Activity:
The error is in line 13.
The Code:
public class SettingsActivity extends Activity {
private Switch switchPushNotifications;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences sharedPreferences = getSharedPreferences("Settings", MODE_PRIVATE);
switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true));
switchPushNotifications = (Switch) findViewById(R.id.switchPush);
switchPushNotifications.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.d("PN", "Push Notifications are currently ON");
Pushbots.sharedInstance().setPushEnabled(true);
Pushbots.sharedInstance().register();
SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
sharedPreferencesEditor.putBoolean("getPushNotifications", true);
sharedPreferencesEditor.commit();
}
else {
Log.d("PN", "Push Notifications are currently OFF");
Pushbots.sharedInstance().setPushEnabled(false);
Pushbots.sharedInstance().unRegister();
SharedPreferences.Editor sharedPreferencesEditor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
sharedPreferencesEditor.putBoolean("getPushNotifications", false);
sharedPreferencesEditor.commit();
}
}
});
}
}
Thanks!
All you need to do is swap these two lines (change their order):
switchPushNotifications.setChecked(sharedPreferences.getBoolean("getPushNotifications", true));
switchPushNotifications = (Switch) findViewById(R.id.switchPush);
You should first initialize it, and then use it. This way you're trying to access a method on something that's still null and thus the NullPointerException.
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"));
}
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.