-1

Just a quick question. I need to store one int in my app and SharedPreferences would be a neat and easy way to do it. Any objections to the use of it? Here is my code:

private SharedPreferences pref;
private Editor editor;
//-------------------------------
//get the best
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
best = pref.getInt("value", 0);
//-------------------------------
//save the best
best = pref.getInt("value", best);
if(best < now){
    editor.putInt("value", now);
    editor.commit();
Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120

1 Answers1

0

Do this to store:

SharedPreferences pref = getSharedPreferences("prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("key", i); // i is integer
edt.commit();

To use it do:

SharedPreferences pref = getSharedPreferences("prefs", Activity.MODE_PRIVATE);
int i = pref.getInt("key", -1);
Mohammed Ali
  • 2,758
  • 5
  • 23
  • 41
  • Thanks :) I don't really know how the memory is being used with SharedPreferences. Does the value stay in the memory even after the app is uninstalled? One int is not much but still. – wantsToLearnAndroid Dec 08 '14 at 19:39
  • It is removed when app is uninstalled. But there are ways to store `SharedPreferences`. You can back up to cloud see http://stackoverflow.com/q/9815363/3879470 : `You should add a BackupAgentHelper to your app. Together with the SharedPreferenceBackupHelper, it backups the SharedPreferences to the cloud (if the device supports it). When the app is reinstalled the data is restored.` – Mohammed Ali Dec 09 '14 at 01:02
  • Also see: http://stackoverflow.com/q/15873066/3879470 : `When you uninstall any application all the changes the application have made in your internal memory are revoked, that means your SharedPreference files, Other data files, Database file, Application gets removed automatically by the Android OS.` – Mohammed Ali Dec 09 '14 at 01:04