SharedPreferences Not Saving after creating separate class for it

  • Replies:2
tspshikari
  • Forum posts: 2

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

Reply
Microvirter
  • Forum posts: 10

Jul 17, 2015, 12:31:20 PM via Website

Nice!

Reply
Deactivated Account
  • Forum posts: 25

Jul 17, 2015, 4:47:07 PM via Website

I have a similar problem

Reply