For android, there are primarly three basic ways of persisting data:
- shared preferences to save small chunks of data
- tradition file systems
- a relational database management system through the support of SQLite databases
SharedPreferences object help you save simple application data as a name/value pairs - you specify a name for the data you want to save, and then both it and its value will be saved automatically to an XML file for you. To save a data in sharedPreferences file:
Obtain an instance of sharedPreferences file:
SharedPreferences appPrefs = getSharedPreferences( or fileName, MODE_PRIVATE);
Create SharedPreferences.Editor object
To put for example a String value into SharedPreferences object use putString() method.
To save the changes to the preferences file, use the commit() method
That will look like this:
// obtain an instance of the SharedPreferences class
preferences = getSharedPreferences(prefFileName, MODE_PRIVATE);
editor = preferences.edit();
// save username String
editor.putString("username", student).commit();
To retrieve it use getString() method:
preferences.getString(username, null) where null is a default value that will be returned if username key is not found in the file.