2

I am trying to get value from SharedPreferences and storing it inside of an static variable. The problem is sometimes I am getting null value from static variable but SharedPreferences has value. I have stored value via this process:

 SharedPreferences sp = u.returnShare();
    SharedPreferences.Editor editor = sp.edit();

    StaticVariables.userId = sp.getString("UserId", "default");

2 Answers 2

3

Don't use static variables, its bad practice. Android can destroy you application's process at any time and later recreate it by recreating activities as necessary. If you're creating your static variable in the "first" activity then it wont get initialized when the 2nd or 3rd are started first.

Sign up to request clarification or add additional context in comments.

2 Comments

Then what can I do? Shall I get value every times from sharedPreference or any other better idea?
Treat the static variable as a cache, if it is null you need to get if from shared preferences again.
3

Static variables are not a good long term storage in android. The system may kill your application at any time when it is in background (for example when the memory is needed for other tasks). All your values stored in static variables are then gone when the app is restarted.

1 Comment

Then what can I do? Shall I get value every times from sharedPreference or any other better idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.