Persist Login State

Learn and practice how to store the login state in the Android key-value storage in this lesson.

Flow overview

When LoginActivity is opened, we need to check the login state:

  • If the user is logged in already, we close LoginActivity and open MainActivity straightaway.
  • If the user is not logged in, we proceed to the regular flow and save the login state in the end.

Shared preferences

In Android, we can use SharedPreferences to store a simple key-value data… A key-value store is basically a Map that is serialized to the disk as a file. This storage support saving the following types of data:

  • String
  • Boolean
  • Integer
  • Long
  • Float
  • Set<String> values

Any data stored in the SharedPreferences is going to be persisted inside the internal application-specific file on the file system. Let’s learn how to create the SharedPreferences and some basic operations.

To create new or load existing SharedPreferences, we can use the Context#getSharedPreferences method. Don’t forget that the Activity class implements the Context interface, so this method can be called inside the Activity.

The getSharedPreferences method has two required parameters:

  • name - the shared preferences file name, in our case travel-blog
  • mode - the operating mode, in our case Context.MODE_PRIVATE means that only our application will have access to this shared preferences

Get hands-on with 1200+ tech skills courses.