Hello guys, in this example we are going to learn SQLite Databse CRUD operaitions with Room Database in Kotlin.

What is Room?
Room is one of android architecure component, which is an abstact layer for the Sqlite Database
By using the room we can hanlde the SQLite Database is easily

Room having 3 main modules
Entity : Entity Represents a table in the database. To create a table with entity we need to annotate class with @Entity
DAO Data : Access Object is used to access and manage the Data. DAO is an interface wich is annotate with @DAO
Database : It works as database holder, A class annotated with @Database and extends with Roomdatabase


In this example we are going to learn CRUD operaitons with Signup and Registration of user.
So Let's start the coding.



Room is Architecture component, we need to add dependencies in our build.gradle file

build.gradle

we are going to use kotlin for this example, so apply plugin: 'kotlin-kapt' sould be add in build.gradle file




apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'
android {
    compileSdkVersion 29
    defaultConfig {
        applicationId "com.rrtutors.roomwithkotlin"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
ext {
    roomVersion = '2.2.1'
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'

    implementation 'androidx.core:core-ktx:1.2.0-rc01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.0-alpha4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0-alpha4'
    implementation "androidx.room:room-runtime:$roomVersion"
    kapt "androidx.room:room-compiler:$roomVersion"
    implementation 'com.google.android.material:material:1.0.0'
}


DataBase Section Registration.kt is an Entity class which is annotation with @Entity, this class is represents registration table in the database.



@Entity(tableName = "registration")
class Registration(  @ColumnInfo (name="name") var name:String,
                   @ColumnInfo (name="email") var email:String 
                     ,@ColumnInfo(name="password") var password:String,
                     @ColumnInfo(name="mobile") var mobile:String) {
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name="_id")
    var id:Int=0 ;
}


Registration Entity having the fileds name,email,password,mobile Each filed we are annotated with @ColumnInfo, this will represents the column name in the registration table. _id filed is primary key with autogenrated filed


RegistrationDAO.kt is DAO interface which handles the registration table data. This will be annotated with @DAO In this DAO interface we are created abstract methods to hanlde CRUD operations.



@Dao
interface RegistrationDAO {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(registration:Registration)

    @Query("select * from registration where email=:email and password=:pass")
    fun checkLogin(email:String,pass:String):List ;

    @Query("select * from registration where _id=:id")
    fun fetchUser(id:Int):Registration;

    @Delete
    fun deleteUser(registration:Registration):Int
}
    


Now Lets create our Database

MyDatabase.kt is our Database class which is abstract class annotated by @Database. @Database annoation having the fileds
entities -> represents the tables which we are going to use in the Database.
version -> represetns databse version
exportSchema -> represents, do we need to export our database schema into specified folder location, by default its value is true.


    @Database(entities = arrayOf(Registration::class),version = 1,exportSchema = false)
abstract class MyDatabase:RoomDatabase() {

    companion object{
        var instance:MyDatabase?=null;
        fun getInstance(ctx:Context):MyDatabase
        {
            if(instance!=null)
            {
                return  instance as MyDatabase;
            }
            instance= Room.databaseBuilder(ctx,MyDatabase::class.java,"mydb").run { allowMainThreadQueries() }.build();
            return instance as MyDatabase;
        }
    }
   abstract fun registrationDAO():RegistrationDAO;
}

In the above class we defined a abstract function registrationDAO which returns the RegistrationDAO class instance to handle the database operations. If we have more DAO class for different Entities we need to defind abstract functions in the Databse class to handle the database operations.


UI Section
In this example we are going to use the SplashScreen,Signup,Login and Homescreen.
I have designs screens in some Look and feel, for that lets check the resources.


background.xml

    
        <?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
       xmlns:android="https://schemas.android.com/apk/res/android" >

    <gradient android:angle="0"
              android:startColor="#F00E5B"
              android:endColor="#F44336"/>

</shape>



button_background.xml

    <?xml version="1.0" encoding="utf-8"?>

<ripple xmlns:android="https://schemas.android.com/apk/res/android"
        android:color="#0dafdc">

    <item>
        <shape android:shape="rectangle"
        >


            <corners
                    android:radius="100dp"/>


            <gradient android:angle="0"
                      android:startColor="#E20650"
                      android:endColor="#F44336"/>

        </shape>
    </item>
</ripple >




layout_background.xml

    <?xml version="1.0" encoding="utf-8"?>

<vector xmlns:android="https://schemas.android.com/apk/res/android"
        android:viewportWidth="500"
        android:viewportHeight="749"
        android:width="625dp"
        android:height="936.25dp">
    <group
            android:scaleX="0.1"
            android:scaleY="-0.1"
            android:translateY="749">
        <path
                android:pathData="M439 7416C282 7361 169 7248 113 7090l-23 -65 0 -1751c0 -1693 1 -1753 19 -1806 35 -101 99 -185 184 -241 57 -38 90 -50 442 -162 132 -42 701 -224 1265 -405 564 -180 1084 -346 1155 -368 72 -22 362 -114 645 -206 558 -179 630 -196 749 -177 165 27 267 129 316 316 13 53 15 321 15 2410 0 2572 4 2397 -58 2523 -56 115 -184 223 -310 262 -63 20 -97 20 -2036 20l-1971 0 -66 -24z"
                android:fillColor="#ffffff" />
        <path
                android:pathData="M498 2820C322 2790 207 2702 128 2534L95 2465 92 1476C90 496 90 486 110 424 155 289 255 178 389 112l76 -37 1998 -3 1997 -2 63 21c160 53 293 193 338 357 17 59 19 106 19 407 0 369 -4 404 -56 507 -55 109 -179 205 -304 237 -25 7 -54 16 -65 21 -11 5 -206 68 -433 140 -227 72 -677 214 -1000 316 -323 102 -623 197 -667 211 -44 14 -343 108 -665 210 -322 102 -691 218 -820 259 -240 76 -271 81 -372 64z"
                android:fillColor="#ffffff" />
    </group>
</vector>




activity_signup.xml

    <?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
                xmlns:app="https://schemas.android.com/apk/res-auto"
                xmlns:tools="https://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/background"
               >

    <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/background"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
    >

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Sign Up"
                android:textStyle="bold"
                android:textColor="#FFEB3B"
                android:textSize="25sp"
                android:textAlignment="center"
        />
    </androidx.appcompat.widget.Toolbar>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/toolbar"
            android:orientation="vertical"
            android:layout_centerHorizontal="true">
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_marginStart="20dp"
                android:layout_marginEnd="20dp"
                android:layout_marginTop="20dp"
                android:orientation="vertical"
                android:layout_height="match_parent"
                android:layout_marginBottom="20dp"
                android:gravity="center"
                android:background="@drawable/layout_background">


            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="vertical"
            >
            <com.google.android.material.textfield.TextInputLayout 
            android:layout_marginTop="0dp" 
            android:layout_width="match_parent" 
            android:layout_height="wrap_content">

                <androidx.appcompat.widget.AppCompatEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:layout_marginEnd="20dp"
                        android:id="@+id/et_name"
                        android:layout_marginStart="20dp"
                        android:textSize="14sp"

                        android:hint="NAME"
                        android:padding="10dp"
                        android:textColorHint="#606060"
                        android:inputType="textPersonName"/>
            </com.google.android.material.textfield.TextInputLayout>
                <com.google.android.material.textfield.TextInputLayout 
                android:layout_marginTop="0dp" 
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                <androidx.appcompat.widget.AppCompatEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:id="@+id/et_email"

                        android:layout_marginEnd="20dp"
                        android:layout_marginStart="20dp"
                        android:hint="EMAIL"
                        android:padding="10dp"
                        android:textSize="14sp"
                        android:textColorHint="#606060"
                        android:inputType="text"/>
                </com.google.android.material.textfield.TextInputLayout>
                <com.google.android.material.textfield.TextInputLayout 
                android:layout_marginTop="0dp" 
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                    <androidx.appcompat.widget.AppCompatEditText
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"

                            android:id="@+id/et_mobile"

                            android:layout_marginEnd="20dp"
                            android:layout_marginStart="20dp"
                            android:hint="MOBILE"
                            android:padding="10dp"
                            android:textSize="14sp"
                            android:maxLength="11"
                            android:textColorHint="#606060"
                            android:inputType="number"/>
               </com.google.android.material.textfield.TextInputLayout>

                <com.google.android.material.textfield.TextInputLayout
                android:layout_marginTop="0dp" 
                android:layout_width="match_parent"
                android:layout_height="wrap_content" 
                app:passwordToggleEnabled="true" >

                <androidx.appcompat.widget.AppCompatEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"


                        android:layout_marginEnd="20dp"
                        android:id="@+id/et_password"
                        android:layout_marginStart="20dp"
                        android:textSize="14sp"

                        android:hint="PASSWORD"
                        android:padding="10dp"
                        android:textColorHint="#606060"
                        android:inputType="textPassword"/>
                </com.google.android.material.textfield.TextInputLayout>

                <CheckBox
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Agree to Terms & Conditions"
                        android:id="@+id/checkbox"
                        android:textColor="#9C27B0"
                        android:layout_marginTop="10dp"
                        android:layout_marginLeft="30dp" />

                <ImageButton
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:layout_gravity="end"
                        android:layout_marginTop="5dp"
                        android:layout_marginEnd="25dp"
                        android:id="@+id/signup"
                        android:rotation="180"
                        android:src="@drawable/ic_enter_arrow"
                        android:background="@drawable/button_background"/>


            </LinearLayout>

            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:gravity="center">
                <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:text="Already have an Account"

                        android:textAlignment="center"
                        android:textColor="#9C27B0"
                        android:textStyle="bold" />

                <Button
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginLeft="40dp"
                        android:layout_marginRight="40dp"
                        android:layout_marginTop="10dp"
                        android:id="@+id/signin"
                        android:background="@drawable/button_background"
                        android:text="SIGN IN"
                        android:textColor="@android:color/white" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>




activity_login.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
                xmlns:app="https://schemas.android.com/apk/res-auto"
                xmlns:tools="https://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/background"
                >


    <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/background"
            android:minHeight="?attr/actionBarSize"
            android:theme="?attr/actionBarTheme"
    >

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="LOGIN"
                android:textStyle="bold"
                android:textColor="#FFEB3B"
                android:textSize="30sp"

                android:textAlignment="center"
        />
    </androidx.appcompat.widget.Toolbar>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/toolbar"
            android:orientation="vertical"
            android:layout_marginTop="0dp">
        <LinearLayout
                android:layout_width="match_parent"
                android:layout_marginStart="20dp"
                android:layout_marginEnd="20dp"
                android:layout_marginTop="20dp"
                android:orientation="vertical"
                android:layout_height="wrap_content"
                android:layout_marginBottom="20dp"
                android:gravity="center"
                android:background="@drawable/layout_background">

            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="345dp"
                    android:orientation="vertical"
            >
                <com.google.android.material.textfield.TextInputLayout android:layout_marginTop="16dp" android:layout_width="match_parent" android:layout_height="wrap_content">

                <androidx.appcompat.widget.AppCompatEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:drawablePadding="10dp"
                        android:id="@+id/email"

                        android:layout_marginEnd="20dp"
                        android:layout_marginStart="20dp"
                        android:hint="EMAIL/MOBILE"
                        android:padding="20dp"
                        android:textSize="14sp"
                        android:textColorHint="#606060"
                        android:inputType="text"/>
            </com.google.android.material.textfield.TextInputLayout>
                <com.google.android.material.textfield.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content" app:passwordToggleEnabled="true">

                <androidx.appcompat.widget.AppCompatEditText
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="10dp"

                        android:layout_marginEnd="20dp"
                        android:id="@+id/password"
                        android:layout_marginStart="20dp"
                        android:textSize="14sp"
                        android:drawablePadding="10dp"
                        android:hint="PASSWORD"
                        android:padding="20dp"
                        android:textColorHint="#606060"
                        android:inputType="textPassword"/>
                </com.google.android.material.textfield.TextInputLayout>

                <CheckBox
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="REMEMBER ME"
                        android:id="@+id/checkbox"
                        android:textColor="#9C27B0"
                        android:layout_marginTop="20dp"
                        android:layout_marginLeft="30dp"/>

                <ImageButton
                        android:layout_width="50dp"
                        android:layout_height="50dp"
                        android:layout_gravity="end"
                        android:layout_marginTop="70dp"
                        android:layout_marginEnd="25dp"
                        android:id="@+id/signin"
                        android:rotation="180"
                        android:src="@drawable/ic_enter_arrow"
                        android:background="@drawable/button_background"/>


            </LinearLayout>

            <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical"
                    android:gravity="center">
                <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginTop="25dp"
                        android:text="Don't have an Account"
                        android:textAlignment="center"
                        android:textColor="#9C27B0"
                        android:textStyle="bold"/>

                <Button
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginLeft="40dp"
                        android:layout_marginRight="40dp"
                        android:layout_marginTop="10dp"
                        android:id="@+id/signup"
                        android:background="@drawable/button_background"
                        android:text="SIGN UP"
                        android:textColor="@android:color/white"/>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>


LoginActivity.kt

package com.rrtutors.roomwithkotlin.ui

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.Toolbar
import com.rrtutors.roomwithkotlin.AppPref
import com.rrtutors.roomwithkotlin.R
import com.rrtutors.roomwithkotlin.database.MyDatabase
import com.rrtutors.roomwithkotlin.entities.Registration

class LoginActivity : AppCompatActivity(), View.OnClickListener {


    var toolbar:Toolbar?=null;
    var email: AppCompatEditText?=null;
    var password:AppCompatEditText?=null;
    var checkbox:CheckBox?=null;
    var signin:ImageButton?=null;
    var signup:Button?=null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initUI()
    }

   fun initUI()
    {
        toolbar=findViewById(R.id.toolbar);
        email=findViewById(R.id.email);
        password=findViewById(R.id.password);
        checkbox=findViewById(R.id.checkbox);
        signin=findViewById(R.id.signin);
        signup=findViewById(R.id.signup);
        signin?.setOnClickListener(this);
        signup?.setOnClickListener(this);
    }

    override fun onClick(v: View?) {
       when (v?.id)
       {
           R.id.signup ->{
              var intent=Intent(applicationContext,SignupActivity::class.java)
               startActivity(intent)
               finish()
           }
           R.id.signin ->{
               var emailStr=email?.text.toString().trim();
               var passStr=password?.text.toString().trim();
              var list= MyDatabase.getInstance(applicationContext).registrationDAO().checkLogin(emailStr,passStr) as List;
               if(list.size<=0)
               {

                   Toast.makeText(applicationContext,"Invalid Credentials",Toast.LENGTH_LONG).show()
                   return;
               }

               AppPref.setSession(applicationContext,list.get(0).id)
               var intent= Intent(this,HomeActivity::class.java)
               startActivity(intent)
               finish()
               Log.v("Length ","Length" +list.size)
           }
       }
    }
}


SignupActivity.kt

package com.rrtutors.roomwithkotlin.ui

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Patterns
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.widget.AppCompatEditText
import com.rrtutors.roomwithkotlin.R
import com.rrtutors.roomwithkotlin.database.MyDatabase
import com.rrtutors.roomwithkotlin.entities.Registration
import kotlinx.android.synthetic.main.activity_signup.*
import java.util.regex.Pattern

class SignupActivity : AppCompatActivity(),View.OnClickListener {


    var et_name: AppCompatEditText?=null;
    var et_email: AppCompatEditText?=null;
    var et_mobile: AppCompatEditText?=null;
    var et_password: AppCompatEditText?=null;
    var checkbox: CheckBox?=null;
    var signup:ImageButton?=null;
    var signin: Button?=null;
    var emailPatter:Pattern?=null;
    var mobilePatter:Pattern?=null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_signup)
        initUI()
    }
    fun initUI()
    {
        et_name=findViewById(R.id.et_name)
        et_email=findViewById(R.id.et_email)
        et_mobile=findViewById(R.id.et_mobile)
        et_password=findViewById(R.id.et_password)
        checkbox=findViewById(R.id.checkbox)
        signup=findViewById(R.id.signup)
        signin=findViewById(R.id.signin)
        signup?.setOnClickListener(this)
        signin?.setOnClickListener(this)

        emailPatter= Patterns.EMAIL_ADDRESS;
        mobilePatter= Patterns.PHONE;
    }

    override fun onClick(v: View?) {

        when(v?.id)
        {
            R.id.signup->{

                var name=et_name?.text.toString().trim()
                var email=et_email?.text.toString().trim()
                var mobile=et_mobile?.text.toString().trim()
                var pass=et_password?.text.toString().trim()
                var registration:Registration= Registration(name,email,pass,mobile)
                if(name.length<=0)
                {
                    Toast.makeText(applicationContext,"Please Enter Name",Toast.LENGTH_SHORT).show()
                    return;
                }
                if(email.length<=0)
                {
                    Toast.makeText(applicationContext,"Please Enter Email",Toast.LENGTH_SHORT).show()
                    return;
                }
                if(mobile.length<=0)
                {
                    Toast.makeText(applicationContext,"Please Enter Mobile",Toast.LENGTH_SHORT).show()
                    return;
                }
                if(pass.length<=0)
                {
                    Toast.makeText(applicationContext,"Please Enter Password",Toast.LENGTH_SHORT).show()
                    return;
                }
                if(!(emailPatter?.matcher(email)?.find())!!)
                {
                    Toast.makeText(applicationContext,"Please Enter valid email",Toast.LENGTH_SHORT).show()
                    return;
                }
                if(!(mobilePatter?.matcher(mobile)?.find())!!)
                {
                    Toast.makeText(applicationContext,"Please Enter valid mobile number",Toast.LENGTH_SHORT).show()
                    return;
                }
                var list= MyDatabase.getInstance(applicationContext).registrationDAO().checkLogin(email,pass) as List;
                if(list.size<=0)
                {
                    MyDatabase.getInstance(applicationContext).registrationDAO().insert(registration);

                    callSignIn()
                    Toast.makeText(applicationContext,"user registered successfuly",Toast.LENGTH_SHORT).show()
                }else
                {
                    Toast.makeText(applicationContext,"user already exist with this email Id",Toast.LENGTH_SHORT).show()
                }


            }
            R.id.signin->{

                callSignIn()
            }
        }
    }

    override fun onBackPressed() {
        callSignIn()
    }

    private fun callSignIn()
    {

        var intent= Intent(this,LoginActivity::class.java)
        startActivity(intent)
        finish()
    }
}


HomeActivity.kt

package com.rrtutors.roomwithkotlin.ui

import android.content.Intent
import android.os.Bundle
import android.util.Log
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.navigation.NavigationView
import androidx.core.view.GravityCompat
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.TextView
import androidx.core.view.get
import com.rrtutors.roomwithkotlin.AppPref
import com.rrtutors.roomwithkotlin.R
import com.rrtutors.roomwithkotlin.database.MyDatabase
import com.rrtutors.roomwithkotlin.entities.Registration
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.android.synthetic.main.app_bar_home.*

class HomeActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    var registration: Registration?=null;
    var txt_user_details:TextView?=null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        setSupportActionBar(toolbar)

        registration=MyDatabase.getInstance(applicationContext).registrationDAO().fetchUser(AppPref.getSessionId(applicationContext))
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }

        val toggle = ActionBarDrawerToggle(
            this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close
        )
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        nav_view.setNavigationItemSelectedListener(this)
        txt_user_details=findViewById(R.id.txt_user_details);
        var txt_name=nav_view.getHeaderView(0).findViewById(R.id.txt_name)
        var txt_email=nav_view.getHeaderView(0).findViewById(R.id.txt_email)
        registration.let {
            txt_name.setText(registration?.name)
            txt_user_details?.setText(registration?.name+"\n"+registration?.email+"\n"+registration?.mobile)
            txt_email.setText(registration?.email)
        }
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            super.onBackPressed()
        }
    }



    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        // Handle navigation view item clicks here.
        when (item.itemId) {
            R.id.nav_logout -> {
                AppPref.clearSeesion(applicationContext)
                var intent= Intent(this,LoginActivity::class.java)
                startActivity(intent)
                finish()
            }
            R.id.nav_delete -> {

                var delete=registration?.let { MyDatabase.getInstance(applicationContext).registrationDAO().deleteUser(it) }
                Log.v("delete","delete "+delete)
                AppPref.clearSeesion(applicationContext)
                var intent= Intent(this,LoginActivity::class.java)
                startActivity(intent)
                finish()
            }


        }

        drawer_layout.closeDrawer(GravityCompat.START)
        return true
    }
}