Boolean Shared Preference is not storing - android

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.

Related

Is it possible to save void in SharedPreferences

I have a button which changes the color of the MainActivity but this works only if the app it is open if I exit the app and open again it return to normal color which is white.
How to store with Shared Preferences do you have any idea how to do that because strings, int and boolean I can save but this function I don' have any idea.
This is my code.
MainActivity.class
public static final String Change_Color = "Change_Color";
private boolean switchOnOff;
setContentView(R.layout.activity_main);
if (switchOnOff == true) {
setColorGreyImageButton();
} else if(switchOnOff == false) {
setColorWhiteImageButton();
}
if(id == R.id.menu_back_white) {
saveColor();
} else if (id == R.id.menu_back_black) {
saveColor2();
}
public void setColorGreyImageButton() {
settings.setColorFilter(Color.parseColor("#757575"));
voiceSearch.setColorFilter(Color.parseColor("#757575"));
share.setColorFilter(Color.parseColor("#757575"));
search.setColorFilter(Color.parseColor("#757575"));
mainView.setBackgroundColor(Color.parseColor("#FFFFFF"));
SharedPreferences in MainActivity
public void saveColor() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Change_Color, false);
switchOnOff = sharedPreferences.getBoolean(Change_Color, false);
}
public void saveColor2() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Change_Color, true);
switchOnOff = sharedPreferences.getBoolean(Change_Color, true);
}
Use these methods in your activity class:
private boolean getChangeColor() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
return sharedPreferences.getBoolean(getPackageName() + ".change_color", false);
}
private void saveChangeColor(boolean changeColor) {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getPackageName() + ".change_color", changeColor);
editor.apply();
}
In onCreate() check the boolean value stored in SharedPreferences:
switchOnOff = getChangeColor();
if (switchOnOff) {
setColorGreyImageButton();
} else {
setColorWhiteImageButton();
}
and when you want to change the value in SharedPreferences call:
saveChangeColor(true);
or
saveChangeColor(false);

How to Store toogle button status in shared preference and load the status later in android?

The thing is I want to store my toogle button status in shared preference, so that I when I return to the application my toogle button wil stay in previous state. This is kind of something Do you want to use this. If user make the button enable that means when he return it will show the button will enable. So far I did is
tb_vibrate = (ToggleButton)this.findViewById(R.id.tb_vibrate);
tb_vibrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(tb_vibrate.isChecked())
{
Toast.makeText(ProfileActivity.this, "Toggle button is on", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(true);
}
else {
Toast.makeText(ProfileActivity.this, "Toggle button is Off", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(false);
}
}
});
And this is my SharePreference class
public class NotificationManager {
private static final String PREFS_FILE_NAME = "AppNotificationManager";
private static final String VIBRATE = "vibrate";
private static final String NOTIFICATION_ALERT = "notification_alert";
private static final String NOTIFICATION_SOUND = "notification_sound";
private static final String CALL_RINGTONE = "call_ringtone";
private static final String RINGTONE_VIBRATION = "ringtone_vibrate";
public static void setVibrate(final Context ctx, final String vibrate) {
final SharedPreferences prefs = ctx.getSharedPreferences(NotificationManager.PREFS_FILE_NAME, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString(NotificationManager.VIBRATE, vibrate);
editor.commit();
}
public static String getVibrate(final Context ctx) {
return ctx.getSharedPreferences(NotificationManager.PREFS_FILE_NAME,
Context.MODE_PRIVATE).getString(NotificationManager.VIBRATE, "");
}
}
So how to create my shared preference class for storing the data and use it later?
you can use SharedPreferences to store state of your ToggleButton
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
Sample code
SharedPreferences sp=getSharedPreferences("Login", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit()
tb_vibrate = (ToggleButton)this.findViewById(R.id.tb_vibrate);
tb_vibrate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(tb_vibrate.isChecked())
{
Toast.makeText(ProfileActivity.this, "Toggle button is on", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(true);
Ed.putBoolean("ISCHECKED",true);
Ed.commit();
}
else {
Toast.makeText(ProfileActivity.this, "Toggle button is Off", Toast.LENGTH_LONG).show();
tb_vibrate.setChecked(false);
Ed.putBoolean("ISCHECKED",false);
Ed.commit();
}
}
});
getting values use the below code
SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
boolean flag = preferences.getBoolean("ISCHECKED", false);
if(flag){
tb_vibrate.setChecked(true);
}else {
tb_vibrate.setChecked(false);
}

Remember click in Android

I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.

Shared Prefference is not saving the data

I am storing the status of togglebutton using a sharedpreffrence.
I am putting "ON" if toggle button is checked and "OFF" if toggle button is unchecked.
But when I am retriveing the status , it always returns "ON"
Here is the code
SharedPreferences.Editor shfEditMessageSMS;
SharedPreferences shfResponderMessage;
shfResponderMessage=getSharedPreferences("MESSAGE", Context.MODE_PRIVATE);
shfEditMessageSMS=shfResponderMessage.edit();
toggleStatus=(ToggleButton)findViewById(R.id.toggleButtonStatus);
toggleStatus.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// TODO Auto-generated method stub
if(((ToggleButton)v).isChecked())
{
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "ON");
shfEditMessageSMS.commit();
showNotification("ON");
}
else
{
shfEditMessageSMS=shfResponderMessage.edit();
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "OFF");
shfEditMessageSMS.commit();
showNotification("OFF");
String SMSResponderOnOrOff=shfResponderMessage.getString("SMSRESPONDERONOFF", "NONE");
Log.i("SMS Responder on click "+SMSResponderOnOrOff," ");
}
}
});
As you can see in the code that if toggle button in unchecked i am doing
shfEditMessageSMS.putString("SMSRESPONDERONOFF", "OFF");
shfEditMessageSMS.commit();
but when I am retrieving and printing using log
String SMSResponderOnOrOff=shfResponderMessage.getString("SMSRESPONDERONOFF", "NONE");
Log.i("SMS Responder on click "+SMSResponderOnOrOff," ");
It always shows "ON" in the logs.
What could be the problem.
thanks.
i have implement the Same thing in my application. Might Help you out to Solve your Problem.Though Could Not able to Find out the Mistake you have done in your Code. Refere below code below.
boolean on;
public SharedPreferences spref;
final String PREF_NAME="preferences";
ToggleButton tb;
#Override protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fb_intermidiate);
spref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
tb = (ToggleButton) findViewById(R.id.toggleButton1);
on = spref.getBoolean("On", true); //default is true
if (on = true)
{
tb.setChecked(true);
} else
{
tb.setChecked(false);
}
back = (Button)findViewById(R.id.button_back);
//back.setText(R.string.back_button_in_settings);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
}); }
public void onToggleClicked(View view) {
on = ((ToggleButton) view).isChecked();
if (on) {
Toast.makeText(this, "On : Notification will be Enabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor = spref.edit();
editor.putBoolean("On", true); // value to store
editor.commit();
} else {
Toast.makeText(this, "Off : Notification will be Disabled", Toast.LENGTH_SHORT).show();
SharedPreferences.Editor editor =spref.edit();
editor.putBoolean("On", false); // value to store
editor.commit();
} }
I had a similar problem but with saving a String array. I "solved" the problem by incrementing a variable on each save.
public void saveProfileList(Context context) {
SharedPreferences sharedprefs = context.getSharedPreferences(PREFS_NAME,Activity.MODE_PRIVATE);
Editor editor = sharedprefs.edit();
editor.putStringSet("vpnlist", profiles.keySet());
// For reasing I do not understand at all
// Android saves my prefs file only one time
// if I remove the debug code below :(
int counter = sharedprefs.getInt("counter", 0);
editor.putInt("counter", counter+1);
editor.apply();
}
There seems to be a bug somewhere in the android code that does not always detect the sharedpreferences as changed.
I have a vague recollection that it can take a while for the value to be read back correctly. You can solve that by encapsulating the value and store it in a variable, from where you also retrieve it. You should also consider using apply() instead of commit() since it does not interrupt the UI thread. Thus, I propose something like:
public class Preferences {
private SharedPreferences mPrefs;
private static final String KEY = "SMSRESPONDERONOFF";
private String mValue;
public Preferences(SharedPreferences prefs) {
mPrefs = prefs;
}
public String getValue() {
if (mValue == null) {
mValue = mPrefs.getString(KEY, "NONE");
}
return mValue;
}
public void setValue(String value) {
mValue = value;
mPrefs.edit().putString(KEY, value).apply();
}
}

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