What is Kotlin?

1. Google announced Kotlin is an official language for android development.Kotlin is flexible and has some cool features and easy to use!
2. Kotlin is a statically-typed, modern programming language that runs on a Java Virtual Machine (JVM) by compiling Kotlin code into Java byte-code.
3. Kotlin is free and open to use
4. It can also be compiled to JavaScript source code to native executable.
5. Kotlin fully supported in Android Studio 3.0 and higher

Why Kotlin?

1. Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues. The Kotlin tooling is fully supported in Android Studio and compatible with the Android build system.

2. Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to very similar bytecode structure. With Kotlin's support for inline functions, code using lambdas often runs even faster than the same code written in Java.

3.Interoperability: Kotlin is 100% interoperable with Java, allowing to use all existing Android libraries in a Kotlin application. This includes annotation processing, so databinding and Dagger work too.

4. Footprint Kotlin has a very compact runtime library, which can be further reduced through the use of ProGuard. In a real application, the Kotlin runtime adds only a few hundred methods and less than 100K to the size of the .apk file.

What is SQLite?

1. SQLite is one of the ways of storing data. It is very lightweight database that comes with Android OS.
2. In Android, integrating SQLite is a tedious task as it needs writing lot of boilerplate code to store simple data. Consider SQLite when your app needs to store simple data objects.
3. For many applications, SQLite is the app’s backbone whether it’s used directly or via some third-party wrapper. In this tutorial, we will write code in Kotlin and also see how to use SQLite in our app directly.

Key point to understand regarding SQLite in this project: -

1. SQLite is RDBMS (Relational Database Management System)
2. SQLite is written in programming language
3. SQLite is embedded within the Android Operating System, so you don’t need anything external on Android to use SQLite
4. To manipulate data (insert, update, delete) in SQLite database – we’ll use SQL (Structured Query Language)

In this tutorial, we are going to learn how to use SQLite using Kotlin. To really understand the usage of SQLite we will create an app using Kotlin. The App contains simple Login form, Registration form. This app shows how SQLite database operations are performed.

What is Material Design?

1. Material Design is a visual language developed by Google which was first introduced with Lollipop OS and since then it has become popular in designing and developing Android Apps.
2. Material Design is a visual language that synthesizes the classic principles of good design with the innovation of technology and science.

Follow the below steps to developed the Login and registration form with Kotlin in android studio 3.0 and higher using SQLite:

Create a new android project.

1. Add libraries to build.gradle file.

1. For designing purpose, you can use Material Design.
2. Add Gradle dependencies libraries in your build.gradle file and rebuilt the project successfully.

dependencies
 {
    Implementation 'com.android.support:appcompat-v7:27.1.1'
    Implementation 'com.android.support:design:27.1.1'
    Implementation 'com.android.support:cardview-v7:27.1.1'
}

2. Update strings.xml located in res->values->string.xml.

Add the below string values to the string.xml file located in res ⇒ values ⇒ strings.xml.

<resources>
    <!--App name-->
    <string name="app_name">ToDoListKotlinApp</string>
    <!--registration-->
    <string name="hint_name">Username</string>
    <string name="hint_pass">Password</string>
    <string name="hint_email">Email</string>
    <string name="register_txt">No account yet? Create one</string>
    <string name="registration_text">REGISTER</string>
    <!--Login-->
    <string name="login_text">LOGIN</string>
    <string name="already_login_txt">Already a member? Login</string>
    <!--error message-->
    <string name="error_message_name">Please enter valid name</string>
    <string name="error_message_email">Please enter valid email</string>
    <string name="error_message_password">Please enter valid password</string>
    <string name="error_email_exists">User may already exist</string>
    <!--success message-->
    <string name="success_message">User added successfully</string>
    <string name="login_success_message">User logged successfully</string>

</resources>

Please refer below attachment for string.xml file declaration:

3. Update colors.xml located in res->values->colors.xml.

Add the below color values to the colors.xml located in res ⇒ values ⇒ colors.xml.

<resources>
    <color name="colorPrimary">#b71c1c</color>
    <color name="colorPrimaryDark">#7f0000</color>
    <color name="colorAccent">#FF4081</color>
    <color name="df_red">#dc3545</color>
    <color name="df_danger">#dc3545</color>
    <color name="formBg">#f0f0f0</color>
    <color name="black_alpha_75">#bf000000</color>
    <color name="colorText">#ffffffff</color>
</resources>

This colors are used in form background, toolbar, actionbar, textview colors.

4. Update styles.xml located in res->values->styles.xml.

Add the below style values to the styles.xml located in res ⇒ values ⇒ styles.xml.

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

        <item name="colorPrimary">@color/colorPrimary</item>

        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

        <item name="colorAccent">@color/colorAccent</item>

    </style>

</resources>

Please refer below attachment for style.xml file

5. Add Logo Image in res->drawable.

Add logo image to the drawable folder located in res ⇒ drawable.

Please refer below path to add resource in drawable file.

6. Create User model class in model package.

Create a new package named model or you say it as a pojo class and create a Kotlin class named UserModel to maintain single user as an object.

package com.itw.todolistkotlinapp.model

class UserModel(val userid: Int = -1, val name: String, val email: String, val pass:  String)

7. Create DbHelper class in dbmanager package.

Create a new package named dbmanager and create Kotlin class named DBHelper. Extend this class with SQLiteOpenHelper to manage database creation and version management. I have written methods for database operations.

 

Methods and functionality

1. addUser:- add user to database.
2. getAllUser:- fetch user’s data from database.
3. checkUser :- check whether user exists in database.

Write the below code in DBHelper.txt file.

package com.itw.todolistkotlinapp.dbmanager

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import android.support.annotation.IntegerRes
import com.itw.todolistkotlinapp.model.UserModel

class DBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(SQL_CREATE_ENTRIES)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        db?.execSQL(SQL_DELETE_ENTRIES)
        onCreate(db)
    }

    override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        onUpgrade(db, oldVersion, newVersion)
    }

    @Throws(SQLiteConstraintException::class)
    fun insertUser(user: UserModel): Boolean {
// Gets the data repository in write mode
        val db = writableDatabase
// Create a new map of values, where column names are the keys
        val values = ContentValues()
        values.put(USER_NAME, user.name)
        values.put(USER_EMAIL, user.email)
        values.put(USER_PASS, user.pass)

// Insert the new row, returning the primary key value of the new row
        db.insert(TABLE_NAME, null, values)
        db.close()
        return true
    }

    @Throws(SQLiteConstraintException::class)
    fun deleteUser(userid: String): Boolean {
// Gets the data repository in write mode
        val db = writableDatabase
// Define 'where' part of query.
        val selection = USER_ID + " LIKE ?"
// Specify arguments in placeholder order.
        val selectionArgs = arrayOf(userid)
// Issue SQL statement.
        db.delete(TABLE_NAME, selection, selectionArgs)
        return true
    }
    /**
     * This method to check user exist or not
     *
     * @param email
     * @return true/false
     */
    fun checkUser(email: String): Boolean {

        // array of columns to fetch
        val columns = arrayOf(USER_ID)
        val db = this.readableDatabase

        // selection criteria
        val selection = "$USER_EMAIL = ?"
        // selection argument
        val selectionArgs = arrayOf(email)
        // query user table with condition
        /**
         * Here query function is used to fetch records from user table this function works like we use sql query.
         * SQL query equivalent to this query function is
         * SELECT user_id FROM user WHERE user_email = 'abc@d.com';
         */
        val cursor = db.query(
            TABLE_NAME, //Table to query
            columns,        //columns to return
            selection,      //columns for the WHERE clause
            selectionArgs,  //The values for the WHERE clause
            null,  //group the rows
            null,   //filter by row groups
            null
        )  //The sort order

        val cursorCount = cursor.count
        cursor.close()
        db.close()

        if (cursorCount > 0) {
            return true
        }
        return false
    }

    fun getUserIdByEmail(email: String): Int {

        val db = this.readableDatabase
        val cursor = db.query(
            TABLE_NAME, null, "$USER_EMAIL = ?", arrayOf(email),
            null, null, null
        )
        if (cursor.getCount() < 1) {
            return 0;
        } else {
            cursor.moveToFirst()
            val userID: Int = cursor.getString(cursor.getColumnIndex(USER_ID)).toInt()
            return userID;
        }
    }

    fun getAllUser(): ArrayList {

        // array of columns to fetch
        val columns = arrayOf(USER_NAME, USER_EMAIL, USER_PASS)

        // sorting orders
        val sortOrder = "$USER_NAME ASC"
        val userList = ArrayList()

        val db = this.readableDatabase

        // query the user table
        val cursor = db.query(
            TABLE_NAME, //Table to query
            columns,            //columns to return
            null,     //columns for the WHERE clause
            null,  //The values for the WHERE clause
            null,      //group the rows
            null,       //filter by row groups
            sortOrder
        )         //The sort order
        if (cursor.moveToFirst()) {
            do {
                val user = UserModel(
                    name = cursor.getString(cursor.getColumnIndex(USER_NAME)),
                    email = cursor.getString(cursor.getColumnIndex(USER_EMAIL)),
                    pass = cursor.getString(cursor.getColumnIndex(USER_PASS))
                )

                userList.add(user)
            } while (cursor.moveToNext())
        }
        cursor.close()
        db.close()
        return userList
    }

    companion object {
        // If you change the database schema, you must increment the database version.
        val DATABASE_VERSION = 1
        val DATABASE_NAME = "User.db"
        val TABLE_NAME = "USER";
        val USER_ID = "USER_ID";
        val USER_NAME = "NAME";
        val USER_EMAIL = "EMAIL";
        val USER_PASS = "PASS";

        private val SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + "(" +
                    USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                    USER_NAME + " TEXT NOT NULL," +
                    USER_EMAIL + " TEXT NOT NULL," +
                    USER_PASS + " TEXT NOT NULL)"

        private val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + TABLE_NAME
    }
}

8. Create activity_login.xml in res->layout->activity_login.xml.

Now create a layout file for the LoginActivity.kt i.e activity_login.xml and add the below code in your layout file.

<LinearLayout
        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"
        android:orientation="vertical"
        tools:context="com.itw.todolistkotlinapp.activity.LoginActivity">

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="0.55"
            android:gravity="center"
            android:background="@color/df_danger">

        <ImageView
                android:id="@+id/imgKotlin"
                android:layout_width="200dp"
                android:layout_height="100dp"
                android:src="@drawable/kotlin"
                android:layout_centerInParent="true"
        />

    </LinearLayout>
    <LinearLayout
            android:layout_weight=".5"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_margin="10dp"
            android:orientation="vertical"
            android:gravity="bottom"
            android:layout_gravity="bottom">

        <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayoutEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="40dp">

            <android.support.design.widget.TextInputEditText
                    android:id="@+id/textInputEditTextEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/hint_email"
                    android:inputType="text"
                    android:maxLines="1"
                    android:textColor="@android:color/black"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayoutPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp">
            <android.support.design.widget.TextInputEditText
                    android:id="@+id/textInputEditTextPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/hint_pass"
                    android:inputType="textPassword"
                    android:maxLines="1"
                    android:textColor="@android:color/black"/>
        </android.support.design.widget.TextInputLayout>
        <Button
                android:id="@+id/button_check_user"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="checkUser"
                android:text="@string/login_text"
                android:layout_gravity="center"/>

        <TextView
                android:id="@+id/textview_result"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        <LinearLayout
                android:id="@+id/ll_entries"
                android:padding="15dp"
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"></LinearLayout>
        <TextView
                android:gravity="center"
                android:id="@+id/txtLogin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/register_txt"
                android:onClick="openRegister"/>
    </LinearLayout>
</LinearLayout>

The below screen shows the login form with input validation

9. Create InputValidation class in utils->InputValidation.kt.

Create a package named utils and create a Kotlin class in it named InputValidation.kt and add below code in it. The code will create validation methods for input field. Validation like empty input, valid email and etc.

package com.itw.todolistkotlinapp.utils

import android.app.Activity
import android.content.Context
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager

class InputValidation

    /**
     * constructor
     *
     * @param context
     */
    (private val context: Context) {

        /**
         * method to check InputEditText filled .
         *
         * @param textInputEditText
         * @param textInputLayout
         * @param message
         * @return
         */
        fun isInputEditTextFilled(textInputEditText: TextInputEditText, textInputLayout: TextInputLayout, message: String): Boolean {
            val value = textInputEditText.text.toString().trim()
            if (value.isEmpty()) {
                textInputLayout.error = message
                hideKeyboardFrom(textInputEditText)
                return false
            } else {
                textInputLayout.isErrorEnabled = false
            }

            return true
        }
/**
         * method to check InputEditText has valid email .
         *
         * @param textInputEditText
         * @param textInputLayout
         * @param message
         * @return
         */
        fun isInputEditTextEmail(textInputEditText: TextInputEditText, textInputLayout: TextInputLayout, message: String): Boolean {
            val value = textInputEditText.text.toString().trim()
            if (value.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(value).matches()) {
                textInputLayout.error = message
                hideKeyboardFrom(textInputEditText)
                return false
            } else {
                textInputLayout.isErrorEnabled = false
            }
            return true
        }

        /**
         * method to check both InputEditText value matches.
         *
         * @param textInputEditText1
         * @param textInputEditText2
         * @param textInputLayout
         * @param message
         * @return
         */
        fun isInputEditTextMatches(textInputEditText1: TextInputEditText, textInputEditText2: TextInputEditText, textInputLayout: TextInputLayout, message: String): Boolean {
            val value1 = textInputEditText1.text.toString().trim()
            val value2 = textInputEditText2.text.toString().trim()
            if (!value1.contentEquals(value2)) {
                textInputLayout.error = message
                hideKeyboardFrom(textInputEditText2)
                return false
            } else {
                textInputLayout.isErrorEnabled = false
            }
            return true
        }

        /**
         * method to Hide keyboard
         *
         * @param view
         */
        private fun hideKeyboardFrom(view: View) {
            val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
        }

}

10. Create LoginActivity class in activity->LoginActivity.kt.

Create a package named activities and create a kotlin class named LoginActivity and add below code. Here i have written the code to validate the input fields Email and Password using the InputValidation class which i described above. Also code for navigation to registration screen on the click of registration link.

package com.itw.todolistkotlinapp.activity

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.view.View
import android.widget.Toast
import com.itw.todolistkotlinapp.R
import com.itw.todolistkotlinapp.dbmanager.DBHelper
import com.itw.todolistkotlinapp.utils.InputValidation
import com.itw.todolistkotlinapp.utils.ToDoPref




class LoginActivity : AppCompatActivity() {

    private lateinit var databaseHelper: DBHelper
    private lateinit var textInputLayoutEmail: TextInputLayout
    private lateinit var textInputLayoutPassword: TextInputLayout
    private lateinit var textInputEditTextEmail: TextInputEditText
    private lateinit var textInputEditTextPassword: TextInputEditText
    private lateinit var inputValidation: InputValidation

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initObjects()
    }

    fun checkUser(v: View) {
        if (!inputValidation!!.isInputEditTextFilled(
                textInputEditTextEmail!!,
                textInputLayoutEmail!!,
                getString(R.string.error_message_email)
            )
        ) {
            return
        }
        if (!inputValidation!!.isInputEditTextEmail(
                textInputEditTextEmail!!,
                textInputLayoutEmail!!,
                getString(R.string.error_message_email)
            )
        ) {
            return
        }
        if (!inputValidation!!.isInputEditTextFilled(
                textInputEditTextPassword!!,
                textInputLayoutPassword!!,
                getString(R.string.error_message_password)
            )
        ) {
            return
        }

        if (databaseHelper!!.checkUser(textInputEditTextEmail!!.text.toString().trim())) {
            Toast.makeText(this, getString(R.string.success_message), Toast.LENGTH_LONG).show()
            ToDoPref.getUserId = databaseHelper.getUserIdByEmail(textInputEditTextEmail!!.text.toString())
            val accountsIntent = Intent(this, HomeActivity::class.java)
            startActivity(accountsIntent)
            finish()
        } else {
            Toast.makeText(this, "not exist", Toast.LENGTH_LONG).show()
        }

    }
    
    fun openRegister(v: View) {
        val intent = Intent(this, RegisterActivity::class.java)
        startActivity(intent)
        finish()
    }

    private fun initObjects() {
        inputValidation = InputValidation(this)
        databaseHelper = DBHelper(this)
        textInputLayoutEmail = findViewById(R.id.textInputLayoutEmail) as TextInputLayout
        textInputLayoutPassword = findViewById(R.id.textInputLayoutPassword) as TextInputLayout
        textInputEditTextEmail = findViewById(R.id.textInputEditTextEmail) as TextInputEditText
        textInputEditTextPassword = findViewById(R.id.textInputEditTextPassword) as TextInputEditText

    }

}

The below screen shows the login form with input validation display the error message if values entered in input fields are not valid.

 

11. Create activity_register.xml in res->layout->activity_register.xml.

Now create a layout file for the RegisterActivity.kt i.e activity_register.xml and add the below code in your layout file. The code will create a simple registration form containing logo on the top with input fields and login screen navigation link.

<LinearLayout 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"
              android:orientation="vertical"
          tools:context="com.itw.todolistkotlinapp.activity.RegisterActivity">

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.55"
        android:gravity="center"
        android:background="@color/df_danger">
    <ImageView
            android:id="@+id/imgKotlin"
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:src="@drawable/kotlin"
            android:layout_centerInParent="true" />

</LinearLayout>

<android.support.v7.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.5"
        android:orientation="vertical"
        android:gravity="bottom"
        android:layout_gravity="center"
        android:layout_margin="10dp">

   

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

        <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayoutName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center">

            <android.support.design.widget.TextInputEditText
                    android:id="@+id/textInputEditTextName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="start"
                    android:hint="@string/hint_name"
                    android:textColorHint="@android:color/black"
                    android:inputType="text"
                    android:maxLines="1"
                    android:textColor="@android:color/black"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayoutEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center">

            <android.support.design.widget.TextInputEditText
                    android:id="@+id/textInputEditTextEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="start"
                    android:textColorHint="@android:color/white"
                    android:hint="@string/hint_email"
                    android:inputType="text"
                    android:maxLines="1"
                    android:textColor="@android:color/black"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
                android:id="@+id/textInputLayoutPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center">
            <android.support.design.widget.TextInputEditText
                    android:id="@+id/textInputEditTextPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:gravity="start"
                    android:textColorHint="@android:color/white"
                    android:hint="@string/hint_pass"
                    android:inputType="textPassword"
                    android:maxLines="1"
                    android:textColor="@android:color/black"/>
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
        <Button
                android:id="@+id/button_add_user"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="addUser"
                android:text="@string/registration_text"/>
        <Button
                android:id="@+id/button_delete_user"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="deleteUser"
                android:text="Delete"
                android:visibility="gone"/>
        <Button
                android:id="@+id/button_show_all"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="showAllUsers"
                android:text="Show All"
                android:visibility="gone"/>
    </LinearLayout>
    <TextView
            android:id="@+id/textview_result"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    <TextView
            android:gravity="center"
            android:id="@+id/txtLogin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/already_login_txt"
            android:onClick="openLogin"/>
</android.support.v7.widget.LinearLayoutCompat>
</LinearLayout>

activity_register.xml would result a screen like this:

12. Create RegisterActivity class in activity->RegisterActivity.kt.

Create a kotlin class named RegisterActivity and add below code.

Below code is written to validate the input fields Name, Email, Password using the InputValidation class which i described above. Also code for navigation to login screen on the click of login link and shows snackbar with success message for registration.

Please add RegisterActivity.kt file into below location :

package com.itw.todolistkotlinapp.activity

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.support.design.widget.TextInputLayout
import android.view.View
import android.widget.TextView
import android.widget.Toast
import com.itw.todolistkotlinapp.R
import com.itw.todolistkotlinapp.dbmanager.DBHelper
import com.itw.todolistkotlinapp.model.UserModel
import com.itw.todolistkotlinapp.utils.InputValidation
import kotlinx.android.synthetic.main.activity_main.*

class RegisterActivity : AppCompatActivity(){

    lateinit var usersDBHelper: DBHelper

    private lateinit var textInputLayoutName: TextInputLayout
    private lateinit var textInputLayoutEmail: TextInputLayout
    private lateinit var textInputLayoutPassword: TextInputLayout
    private lateinit var textInputEditTextName: TextInputEditText
    private lateinit var textInputEditTextEmail: TextInputEditText
    private lateinit var textInputEditTextPassword: TextInputEditText

    private lateinit var inputValidation: InputValidation
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        usersDBHelper = DBHelper(this)
        inputValidation = InputValidation(this)
        initViews()
    }
    /**
     * This method is to initialize views
     */
    private fun initViews() {

        textInputLayoutName = findViewById(R.id.textInputLayoutName) as TextInputLayout
        textInputLayoutEmail = findViewById(R.id.textInputLayoutEmail) as TextInputLayout
        textInputLayoutPassword = findViewById(R.id.textInputLayoutPassword) as TextInputLayout
        textInputEditTextName = findViewById(R.id.textInputEditTextName) as TextInputEditText
        textInputEditTextEmail = findViewById(R.id.textInputEditTextEmail) as TextInputEditText
        textInputEditTextPassword = findViewById(R.id.textInputEditTextPassword) as TextInputEditText

    }
    fun addUser(v: View){
        if (!inputValidation!!.isInputEditTextFilled(textInputEditTextName, textInputLayoutName, getString(R.string.error_message_name))) {
            return
        }
        if (!inputValidation!!.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
            return
        }
        if (!inputValidation!!.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
            return
        }
        if (!inputValidation!!.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_password))) {
            return
        }
        if (!usersDBHelper!!.checkUser(textInputEditTextEmail!!.text.toString().trim())) {
            var result = usersDBHelper.insertUser(UserModel(name = textInputEditTextName!!.text.toString().trim(),
                email = textInputEditTextEmail!!.text.toString().trim(),
                pass = textInputEditTextPassword!!.text.toString().trim()))

            //clear all edittext s
            this.textInputEditTextEmail.setText("")
            this.textInputEditTextName.setText("")
            this.textInputEditTextPassword.setText("")
            this.textview_result.text = "Added user : "+result
            Toast.makeText(this,  getString(R.string.success_message), Toast.LENGTH_LONG).show()

            this.ll_entries.removeAllViews()
        }else {
            Toast.makeText(this,  getString(R.string.error_email_exists), Toast.LENGTH_LONG).show()
        }

    }
    fun deleteUser(v:View){
        var userid = this.textInputEditTextPassword.text.toString()
        val result = usersDBHelper.deleteUser(userid)
        this.textview_result.text = "Deleted user : "+result
        this.ll_entries.removeAllViews()
    }
    fun showAllUsers(v:View){
        var users = usersDBHelper.getAllUser()
        this.ll_entries.removeAllViews()
        users.forEach {
            var tv_user = TextView(this)
            tv_user.textSize = 30F
            tv_user.text = it.userid.toString() + " " + it.name.toString() + "  " + it.email.toString()
            this.ll_entries.addView(tv_user)
        }
        this.textview_result.text = "Fetched " + users.size + " users"
    }
    fun openLogin(v: View){
        val intent = Intent(this, LoginActivity::class.java)
        startActivity(intent)
        finish()
    }
}

Below screen shows the register form with input validation display the error message if values entered in input fields are not valid.

Below Screen shows the filled register form with valid values.

Below screen shows the register form display the toast with registration success message.

13. Update AndroidManifest.xml.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.itw.todolistkotlinapp">

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme"
            android:name=".app.ToDoApplication"
        >
        <activity android:name=".activity.LoginActivity">
        </activity>

        <activity android:name=".activity.RegisterActivity">
        </activity>

        <activity android:name=".activity.HomeActivity">
        </activity>

        <activity android:name=".activity.AppStartActivity">
        </activity>

        <activity android:name=".activity.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

Words from our clients

 

Tell Us About Your Project

We’ve done lot’s of work, Let’s Check some from here