Create a Simple Login App in Android

In my previous blog I wrote about Android Studio errors faced by users and solutions during Installation of Android Studio. Here is the link of that blog Android Studio Installation Hacks.

In this blog we will create an Android Simple Login App using Android Studio.

Android Simple Login App Assumptions

In this Android Simple Login app there are two activities:

  • The First activity is to design the front end, which is user view. Means how user will view our app.
  • The Second activity is how to write the back end code for the Android Simple Login Application.

So lets gets started with our basic Android Simple Login App:

  • Open your Android Studio.
  • Click on Start a New Android Studio Project.
  • Write your Application Name LoginApp”  and leave other fields blank as it is, then click NEXT.
  • Select the Minimum SDK API 15: Android 4.0.3(IceCreamSandwich)”I selected API 15 because it covers 94% device and it has almost all the features. If you want to cover 100% device then you can select API 8: Android 2.2(Froyo). But it has limitation on features. After selecting your API click on NEXT.
  • Select the blank activity and click NEXT.
  • Write the activity name “Login” and leave everything as it is. Click Finish.
  • After clicking Finish, it takes around 5 minutes to build your first activity, which is Login Activity .
Android Simple Login App Building Your First Activity

Android Simple Login App Building Your First Activity

  • Now we will create another activity called “User”.  This activity will redirect user to “User screen” after he provides valid Login and password.
  • To create a new activity go to app -> res -> layout. Right click on layout and go to  new -> Activity -> Blank Activity.
  • You will see the new activity screen.
  • Write the name of your new activity as User” and leave everything as it is. Click Finish.
Android Simple Login App Create User Activity

Android Simple Login App Create User Activity

  • Now we have two activities, which you can see in app -> res -> layout .
    • activity_login.xml
    • activity_user.xml
  • Go to the activity_user.xml file. You can see the path of your user activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.abhinavhackpundit.simpleloginapp.UserActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/screen_page_text"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

  • Go to AndroidManifest.xml file.
  • You will see your both activities. One is login activity which is also the launcher activity . Other is user activity. Here we set the Intent filter for our second activity which is also called as user activity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.abhinavhackpundit.simpleloginapp" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".LoginActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".UserActivity"
            android:label="@string/title_activity_user" >
            <intent-filter>
                <action android:name="com.abhinavhackpundit.simpleloginapp.UserActivity" />

                <category android:name="android.intent.category.default" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Part-I: Android Simple Login App Front End

  • We will start with designing our Login Activity for our Android Simple Login App. Go to app -> res -> layout -> activity_login.xml.
  • Pick 5 large text elements, 1 person name element, 1 Button and 1 password element from palette. Arrange it as shown in the image below:
  • Change the text and id as below:
    • Text: Login Page, Id: textView_login
    • Text: Username, Id: textView_username
    • Text: Password, Id: textView_password
    • Text: ” “, Id: editText_user
    • Text: ” “, id: editText_password
    • Text: Attempt, id: textView_attempt
    • Text: ” “, Id: textView_attempt_count
    • Text: “Login“, Id: button_login
Android Simple Login App First Activity Design

Android Simple Login App First Activity Design

  • Define strings constant for all the elements in strings.xml file. You can find string.xml file in  app -> res -> values ->strings.xml.
<resources>
    <string name="app_name">SimpleLoginApp</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_user">UserActivity</string>
    <string name="login_text">Login Page</string>
    <string name="username_text">User Name</string>
    <string name="password_text">Password</string>
    <string name="attempt_text">Attempt</string>
    <string name="button_login_text">Login</string>
    <string name="screen_page_text">Welcome  to the second page</string>
</resources>
  • Now we will design the second activity which is user activity. Go to app -> res ->layout -> activity_user.xml.
  • Select large text element from the palette. Edit its text to “welcome to second page“.
Android Simple Login App Second Activity Design

Android Simple Login App Second Activity Design

  • Great! we are done with the design of front end part.

Part-II: Android Simple Login App Back End

  • In the previous part we saw how to design UI of Android simple login app.
  • In this part we will see how to write the code behind login button. And how to validate the username and password.
  • Go to the java file in which we will do code for the action performed by button.
  • Go to app -> Java -> Com.abhinavhackpundit.loginapp ->login.
Android Simple Login App login Java File

Android Simple Login App login Java File

  • The code or logic behind the action of app is shown below:
package com.abhinavhackpundit.loginapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends AppCompatActivity {

    private static EditText username;
    private static EditText password;
    private static TextView attempt;
    private static Button login_button;
    int attempt_counter=5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        LoginButton();
    }

    public void LoginButton(){
        username = (EditText)findViewById(R.id.editText_user);
        password = (EditText)findViewById(R.id.editText_password);
        attempt = (TextView)findViewById(R.id.textView_attempt);
        login_button = (Button)findViewById(R.id.button_login);

        attempt.setText(Integer.toString(attempt_counter));

        login_button.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (username.getText().toString().equals("user") &amp;amp;amp;&amp;amp;amp;
                                password.getText().toString().equals("pass")){
                            Toast.makeText(Login.this,"Username and password is correct",
                                    Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent("com.abhinavhackpundit.loginapp.User");
                            startActivity(intent);

                        }
                        else {
                            Toast.makeText(Login.this,"Username and password is NOT correct",
                                    Toast.LENGTH_SHORT).show();
                            attempt_counter--;
                            attempt.setText(Integer.toString(attempt_counter));
                            if(attempt_counter==0)
                                login_button.setEnabled(false);
                        }
                    }
                }
        );
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
  • Below is the explanation of each highlighted line because that java code is behind the login page activity.
  • Line 16 to Line 20: Here we have declared two Edit Text boxes for username and password. One Text View for attemptone for Button and one Integer for attempt_counter(the number of times user can enter wrong user and password after that button will be disabled).
  • Line 26: Here we called the LoginButton() function.
  • Line 29: Here we have defined a function LoginButton().
  • Line 30: to Line 33: Here we Cast all the variable we have declared above in Line 16 to Line 20.
  • Line 37: Here we call the function login_button.setOnClickListener() so that we perform action on button according to us.
  • Line 41 to Line 48: Here we have put If condition. Logic is if username=”user” and password=”pass” are right then it will display a message “Your Username and Password is correct” and it will go to Second activity page.
    • Intent: An Android Intent is an abstract description of an operation to be performed. It can be used with startActivity() to launch an Activity.
  • Line 49 to Line 51: Here we have given Else Condition that, if username=”user” and Password=”pass” is not correct then it displays a message “Your Username and Password is NOT correct”.
  • Line 52: If Else Condition is right then it will reduce the attempt_counter.
  • Line 53: Here we have displayed the number of attempts left.
  • Line 54 to Line 55: Here we have put the If Condition that, if attempt_counter is less than Zero, then it will disable the Login Button.

Congratulations! we are ready to Run our Android Simple Login App. To run our app I used Genymotion Emulator as it’s fast. Also its performance is better than default Android emulator. If you have not already installed I highly recommend Genymotion Emulator. You can install from here: Android Emulator Genymotion Step by Step Installation

  • Click on Genymotion device manager. After selecting your custom device in Genymotion device manager window click NEXT.
  • Click on Run. You can see your Android Login App running.
AndroidSimple Login App Running LoginApp

Android Simple Login App Running LoginApp

Output After clicking Login Button

Android Simple Login App Second Activity

Android Simple Login App Second Activity

Login is very basic and most used feature in an Android App or Web App. Users needs to login to prove their authenticity and access website features. It’s a very simple feature for Android Geeks. But it can be challenging for beginners. You can reuse above code and follow steps for creating your Simple Login Android App. If you have used any other method for creating an Android simple login app, do let me know in comments. Would love to try out.

This is a beginner tutorial for implementing an Android App. Read below articles for more advanced android tutorials.

Thank you for reading this article. If you face any problem or having any doubts, just let me know in comment box. If you like my article please like our Facebook page and also follow on Twitter. By doing so you will get regular updates about Android tutorials. For regular updates you can also subscribe to hackpundit.com with your email.