- Forum posts: 2
Jun 25, 2015, 10:03:43 AM via Website
Jun 25, 2015 10:03:43 AM via Website
Iam developing an App where iam saving the values in SharedPrefernces. I've created a separate class SharedPreferenceforAlarm for setting or getting the values stored in SharedPreferences. To set or get the stored values, iam calling the class object from different activities.
The problem which iam facing is that the values are not saving correctly.
For example(see the code):
Default value for alarmisSet: False
Default value for alarmName : No Alarm
If iam calling setAlarm(this, true) from any activity, the Log what iam getting is "SHAREDPREFERENCES, Alarm is set: false;"
Same case if iam calling setAlarmName(), default alarmName is printing not the one iam giving.
/*****************************Shared Preference Class**************************************//
public class SharedPreferencesforAlarm {
public static final String TAG = "SHAREDPREFERENCES" ;
public static final String MyPREFERENCES = "Alarm" ;
public static final String alarmisSet="alarmisSet";
public static final String alarmName="alarmName";
public SharedPreferencesforAlarm() {
super();
}
public void setAlarm(Context context, Boolean value) {
SharedPreferences mySettings;
mySettings = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Editor editor=mySettings.edit();
editor.putBoolean(alarmisSet, value);
editor.commit();
Log.d(TAG,"Alarm is Set:"+value);
}
public Boolean getAlarm(Context context, Boolean value) {
SharedPreferences mySettings;
mySettings = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
return(mySettings.getBoolean(alarmisSet, value));
}
public void setAlarmName(Context context,String name) {
SharedPreferences mySettings;
mySettings = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
editor = mySettings.edit();
editor.putString(alarmName, name);
editor.commit();
Log.d(TAG, "Alarm Name:" + name);
}
public String getAlarmName() {
SharedPreferences mySettings;
mySettings = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
return(mySettings.getString(alarmName, null));
}
/***********CODE FOR CALLING THE SHARED PREFERENCE CLASS FROM ANY ACTVITY*****************************//
SharedPreferencesforAlarm sharedPreferences = new SharedPreferencesforAlarm(); //creating the object
sharedPreferences.setAlarm(this, true);
sharedPreferences.setAlarmName(this, alarmName.getText().toString()); //alarmName is a TextView
Recommended editorial content
With your consent, external content is loaded here.
By clicking on the button above, you agree that external content may be displayed to you. Personal data may be transmitted to third-party providers in the process. You can find more information about this in our Privacy Policy.