0

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?

Jemshit
  • 9,501
  • 5
  • 69
  • 106
  • try calling static methods like Itu.getSharedPreferencesItu(); – Harin Apr 13 '15 at 12:47
  • I understood the error, but still has question in my mind, check here: http://stackoverflow.com/questions/29605084/accessing-static-sharedpreference-variable-directly-vs-through-getter-function – Jemshit Apr 13 '15 at 12:48

1 Answers1

0

I have changed public static SharedPreferences sharedPreferencesFDefault; to public SharedPreferences sharedPreferencesFDefault; and now clear() works. The thing was getting static sharedPreference, from Application class, into static variable of Activity class.

I still don't know what happens when we initialize static variable with another static variable. You can follow that question here.

Community
  • 1
  • 1
Jemshit
  • 9,501
  • 5
  • 69
  • 106