Save settings on application close and restore settings on startup

1 1 1 1 1 Save settings on application close and restore settings on startup5.00Rating 3.00 (2 Votes)

In order to restore preferences upon application startup, you can use Android SharedPreferences class.

In onCreate metod call:

SharedPreferences sharedPref = getSharedPreferences("myprefs", 0);

// restore integer value, 1 - default

integer_value = sharedPref.getInt("integer_value", 1);

//same for the string value
string_value = sharedPref.getString("string_value", "this is a default value";

And in order to save values on application exit, write in onStop method:

SharedPreferences sharedPref= getSharedPreferences("myprefs", 0);
SharedPreferences.Editor editor= sharedPref.edit();

editor.putString("string_value", string_value);
editor.putInt("integer_value", integer_value);
editor.commit();

You can actually save other types of data also.

Also see these articles:
1. http://samir-mangroliya.blogspot.in/p/android-shared-preferences.html
2. http://developer.android.com/guide/topics/data/data-storage.html

You have no rights to post comments

Thursday the 23rd.