3

I'm novice in Android development and now I'd really like to learn Shared Preferences. I've googled it so many times and I don't think I quite mastered it.

I believe this Shared Preferences will help me to store username and a password on my login screen activity. Thanks you!

Hendra Anggrian
  • 5,780
  • 13
  • 57
  • 97

2 Answers2

14

I made some videos about this as an audition for a job. They helped me get the job, and they're still available on Vimeo, so hopefully they can help you out.

Part 1: Saving Data

Part 2: Retrieving Data

Also, for what it's worth, be careful storing usernames and passwords in SharedPreferences. You can do it there, but read up on the risks in this other SO question: What is the most appropriate way to store user settings in Android application

Community
  • 1
  • 1
Ben Jakuben
  • 3,147
  • 11
  • 62
  • 104
5

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:

  1. Obtain an instance of sharedPreferences file: SharedPreferences appPrefs = getSharedPreferences( or fileName, MODE_PRIVATE);

  2. Create SharedPreferences.Editor object

  3. To put for example a String value into SharedPreferences object use putString() method.

  4. 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.
Marcin S.
  • 11,161
  • 6
  • 50
  • 63