Many applications require users to login in order to access all the available features. In this tutorial we will secure an Android activity by requiring users to enter their username and password.

We will start by creating a new blank activity with fragment, LoginActivity.

We will use the following layout for the login fragment (2 edit texts for username & password, 1 button to submit the login form and one text view to show any errors that could happen):

Before writing the actual login code, we will create a helper class to read & save related values to Android’s SharedPreferences:

Now let’s see the actual login code:

In the end, all that’s left is to start this activity whenever we need the user to login: