Android Android -3 years ago 80
Android Question

Can the value of final static field change in android?

I'm working on

SharedPreferences
and in my program i have a final static variable each for name and email as

public static final String PREF_NAME = "name";
public static final String PREF_EMAIL = "email";


After initializing my
SharedPreferences
Object,

SharedPreferences sPref = this.getSharedPreferences("com.vivid.sharedprefrences",Context.MODE_PRIVATE);


I Change the value of the constant fields by replacing them by the user entered name and email

sEditor.putString(PREF_NAME,name);
sEditor.putString(PREF_EMAIL,email);
sEditor.commit();


But as per the other answers on stack overflow
a static final variable value cannot be changed once initialized

But here the value of a static final field changes when i insert the name and email into
PREF_NAME
and
PREF_EMAIL

How is that possible?

Answer Source

When you do this sEditor.putString(PREF_EMAIL,email);, the first parameter is the key and not the value. So what happens is in your preference the value of email is saved for the KEY PREF_EMAIL.

Hence the key is never changing. Your shared preference are Key-ValuePair kind of collections. The value of String PREF_EMAIL is what you have defined in the line - public static final String PREF_EMAIL = "email"; i.e. email and will always remain the same.

The value of preference saved with the identifier key as PREF_EMAIL changes.

so your Shared Preference will be saved as -

email = "email@sample.com" // this is just an example representation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download