Android Login and Register with SQLite Database Example

Posted by

Hello everyone and welcome to easytechsolutions.info , So in today’s post we are going to make a login as well as register form with the use of android in built database SQLite.

As you all know Android comes with in built support of SQLite database so it’s better to use it because it will help to store information on offline as well so that you can see all your data in offline too.

So let’s get started by implementing this below are the steps you need to do:-

Step 1:- Open up Android Studio and make a new project and Select Empty Activity.

Step 2:- Now we need 3 layout files in order to achieve this implementation so first we create all the necessary layout files:-

activity_main.xml (Copy and paste below code):-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:background="#ff00"
    >

    <TextView
        android:text="@string/sql"
        android:gravity="center"
        android:textAppearance="?android:textAppearanceLarge"
        android:textColor="#000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="@string/email"
        android:textColor="#fff"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:layout_marginTop="20dp"
        android:id="@+id/editEmail"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/password"
        android:textColor="#000"
        android:ems="10"
        android:layout_below="@+id/editEmail"
        android:layout_marginTop="20dp"
        android:id="@+id/editPassword"
        />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/buttonLogin"
        android:layout_below="@+id/editPassword"
        android:layout_marginTop="20dp"
        android:text="Log IN "
        android:background="#ff0"
        android:textAppearance="?android:textAppearanceLarge"
        android:fontFamily="sans-serif-condensed"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/buttonRegister"
        android:layout_below="@+id/buttonLogin"
        android:layout_marginTop="20dp"
        android:textAppearance="?android:textAppearanceLarge"
        android:background="#ff0"
        android:fontFamily="sans-serif-condensed"
        android:text="@string/sign"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/update"
        android:layout_below="@+id/buttonRegister"
        android:layout_marginTop="20dp"
        android:background="#ff0"
        android:text="Update"
        android:textAppearance="?android:textAppearanceLarge"
        android:fontFamily="sans-serif-condensed"
        />

</RelativeLayout>

activity_register.xml (Copy and paste below code):-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_register"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:background="#ff00"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    >

    <TextView
        android:text="@string/register"
        android:gravity="center"
        android:textAppearance="?android:textAppearanceLarge"
        android:textColor="#000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="@string/name"
        android:textColorHint="#fff"
        android:ems="10"
        android:layout_below="@+id/textView"
        android:fontFamily="sans-serif-condensed"
        android:layout_marginTop="20dp"
        android:id="@+id/editName"
        />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="@string/regi"
        android:textColorHint="#fff"
        android:ems="10"
        android:layout_below="@+id/editName"
       android:fontFamily="sans-serif-condensed"
        android:layout_marginTop="20dp"
        android:id="@+id/editEmail"
      />

    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/password1"
        android:textColorHint="#fff"
        android:ems="10"
        android:layout_below="@+id/editEmail"
        android:layout_marginTop="20dp"
        android:id="@+id/editPassword"
        />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/buttonRegister"
        android:background="#ff0"
        android:layout_below="@+id/editPassword"
        android:textAppearance="?android:textAppearanceLarge"
        android:layout_marginTop="20dp"
        android:text="Register From here "/>

</RelativeLayout>

activity_dashboard.xml (Copy and paste below code):-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_dashboard"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    >

    <TextView
        android:text="@string/success"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textAppearance="?android:textAppearanceLarge"
        android:textColor="#000"
        android:id="@+id/textView1"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="176dp" />

    <Button
        android:text="LOGOUT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:fontFamily="sans-serif-condensed"
        android:background="#ff00"
        android:textColor="#fff"
        android:textAppearance="?android:textAppearanceLarge"
        android:layout_marginTop="36dp"
        android:id="@+id/button1" />

</RelativeLayout>

Now we are done with layout files and we completed our Android App layout now its time to make all the Java files in order to achieve functionality .

Step 3:- we need to make 4 Java files and link it with related layout files.

MainActivity.java (Copy and paste below code):-

package com.sqliteloginandroid;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button LogInButton, RegisterButton , UpdateButton ;
    EditText Email, Password ;
    String EmailHolder, PasswordHolder;
    Boolean EditTextEmptyHolder;
    SQLiteDatabase sqLiteDatabaseObj;
    SQLiteHelper sqLiteHelper;
    Cursor cursor;
    String TempPassword = "NOT_FOUND" ;
    public static final String UserEmail = "";

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

        LogInButton = (Button)findViewById(R.id.buttonLogin);

        RegisterButton = (Button)findViewById(R.id.buttonRegister);

        Email = (EditText)findViewById(R.id.editEmail);
        Password = (EditText)findViewById(R.id.editPassword);

        UpdateButton = (Button) findViewById(R.id.update);

        sqLiteHelper = new SQLiteHelper(this);

        //Adding click listener to log in button.
        LogInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Calling EditText is empty or no method.
                CheckEditTextStatus();

                // Calling login method.
                LoginFunction();


            }
        });


        //UpdateButton OnClickListner :-
        UpdateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sqLiteHelper.updateRecord(Email.getText().toString(),Password.getText().toString());
                Toast.makeText(MainActivity.this, "Updated Successfully", Toast.LENGTH_SHORT).show();
            }
        });

        // Adding click listener to register button.
        RegisterButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Opening new user registration activity using intent on button click.
                Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                startActivity(intent);

            }
        });

    }

    // Login function starts from here.
    public void LoginFunction(){

        if(EditTextEmptyHolder) {

            // Opening SQLite database write permission.
            sqLiteDatabaseObj = sqLiteHelper.getWritableDatabase();

            // Adding search email query to cursor.
            cursor = sqLiteDatabaseObj.query(SQLiteHelper.TABLE_NAME, null, " " + SQLiteHelper.Table_Column_2_Email + "=?", new String[]{EmailHolder}, null, null, null);

            while (cursor.moveToNext()) {

                if (cursor.isFirst()) {

                    cursor.moveToFirst();

                    // Storing Password associated with entered email.
                    TempPassword = cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table_Column_3_Password));

                    // Closing cursor.
                    cursor.close();
                }
            }

            // Calling method to check final result ..
            CheckFinalResult();

        }
        else {

            //If any of login EditText empty then this block will be executed.
            Toast.makeText(MainActivity.this,"Please Enter UserName or Password.",Toast.LENGTH_LONG).show();

        }

    }

    // Checking EditText is empty or not.
    public void CheckEditTextStatus(){

        // Getting value from All EditText and storing into String Variables.
        EmailHolder = Email.getText().toString();
        PasswordHolder = Password.getText().toString();

        // Checking EditText is empty or no using TextUtils.
        if( TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)){

            EditTextEmptyHolder = false ;

        }
        else {

            EditTextEmptyHolder = true ;
        }
    }

    // Checking entered password from SQLite database email associated password.
    public void CheckFinalResult(){

        if(TempPassword.equalsIgnoreCase(PasswordHolder))
        {

            Toast.makeText(MainActivity.this,"Login Successfully",Toast.LENGTH_LONG).show();

            // Going to Dashboard activity after login success message.
            Intent intent = new Intent(MainActivity.this, DashboardActivity.class);

            // Sending Email to Dashboard Activity using intent.
            intent.putExtra(UserEmail, EmailHolder);

            startActivity(intent);


        }
        else {

            Toast.makeText(MainActivity.this,"UserName or Password is Wrong, Please Try Again.",Toast.LENGTH_LONG).show();

        }
        TempPassword = "NOT_FOUND" ;

    }

}

RegisterActivity.java (Copy and paste below code):-

package com.sqliteloginandroid;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by AJAY THAKUR on 9/12/2017.
 */

public class RegisterActivity extends AppCompatActivity {
        EditText Email, Password, Name ;
        Button Register;
        String NameHolder, EmailHolder, PasswordHolder;
        Boolean EditTextEmptyHolder;
        SQLiteDatabase sqLiteDatabaseObj;
        String SQLiteDataBaseQueryHolder ;
        SQLiteHelper sqLiteHelper;
        Cursor cursor;
        String F_Result = "Not_Found";

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

            Register = (Button)findViewById(R.id.buttonRegister);

            Email = (EditText)findViewById(R.id.editEmail);
            Password = (EditText)findViewById(R.id.editPassword);
            Name = (EditText)findViewById(R.id.editName);

            sqLiteHelper = new SQLiteHelper(this);

            // Adding click listener to register button.
            Register.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    // Creating SQLite database if dose n't exists
                    SQLiteDataBaseBuild();

                    // Creating SQLite table if dose n't exists.
                    SQLiteTableBuild();

                    // Checking EditText is empty or Not.
                    CheckEditTextStatus();

                    // Method to check Email is already exists or not.
                    CheckingEmailAlreadyExistsOrNot();

                    // Empty EditText After done inserting process.
                    EmptyEditTextAfterDataInsert();


                }
            });

        }

        // SQLite database build method.
        public void SQLiteDataBaseBuild(){

            sqLiteDatabaseObj = openOrCreateDatabase(SQLiteHelper.DATABASE_NAME, Context.MODE_PRIVATE, null);

        }

        // SQLite table build method.
        public void SQLiteTableBuild() {

            sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS " + SQLiteHelper.TABLE_NAME + "(" + SQLiteHelper.Table_Column_ID + " PRIMARY KEY AUTOINCREMENT NOT NULL, " + SQLiteHelper.Table_Column_1_Name + " VARCHAR, " + SQLiteHelper.Table_Column_2_Email + " VARCHAR, " + SQLiteHelper.Table_Column_3_Password + " VARCHAR);");

        }

        // Insert data into SQLite database method.
        public void InsertDataIntoSQLiteDatabase() {
            long a;
            // If editText is not empty then this block will executed.
            if (EditTextEmptyHolder == true) {
                ContentValues contentValues = new ContentValues();
                contentValues.put("name", NameHolder);
                contentValues.put("email", EmailHolder);
                contentValues.put("password", PasswordHolder);
                a = sqLiteHelper.insert(SQLiteHelper.TABLE_NAME, contentValues, SQLiteHelper.Table_Column_ID);
                if (a > 0) {
                    Toast.makeText(this, "Data Inserted", Toast.LENGTH_SHORT).show();
                }
                sqLiteDatabaseObj.close();

            }
        }



        // Empty edittext after done inserting process method.
        public void EmptyEditTextAfterDataInsert(){

            Name.getText().clear();

            Email.getText().clear();

            Password.getText().clear();

        }

        // Method to check EditText is empty or Not.
        public void CheckEditTextStatus(){

            // Getting value from All EditText and storing into String Variables.
            NameHolder = Name.getText().toString() ;
            EmailHolder = Email.getText().toString();
            PasswordHolder = Password.getText().toString();

            if(TextUtils.isEmpty(NameHolder) || TextUtils.isEmpty(EmailHolder) || TextUtils.isEmpty(PasswordHolder)){

                EditTextEmptyHolder = false ;

            }
            else {

                EditTextEmptyHolder = true ;
            }
        }

        // Checking Email is already exists or not.
        public void CheckingEmailAlreadyExistsOrNot(){

            // Opening SQLite database write permission.
            sqLiteDatabaseObj = sqLiteHelper.getWritableDatabase();

            // Adding search email query to cursor.
            cursor = sqLiteDatabaseObj.query(SQLiteHelper.TABLE_NAME, null, " " + SQLiteHelper.Table_Column_2_Email + "=?", new String[]{EmailHolder}, null, null, null);

            while (cursor.moveToNext()) {

                if (cursor.isFirst()) {

                    cursor.moveToFirst();

                    // If Email is already exists then Result variable value set as Email Found.
                    F_Result = "Email Found";

                    // Closing cursor.
                    cursor.close();
                }
            }

            // Calling method to check final result and insert data into SQLite database.
            CheckFinalResult();

        }


        // Checking result
        public void CheckFinalResult(){

            // Checking whether email is already exists or not.
            if(F_Result.equalsIgnoreCase("Email Found"))
            {

                // If email is exists then toast msg will display.
                Toast.makeText(RegisterActivity.this,"Email Already Exists",Toast.LENGTH_LONG).show();

            }
            else {

                // If email already dose n't exists then user registration details will entered to SQLite database.
                InsertDataIntoSQLiteDatabase();

            }

            F_Result = "Not_Found" ;

        }

    }

DashboardActivity.java (Copy and paste below code):-

package com.sqliteloginandroid;

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

/**
 * Created by AJAY THAKUR on 9/12/2017.
 */

public class DashboardActivity extends AppCompatActivity {

    String EmailHolder;
    TextView Email;
    Button LogOUT ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        Email = (TextView)findViewById(R.id.textView1);
        LogOUT = (Button)findViewById(R.id.button1);

        Intent intent = getIntent();

        // Receiving User Email Send By MainActivity.
        EmailHolder = intent.getStringExtra(MainActivity.UserEmail);

        // Setting up received email to TextView.
        Email.setText(Email.getText().toString()+ EmailHolder);

        // Adding click listener to Log Out button.
        LogOUT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Finishing current DashBoard activity on button click.
                finish();

                Toast.makeText(DashboardActivity.this,"Log Out Successfull", Toast.LENGTH_LONG).show();

            }
        });

    }
}

SQLiteHelper.java (Copy and paste below code):-

package com.sqliteloginandroid;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;

/**
 * Created by AJAY THAKUR on 9/12/2017.
 */

public class SQLiteHelper extends SQLiteOpenHelper {

    static String DATABASE_NAME="UserDataBase";

    public static final String TABLE_NAME="UserTable";

    public static final String Table_Column_ID="id";

    public static final String Table_Column_1_Name="name";

    public static final String Table_Column_2_Email="email";

    public static final String Table_Column_3_Password="password";

   // private ContentValues cValues;
    //private SQLiteDatabase dataBase = null;

    public SQLiteHelper(Context context) {

        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase database) {

        String CREATE_TABLE="CREATE TABLE IF NOT EXISTS "+TABLE_NAME+" ("+Table_Column_ID+" INTEGER PRIMARY KEY AUTOINCREMEMT, "+Table_Column_1_Name+" VARCHAR, "+Table_Column_2_Email+" VARCHAR, "+Table_Column_3_Password+" VARCHAR)";
        database.execSQL(CREATE_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);

    }

   public int updateRecord(String email, String password) {

        SQLiteDatabase dataBase = getWritableDatabase();
        ContentValues cValues = new ContentValues();

        //cValues.put(Table_Column_1_Name, name);
        cValues.put(Table_Column_2_Email, email);
        cValues.put(Table_Column_3_Password,password);
//    Update data from database table
        long insertchek=dataBase.update(SQLiteHelper.TABLE_NAME, cValues,
                Table_Column_2_Email+"='"+email+"' AND "+Table_Column_3_Password+"='"+password+"'", null);
        dataBase.close();
        return (int)insertchek;
    }

    public long insert(String table,ContentValues cv,String whereclm)
    {
        SQLiteDatabase dataBase = getWritableDatabase();
        long a=dataBase.insert(table,whereclm,cv);
        return a;
    }

}

Above is the SQLiteHelper class is the main class where all the database linking thing is done.
Now just save all and run your project and you will get to see a Login page pop up so play around it and make sure you will grab some useful information in order to use SQLite Database.

That’s it for now thank you all !

Leave a Reply

Your email address will not be published. Required fields are marked *