0

I have static DefaultSharedPreference variable defined as like here:

public class Itu extends Application {
    public static SharedPreferences sharedPreferencesFDefault;

    @Override
    public void onCreate() {
        sharedPreferencesFDefault = PreferenceManager.getDefaultSharedPreferences(this); 
    }
    public static SharedPreferences getSharedPreferencesItu(){
        return sharedPreferencesFDefault;
    }
}

(1. way) When i access it directly from some Activity, it clears sharedPreference:

((Itu) getApplication()).sharedPreferencesFDefault.edit().clear().commit();

(2. way) But when i access it through Getter method and try to clear() it, it does NOT work:

public static SharedPreferences sharedPreferencesFDefault;
sharedPreferencesFDefault = ((Itu) getApplication()).getSharedPreferencesItu();
sharedPreferencesFDefault.edit().clear().commit();

Old question: What is the difference between 1.way and 2.way?

UPDATE: I changed public static SharedPreferences sharedPreferencesFDefault to public SharedPreferences sharedPreferencesFDefault and both ways worked.

New question: What happens when i initialize static variable with another static variable indeed?

Jemshit
  • 9,501
  • 5
  • 69
  • 106
  • The best way is not to have it `static` and access it using `PreferenceManager.getDefaultSharedPreferences(context)` – StenSoft Apr 13 '15 at 13:10
  • @StenSoft since i need to access "same" sharedPreference through multiple Activities and Fragment, i need it as static. If i get sharedPreference through different contexts, i think i'll get different sharedPreference files which i do not desire. – Jemshit Apr 13 '15 at 13:16
  • [It returns the same preferences for the whole application](http://stackoverflow.com/a/9518308/4538344) – StenSoft Apr 13 '15 at 13:20

0 Answers0