Android Login with SQLite Database Tutorial

Overview

In this tutorial, we show you how to create Android Login Example with SQLite Database using Android Studio. This Application has two screens, first one is login screen where we can just login with our credentials. Second screen is Welcome screen after we login successfully.


Android Login with SQLite Database Tutorial

Watch Tutorial



SQLite Creating Database and Table

Create Database Name: test.db
The following SQLite Script is used to create a table called user and insert data to it.

DROP TABLE IF EXISTS "main"."user";
CREATE TABLE "user" (
"username"  TEXT NOT NULL,
"password"  TEXT,
PRIMARY KEY ("username")
);

INSERT INTO "main"."user" VALUES ('test', 123);

Creating the project

Open the Android Studio, then click “Start a new Android Studio project”.
Start a new Android Studio project

Enter the  info below:
Application Name: LoginWithSQLiteDBExample
Company domain: jackrutorial.com
Project location: C:/android
Then click "Next".

Create Android Project Login

 Select the form factors and minimum SDK. In this tutorial, We selected the minimum SDK "API 15: Android 4.0.3(IceCreamSandwich)", click "Next".

Select the form factors and minimum SDK

Select the Empty activity and click "Next".

select the Activity

Leave the activity name “MainActivity”, Click Finish.

Configure Login Activity

Adding test.db file into the project

Right click on app folder goto New> Folder>Assets Folder

add assets in android Studio


Keep all the settings default on Dialog box. Under target source set, option main should be selected and Click Finish.

configure component assets

Now open app folder. you will find your Assets folder by the name of "assets". Copy file test.db to assets folder.
copy db to assets folder

view assets folder in project

Create DatabaseHelper class to the following
package com.jackrutorial.loginwithsqlitedbexample;

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

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "test.db";
    private static final int DATABASE_VERSION = 1;
    private final Context context;
    SQLiteDatabase db;

    private static final String DATABASE_PATH = "/data/data/com.jackrutorial.loginwithsqlitedbexample/databases/";
    private final String USER_TABLE = "user";


    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
        createDb();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void createDb(){
        boolean dbExist = checkDbExist();

        if(!dbExist){
            this.getReadableDatabase();
            copyDatabase();
        }
    }

    private boolean checkDbExist(){
        SQLiteDatabase sqLiteDatabase = null;

        try{
            String path = DATABASE_PATH + DATABASE_NAME;
            sqLiteDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        } catch (Exception ex){
        }

        if(sqLiteDatabase != null){
            sqLiteDatabase.close();
            return true;
        }

        return false;
    }

    private void copyDatabase(){
        try {
            InputStream inputStream = context.getAssets().open(DATABASE_NAME);

            String outFileName = DATABASE_PATH + DATABASE_NAME;

            OutputStream outputStream = new FileOutputStream(outFileName);

            byte[] b = new byte[1024];
            int length;

            while ((length = inputStream.read(b)) > 0){
                outputStream.write(b, 0, length);
            }

            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private SQLiteDatabase openDatabase(){
        String path = DATABASE_PATH + DATABASE_NAME;
        db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);
        return db;
    }

    public void close(){
        if(db != null){
            db.close();
        }
    }

    public boolean checkUserExist(String username, String password){
        String[] columns = {"username"};
        db = openDatabase();

        String selection = "username=? and password = ?";
        String[] selectionArgs = {username, password};

        Cursor cursor = db.query(USER_TABLE, columns, selection, selectionArgs, null, null, null);
        int count = cursor.getCount();

        cursor.close();
        close();

        if(count > 0){
            return true;
        } else {
            return false;
        }
    }


}

Change the activity_login.xml layout to the following.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.jackrutorial.loginwithsqlitedbexample.LoginActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_gravity="center"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Username: "
            />

        <EditText
            android:id="@+id/edtUsername"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password: "
            />

        <EditText
            android:id="@+id/edtPassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            />

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            />


    </LinearLayout>

</android.support.constraint.ConstraintLayout>

Change LoginActivity activity code to the following
package com.jackrutorial.loginwithsqlitedbexample;

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

public class LoginActivity extends AppCompatActivity {

    Button btnLogin;
    EditText edtUsername;
    EditText edtPassword;
    DatabaseHelper databaseHelper;

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

        btnLogin = (Button) findViewById(R.id.btnLogin);
        edtUsername = (EditText) findViewById(R.id.edtUsername);
        edtPassword = (EditText) findViewById(R.id.edtPassword);

        databaseHelper = new DatabaseHelper(LoginActivity.this);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isExist = databaseHelper.checkUserExist(edtUsername.getText().toString(), edtPassword.getText().toString());

                if(isExist){
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.putExtra("username", edtUsername.getText().toString());
                    startActivity(intent);
                } else {
                    edtPassword.setText(null);
                    Toast.makeText(LoginActivity.this, "Login failed. Invalid username or password.", Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
}

Create Activity

  • Click the app folder for your project and choose File > New > Activity > Empty Activity
  • Name the new activity "MainActivity".
  • Click Finish.
Change the activity_main.xml layout to the following.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.jackrutorial.loginwithsqlitedbexample.MainActivity">

    <TextView
        android:id="@+id/helloUser"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        />

</android.support.constraint.ConstraintLayout>

Change MainActivity activity code to the following.
package com.jackrutorial.loginwithsqlitedbexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView helloUser;

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

        helloUser = (TextView) findViewById(R.id.helloUser);

        Bundle extras = getIntent().getExtras();
        String username = null;
        if(extras != null){
            username = extras.getString("username");
            helloUser.setText("Welcome " + username);
        }

    }
}

Run this app in the Android Emulator

You can run this app from an Android Studio project. Or you can run this app that's been installed on the emulator as you would run any app on a device.
To start the emulator and run this app in your project
  • Open Android Studio project and click Run.
  • In the Select Deployment Target dialog, select an existing emulator definition, and then click OK.
Note
  • If you don’t see a definition you want to use, click Create New Virtual Device to launch the AVD Manager. After you define a new AVD, in the Select Deployment Target dialog, click OK.
  • If you want to use this emulator definition as the default for your project, select Use same selection for future launches
test login failed
test login successfully

Previous Post
Next Post

post written by: