Shared Prefference is not saving the data - android

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

Related

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

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.

android sharedPreferences to set and retrieve boolean value

I want to save boolean values and then compare them in an if-else block. but when run my application, nothing is displayed.
my Code is here:
prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = prefs.edit();
boolean init = false;
if (init) {
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor.putBoolean("init", true).commit();
}
});
} else {
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
So my question is why shared preferences is not working? please help me.
This is how you need to work with shared preferences.
The senerio I am about to show is to check if this particular activity is running for the first time or not.
Here is what you do in your on create method:
//SharePrefernces
SharedPreferences appIntro = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Check if the Application is Running for the First time
appIntro = getSharedPreferences("hasRunBefore_appIntro", 0); //load the preferences
Boolean hasRun = appIntro.getBoolean("hasRun_appIntro", false); //see if it's run before, default no
//If FirstTime
if (!hasRun) {
//code for if this is the first time the application is Running
//Display Activity
super.onCreate(savedInstanceState);
setContentView(R.layout.app_intro_activity);
//Button to send Confirmation back
Button btn_ok = (Button) findViewById(R.id.appintro_btn_ok);
btn_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Save information that this application has run for the first time
SharedPreferences settings = getSharedPreferences("hasRunBefore_appIntro", 0);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("hasRun_appIntro", true);
edit.commit(); //apply
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
});
}//End of if(firstTime)
else {
//code if the Application has run before
super.onCreate(savedInstanceState);
//Navigate Directly to MainActivity
Intent intent = new Intent(Application_Intro_Activity.this, MainActivity.class);
startActivity(intent);
//close Activity
finish();
}
}//End of OnCreate()
you are checking always false value of init and it does not enter into your if statement,So prefs will not updated.instead do it as
boolean init = prefs.getBoolean("init",false);
and check it as
if(!init)
i.e. change
boolean init = false;
if (init) {
to
boolean init = prefs.getBoolean("init",false);
if(!init)
You are not using SharedPreferences values in above code . You might need to do like this :
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean prefValue = prefs.getBoolean("init", false);
if(!prefValue)
{
// add value in SharedPreferences
Ion.with(this)
.load("myurl")
.asJsonArray().setCallback(new FutureCallback<JsonArray>() {
#Override
public void onCompleted(Exception arg0, JsonArray data) {
// TODO Auto-generated method stub
for (int i = 0; i < data.size(); i++) {
cat.setTitle(data.get(i).getAsJsonObject()
.get("title").getAsString());
arrayList.add(cat);
db.addCategory(cat);
adapter.notifyDataSetChanged();
}
populateScroller();
editor = prefs.edit();
editor.putBoolean("init", true).commit();
}
});
}
else{
dataSource = new CategoryDataSource(this);
dataSource.open();
arrayList = dataSource.getCategoryList();
for (Categories c : arrayList) {
c.getTitle();
}
}
The key is : You need to check the preference values first and accordingly code
You can also use SharedPreferences like this:
/* In your onCreate method */
SharedPreferences sp = getSharedPreferences(MyPrefs, Context.MODE_PRIVATE);
if (!sp.getBoolean("first", false)) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("first", true);
editor.apply();
Intent intent = new Intent(this, IntroActivity.class); // Call the one tie launch java class
startActivity(intent);
}

Load preferences in another activity?

I stored a value in my MainActivity called "tgpref".
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); //value to save
editor.commit();"
In my onCreate i have
public SharedPreferences preferences;
---
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getPreferences(MODE_PRIVATE);
I want to display the value in my widget so i try to write in the onUpdate in widget provider class this
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean tgpref = preferences.getBoolean("tgpref", false)
if (tgpref == true) {
remoteViews.setTextViewText(R.id.battery, "Risp on");
} else {
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
If the toggle button in the MainActivty is clicked i want that in my widget appears "Risp on" else "Risp off". Right now displays only "Risp off" so i don't know how i can do. Any helps? Nothing happen i can't load the value
it looks good, so i guess your button doesn`t trigger the value change?!
MainActiviy
private Boolean mTgpref;
private SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
//...
//get value from shared preferences and update ui
prefs = this.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
mTgpref = prefs.getBoolean("tgpref", false);
setYourText();
}
private void setYourTextAndStoreToSharedPref(){
Log.i("TEST","mTgpref -> " + mTgpref); //check value
if(mTgpref){
remoteViews.setTextViewText(R.id.battery, "Risp on");
}
else
{
remoteViews.setTextViewText(R.id.battery, "Risp off");
}
prefs.edit().putBoolean("tgpref", mTgpref).commit();
//UPDATE YOUR WIDGET HERE
}
//function called on switch button click
private void onSwitchClickButtonClick(){
mTgpref = !mTgpref; //toggle Boolean
setYourText();
}
EDIT
Sorry, I misunderstood your main problem. After updating SharedPreferences, you should follow the steps described here: http://developer.android.com/guide/topics/appwidgets/index.html#UpdatingFromTheConfiguration

android getsharedPreferences not sure how to show hide other activities

I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);

Categories

Resources