Search⌘ K
AI Features

Persist Login State

Explore how to persist login state in an Android app using Kotlin's SharedPreferences. Learn to store and retrieve login data, create a dedicated preferences class, and manage app navigation based on the user's login status.

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. ...