Kotlin Login & Sign Up Using SQLite Database & SharedPreference Example

In this example, I will show you how to integrate a Login and Sign Up page with SQLite Database and SharedPreference in kotlin.

Kotlin Login & Sign Up Using SQLite Database & SharedPreference Example Video

  • You can also go through this video explanation.

Kotlin Login & Sign Up Using SQLite Database & SharedPreference Example

Creating a New Project

  • So first create a new Android Studio project using Kotlin.
  • Once the project is loaded come inside the activity_main.xml and remove the Hello World TextView.
Android studio project screen

Step 1:
Create new Package:- database
DatabaseHandler.kt
Create new class DatabaseHandler.kt under database package and Add following code.
package com.kotlinkatta.loginsqlite.database

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

class DatabaseHandler(context: Context): SQLiteOpenHelper(context, DATABASE_NAME,null, DATABASE_VERSION) {
companion object {
private val DATABASE_VERSION = 1
private val DATABASE_NAME = "database"

val user_table_name = "UserTable"
val user_key_id = "key_id"
val user_email_id = "email_id"
val user_password = "password"

val create_user_table = ("CREATE TABLE " + user_table_name + "("
+ user_key_id + " integer primary key autoincrement,"
+ user_email_id + " TEXT,"
+ user_password + " TEXT" + ")")
}

override fun onCreate(db: SQLiteDatabase?) {
db?.execSQL(create_user_table)
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db!!.execSQL("DROP TABLE IF EXISTS " + user_table_name)
onCreate(db)
}
}
Step 2:
DatabaseSingleton.kt
Create new class DatabaseSingleton.kt under database package and Add following code.
package com.kotlinkatta.loginsqlite.database

import android.content.Context
import android.database.sqlite.SQLiteDatabase

object DatabaseSingleton {
var database: SQLiteDatabase? = null
fun getInstance(activity: Context?): SQLiteDatabase? {
if (database == null) database =
DatabaseHandler(activity!!).getWritableDatabase()
return database
}
}
Step 3:
UserTableManager.kt
Create new class UserTableManager.kt under database package and Add following code.
package com.kotlinkatta.loginsqlite.database

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

class UserTableManager {
var sqLiteDatabase: SQLiteDatabase? = null
constructor(activity: Context?) {
sqLiteDatabase = DatabaseSingleton.getInstance(activity)
}

// Insert Sign User Data
fun insert_Sign_User_Data(email_id:String, password:String) {
val cv = ContentValues()
cv.put(DatabaseHandler.user_email_id, email_id)
cv.put(DatabaseHandler.user_password, password)
sqLiteDatabase!!.insert(DatabaseHandler.user_table_name, null, cv)
}

// check User Exists or not
fun check_user_exists(email_id:String, password:String): Boolean {
var count = 0
val countQuery = "select * from " + DatabaseHandler.user_table_name+ " where " +DatabaseHandler.user_email_id+ " = " + "'"+email_id+"'"+ " and " +DatabaseHandler.user_password+ " = " + "'"+password+"'"
val cursor = sqLiteDatabase!!.rawQuery(countQuery, null)
if (cursor != null && !cursor.isClosed) {
count = cursor.count
cursor.close()
}
return if (count > 0) {
true
} else {
false
}
}
}
Step 4:
Create new Package:- sharedPreference
SharedPref.kt
Create new class SharedPref.kt under sharedPreference package and Add following code.
package com.kotlinkatta.loginsqlite.sharedPreference

import android.content.Context
import android.content.SharedPreferences

class SharedPref (val context: Context) {
private val preference_Name = "Kotlinkatta"
val shared_Pref: SharedPreferences = context.getSharedPreferences(preference_Name, Context.MODE_PRIVATE)

/*Stored String Data*/
fun save_String(key_name: String, text: String) {
val editor: SharedPreferences.Editor = shared_Pref.edit()
editor.putString(key_name, text)
editor.commit()
}

fun getPreferenceString(key_name: String): String? {
return shared_Pref.getString(key_name, null)
}

fun clearSharedPreference() {
val editor: SharedPreferences.Editor = shared_Pref.edit()
editor.clear()
editor.commit()
}
}
Step 5:
sign_up_window.xml
Create new sign_up_window.xml  file under layout folder and Add following code.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/popup_element"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9999"
android:layout_gravity="center"
android:gravity="center"
android:orientation="vertical">

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
android:layout_margin="10dp"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#757575">

<TextView
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sign Up"
android:textColor="#FFF"
android:textSize="25dp"
android:gravity="center"/>

<EditText
android:id="@+id/edt_dia_email_id"
android:hint="Enter Email Id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"
android:background="#E7E7E7"/>

<EditText
android:id="@+id/edt_dia_password"
android:hint="Enter Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"
android:background="#E7E7E7"/>

<Button
android:id="@+id/btn_dia_submit"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Submit"
android:textAllCaps="false"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
</ScrollView>
</LinearLayout>
Step 6:
activity_main.xml
Add following code into activity_main.xml 
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="40dp"
android:fontFamily="sans-serif-black"
android:gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="30dp"/>

<EditText
android:id="@+id/edt_email"
android:hint="Enter Email Id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"
android:background="#E7E7E7"/>

<EditText
android:id="@+id/edt_password"
android:hint="Enter Password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"
android:background="#E7E7E7"/>

<Button
android:layout_marginTop="10dp"
android:id="@+id/btn_login"
android:text="Login"
android:textAllCaps="false"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<Button
android:layout_marginTop="10dp"
android:id="@+id/btn_sign_up"
android:textAllCaps="false"
android:text="Create New Account"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Step 7:
MainActivity.kt
Add following code into MainActivity.kt.
package com.kotlinkatta.loginsqlite

import android.app.ActionBar
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.PopupWindow
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.kotlinkatta.loginsqlite.database.UserTableManager
import com.kotlinkatta.loginsqlite.sharedPreference.SharedPref
import kotlinx.android.synthetic.main.sign_up_window.view.*

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

var sharedPreference =SharedPref(this)
var edt_email = findViewById<EditText>(R.id.edt_email)
var edt_password = findViewById<EditText>(R.id.edt_password)
var btn_login = findViewById<Button>(R.id.btn_login)
var btn_sign_up = findViewById<Button>(R.id.btn_sign_up)

val str_login_status = sharedPreference!!.getPreferenceString("login_status")
if (str_login_status!=null){
val intent = Intent(this, WelcomeActivity::class.java)
startActivity(intent)
finish()
}

btn_login.setOnClickListener {
val str_email_id = edt_email.text.toString()
val str_password = edt_password.text.toString()

if(str_email_id.equals("") || str_password.equals("")){
Toast.makeText(this,"Please Enter Details.",Toast.LENGTH_SHORT).show()
}else {

val user_exists: Boolean = UserTableManager(applicationContext).check_user_exists(str_email_id,str_password)
if (user_exists == true) {
sharedPreference!!.save_String("login_status","1")
val intent = Intent(this, WelcomeActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this,"Enter Valid Email Id & Password.",Toast.LENGTH_SHORT).show()
}
}
}

btn_sign_up.setOnClickListener {
fun_SignUp_PopupWindow()
}
}
private fun fun_SignUp_PopupWindow() {
val layoutInflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val popView: View = layoutInflater.inflate(R.layout.sign_up_window, null)
val popupWindow: PopupWindow
popupWindow = PopupWindow(popView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT,true)
popupWindow.showAtLocation(popView, Gravity.CENTER, 0, 0)

val btn_dia_submit = popView.findViewById(R.id.btn_dia_submit) as Button
btn_dia_submit.setOnClickListener {

val str_dia_email_id = popView.edt_dia_email_id.text.toString()
val str_dia_password = popView.edt_dia_password.text.toString()

if(str_dia_email_id.equals("") || str_dia_password.equals("")){
Toast.makeText(this,"Please Enter Details.",Toast.LENGTH_SHORT).show()
}else {
popupWindow.dismiss()
UserTableManager(applicationContext).insert_Sign_User_Data(str_dia_email_id,str_dia_password)
Toast.makeText(this,"Your Account Created Successfully.",Toast.LENGTH_SHORT).show()
}
}
}
}
Step 8:
Create new Empty Activity:- WelcomeActivity.kt
WelcomeActivity.kt
Add following code into WelcomeActivity.kt.
package com.kotlinkatta.loginsqlite

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import com.kotlinkatta.loginsqlite.sharedPreference.SharedPref

class WelcomeActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)

var sharedPreference =SharedPref(this)
var btn_log_out = findViewById<Button>(R.id.btn_log_out)
btn_log_out.setOnClickListener {
sharedPreference!!.clearSharedPreference()
Toast.makeText(this,"User LogOut Successfully.",Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
}
}
}
Step 9:
activity_welcome.xml
Add following code into activity_welcome.xml.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".WelcomeActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" >

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="30dp"
android:fontFamily="sans-serif-black"
android:textColor="#000000"
android:text="Welcome To DashBoard"
android:layout_marginTop="50dp"/>

<Button
android:layout_margin="30dp"
android:id="@+id/btn_log_out"
android:textAllCaps="false"
android:text="LogOut"
android:background="@color/colorAccent"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Output:





Comments