0

I have been spending the last few hours researching on how to store data within internal storage however I cannot for some reason be capable of storing an integer.

I would like to know how to store an int value within a file as well as be able to read off of it. Please provide a brief example on how I can achieve this and would it be preferable to use the SharedPreferences class?

ChallengeAccepted
  • 1,684
  • 1
  • 16
  • 25

2 Answers2

1

Yes I think SharedPreferences would be the easiest way :

SharedPrefrences prefs=PreferenceManager.getDefaultSharedPreferences(context);
Editor editor=prefs.edit();
editor.putInt("MYINT",intValue);
editor.commit();

To retrieve the int use :

PreferenceManger.getDefaultSharedPreferences(context).getInt("MYINT",-1);
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
1

It is better to use SharedPreference if it is just an int value:

public int getValue() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    return prefs.getInt("value_key", 0);
}

public void setValue(int newValue) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("value_key", newValue);
    editor.commit();
}
iTurki
  • 16,292
  • 20
  • 87
  • 132