Kotlin Android SQLite Tutorial
In this Article Today learn Kotlin Android SQLite Tutorial in Android Studio. kotlin langauge provide a Insert data Sqlite. follow the full Source code Kotlin Android SQLite Tutorial. follow the link kotlin tutorial :https://developer.android.com/training/data-storage/room.
Previous tutorial kotlin login page follow the link : https://techicaltutorial.blogspot.com/2021/02/kotlin-login-page-example-in-android.html
1.MainActivity.kt:
package com.akash.kotlinsqlite
import android.app.Activity
import android.app.AlertDialog
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import android.content.DialogInterface
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
//method for saving records in database
fun saveRecord(view: View){
val id = u_id.text.toString()
val name = u_name.text.toString()
val email = u_email.text.toString()
val databaseHandler: DatabaseHandler= DatabaseHandler(this)
if(id.trim()!="" && name.trim()!="" && email.trim()!=""){
val status = databaseHandler.addEmployee(EmpModelClass(Integer.parseInt(id),name, email))
if(status > -1){
Toast.makeText(applicationContext,"Record Saved SucessFully",Toast.LENGTH_LONG).show()
u_id.text.clear()
u_name.text.clear()
u_email.text.clear()
}
}else{
Toast.makeText(applicationContext,"id or name or email cannot be blank",Toast.LENGTH_LONG).show()
}
}
}
2.EmpModelClass.kt:
package com.akash.kotlinsqlite
class EmpModelClass (var userId: Int, val userName:String , val userEmail: String)
3.DatabaseHandler.kt:
package com.akash.kotlinsqlite
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteException
//creating the database logic, extending the SQLiteOpenHelper base class
class DatabaseHandler(context: Context): SQLiteOpenHelper(context,DATABASE_NAME,null,DATABASE_VERSION) {
companion object {
private val DATABASE_VERSION = 1
private val DATABASE_NAME = "EmployeeDatabase"
private val TABLE_CONTACTS = "EmployeeTable"
private val KEY_ID = "id"
private val KEY_NAME = "name"
private val KEY_EMAIL = "email"
}
override fun onCreate(db: SQLiteDatabase?) {
// TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
//creating table with fields
val CREATE_CONTACTS_TABLE = ("CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT" + ")")
db?.execSQL(CREATE_CONTACTS_TABLE)
}
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("DROP TABLE IF EXISTS " + TABLE_CONTACTS)
onCreate(db)
}
//method to insert data
fun addEmployee(emp: EmpModelClass):Long{
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(KEY_ID, emp.userId)
contentValues.put(KEY_NAME, emp.userName) // EmpModelClass Name
contentValues.put(KEY_EMAIL,emp.userEmail ) // EmpModelClass Phone
// Inserting Row
val success = db.insert(TABLE_CONTACTS, null, contentValues)
//2nd argument is String containing nullColumnHack
db.close() // Closing database connection
return success
}
//method to read data
//method to update data
}
4.activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="Employee Record "
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textSize="20dp"
android:layout_column="1" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="User Id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:id="@+id/u_id"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:layout_marginStart="20sp"
android:width="150px" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="User Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:id="@+id/u_name"
android:width="200dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="User Email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1" />
<EditText
android:id="@+id/u_email"
android:width="200dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_marginStart="20sp"
android:layout_marginLeft="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="saveRecord"/>
</LinearLayout>
</LinearLayout>
5.AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.akash.kotlinsqlite">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
6.strings.xml:
<resources>
<string name="app_name">kotlin sqlite</string>
</resources>
7.styles.xml:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>
8.colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#6200EE</color>
<color name="colorPrimaryDark">#3700B3</color>
<color name="colorAccent">#03DAC5</color>
</resources>
9.Output:
No comments:
Post a Comment