I am using defaultSharedPreferences()
throughout my application. I define it once in my Application class and use it whenever needed:
public class Itu extends Application {
public static SharedPreferences sharedPreferencesFDefault;
@Override
public void onCreate() {
sharedPreferencesFDefault = PreferenceManager.getDefaultSharedPreferences(this);
}
public static SharedPreferences getSharedPreferencesItu(){
return sharedPreferencesFDefault;
}
public static int getStudentNameColor(SharedPreferences sharedPref){
int color = sharedPref.getInt("studentNameColor", -1);
if (color == -1) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("studentNameColor", 0);
editor.commit();
color = sharedPref.getInt("studentNameColor", 0);
}
....
return color;
}
I use it in this Activity:
public class StudentAddActivity extends ActionBarActivity {
...
private void attemptAdd() {
SharedPreferences sharedPref=((Itu)getApplication()).getSharedPreferencesItu();
int color=Itu.getStudentNameColor(sharedPref);
}
Now i want to delete all values from my another activity which does not work:
public class CourseListActivity extends ActionBarActivity{
public static SharedPreferences sharedPreferencesFDefault;
...
sharedPreferencesFDefault = ((Itu) getApplication()).getSharedPreferencesItu();
sharedPreferencesFDefault.edit().clear().commit();
}
After i call sharedPreferencesFDefault.edit().clear().commit();
, i still see that my "studentNameColor"
value exists in defaultSharedPreferences
.
What might be problem? Using defaultSharedPreferences instead of sharedPreference? or passing Application context instead of each activity's context? or i call wrong function to delete?
UPDATE 1: i can delete it from my Application class, but not from my Activities. why?
UPDATE 2: i can delete now it from another activity by accessing variable directly:
((Itu) getApplication()).sharedPreferencesFDefault.edit().clear().commit();
But if i get sharedPreference variable through my static function, i can not clear it, why?