Krishnan V S Krishnan V S - 2 months ago 29
Android Question

Android - right way to store a value for repeated use?

I have a service in my app that is always running but the global static variables seem to get reset when the phone is idle for a while (possibly the app is getting closed). Please let me know the optimal way to store a value for repeated use, maybe once in 2-5 mins.

Will using a SharedPreference cause high overhead if accessed once in 2-5 mins ?

Appreciate your help.


SharedPreference is best option.

public class AppPreference {
public static final String APP_NAME_KEY= "your_app_name";
public static final String SAMPLE_KEY = "sample";

public SharedPreferences preferences;
private SharedPreferences.Editor editor;

private String sample;

public AppPreference(Context context) {
        preferences = context.getSharedPreferences(APP_NAME_KEY, Context.MODE_PRIVATE);
        editor = preferences.edit();

public void setSample(String sample) {
    this.sample= sample;
    editor.putString(SAMPLE_KEY , this.sample);

public String getSample() {
        return preferences.getString(SAMPLE_KEY, null);

You can use Integer, Float, boolean values according to your requirement.