Android SQLite Example Application Using Kotlin


Kotlin Android SQLite – SQLite is an open source database based on SQL language. Android has SQLite database implementation by default.


Android SQLite Example Application Using Kotlin

Koltin Android SQLite Example Application : In this Android Tutorial, we shall learn how to use SQLite database in your Android Application with an example using Kotlin Programming language.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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="net.dvinfosys.sqlitedemo.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.dvinfosys.sqlitedemo">
<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"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<?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:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="net.dvinfosys.sqlitedemo.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="SQLite Tutorial - Person Management"
android:textSize="20dp"
android:gravity="center"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical">
<EditText
android:id="@+id/edittext_userid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Person ID" />
<EditText
android:id="@+id/edittext_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Person Name" />
<EditText
android:id="@+id/edittext_surname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Person SurName" />
<EditText
android:id="@+id/edittext_age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Person Age" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
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="addPerson"
android:text="Add"
tools:ignore="OnClick" />
<!--<Button
android:id="@+id/button_update_person"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Update"
android:onClick="updatePerson"
tools:ignore="OnClick" />-->
<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"
tools:ignore="OnClick" />
<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"
tools:ignore="OnClick" />
</LinearLayout>
<TextView
android:id="@+id/textview_result"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/ll_entries"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="15dp"></LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginBottom="10dp"
android:background="@color/colorPrimary">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center"
android:text="Delete Person "
android:textColor="#fff"
android:textSize="15sp"
android:textStyle="bold" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="@color/colorPrimaryDark" />
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Person Name : "
android:textColor="@color/colorPrimary"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Person Name"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Person Surname : "
android:gravity="center"
android:textColor="@color/colorPrimary"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_person_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Person Surname"
android:textSize="15sp" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Person Age : "
android:textColor="@color/colorPrimary"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_person_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="Person Age"
android:textSize="15sp" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginTop="10dp"
android:background="@color/colorPrimaryDark" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/no_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="@color/colorPrimary"
android:text="No"
android:textColor="#fff"
android:textSize="13sp" />
<Button
android:id="@+id/yes_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:layout_weight="1"
android:background="@color/colorPrimary"
android:text="Yes"
android:textColor="#fff"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
view raw deletedilog.xml hosted with ❤ by GitHub
package net.dvinfosys.sqlitedemo
import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.deletedilog.*
class MainActivity : AppCompatActivity() {
lateinit var mySqlHalper:MySqlHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
MySqlHelper.getInstance(this)
mySqlHalper= MySqlHelper(this)
fab.setOnClickListener {
val person = Person(100, "Dhaval", "Bhuva", 23)
mySqlHalper.insert(person)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
fun deleteUser(v:View)
{
val personId=this.edittext_userid.text.toString()
val dialogAlert=AlertDialog.Builder(this)
val inflater=this.layoutInflater
val dialogView=inflater.inflate(R.layout.deletedilog,null)
dialogAlert.setView(dialogView)
val cName=dialogView.findViewById<TextView>(R.id.tv_person_name)
val cSurname=dialogView.findViewById<TextView>(R.id.tv_person_surname)
val cAge=dialogView.findViewById<TextView>(R.id.tv_person_age)
val viewPerson=mySqlHalper.readPerson(personId)
viewPerson.forEach{
//deleteAlert.setMessage("Name : "+it.name.toString()+"\nSurname : "+it.surname.toString()+"\nAge : "+it.age.toString())
val personName=it.name.toString()
val personSurname=it.surname.toString()
val personAge=it.age.toString()
cName.setText(personName)
cSurname.setText(personSurname)
cAge.setText(personAge)
}
val buttonYes=dialogView.findViewById<Button>(R.id.yes_button)
buttonYes.setOnClickListener(){
val result=mySqlHalper.deletePerson(personId.toString())
if (result){
Toast.makeText(applicationContext,"Delete Person Successfully...",Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(applicationContext,"Person Not Found...",Toast.LENGTH_SHORT).show()
}
this.textview_result.text = "Deleted Person : "+result
}
val buttoNo=dialogView.findViewById<Button>(R.id.no_button)
buttoNo.setOnClickListener{
Toast.makeText(this,"Peson No Delete...",Toast.LENGTH_SHORT).show()
}
dialogAlert.show()
this.ll_entries.removeAllViews()
}
fun addPerson(v: View) {
val id = this.edittext_userid.text.toString()
val name = this.edittext_name.text.toString()
val surname = this.edittext_surname.text.toString()
val age = this.edittext_age.text.toString()
val mainid = id.toInt()
val mainage = age.toInt()
val person = Person(mainid, name, surname, mainage)
mySqlHalper.insert(person)
this.edittext_age.setText("")
this.edittext_name.setText("")
this.edittext_userid.setText("")
this.edittext_surname.setText("")
this.textview_result.text = "Added user : "+person
this.ll_entries.removeAllViews()
}
fun showAllUsers(v: View) {
val person=mySqlHalper.readAllPerson()
this.ll_entries.removeAllViews()
person.forEach{
val tvPerson=TextView(this)
tvPerson.textSize=30f
tvPerson.text=it.id.toString()+" - "+it.name.toString() +" "+ it.surname.toString() + " - " + it.age.toString()
this.ll_entries.addView(tvPerson)
}
this.textview_result.text = "Fetched " + person.size + " users"
}
}
view raw MainActivity.kt hosted with ❤ by GitHub
package net.dvinfosys.sqlitedemo
import android.content.ContentUris
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 org.jetbrains.anko.db.*
class MySqlHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "mydb") {
companion object {
private var instance: MySqlHelper? = null
val TableName = "Person"
val PersonId = "_id"
val PersonName = "name"
val PersonSurname = "surname"
val Personage = "age"
@Synchronized
fun getInstance(ctx: Context): MySqlHelper {
if (instance == null) {
instance = MySqlHelper(ctx.applicationContext)
}
return instance!!
}
}
//val db: SQLiteDatabase? =null
override fun onCreate(db: SQLiteDatabase?) {
db?.createTable("Person", true,
"_id" to INTEGER + PRIMARY_KEY + UNIQUE,
"name" to TEXT,
"surname" to TEXT,
"age" to INTEGER)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
db?.dropTable("Person", true)
onCreate(db)
}
override fun onDowngrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
onUpgrade(db, oldVersion, newVersion)
}
val Context.database: MySqlHelper get() = MySqlHelper.getInstance(applicationContext)
@Throws(SQLiteConstraintException::class)
fun insert(person: Person)
{
val db = this.writableDatabase
val values = ContentValues()
values.put("_id", person.id)
values.put("name", person.name)
values.put("surname", person.surname)
values.put("age", person.age)
db?.insert("Person", null, values)
db.close()
}
fun readAllPerson(): ArrayList<Person> {
val person = ArrayList<Person>()
val db = this.writableDatabase
var cursor: Cursor? = null
try {
cursor = db.rawQuery("select * from Person", null)
} catch (e: SQLiteException) {
onCreate(db)
return ArrayList()
}
var personId: Int
var name: String
var surname: String
var age: Int
if (cursor!!.moveToFirst()) {
while (cursor.isAfterLast == false) {
personId = cursor.getInt(cursor.getColumnIndex("_id"))
name = cursor.getString(cursor.getColumnIndex("name"))
surname = cursor.getString(cursor.getColumnIndex("surname"))
age = cursor.getInt(cursor.getColumnIndex("age"))
person.add(Person(personId, name, surname, age))
cursor.moveToNext()
}
}
return person
}
@Throws(SQLiteConstraintException::class)
fun readPerson(personId: String):ArrayList<Person>{
val person=ArrayList<Person>()
val db=writableDatabase
var cursor: Cursor? = null
try {
cursor = db.rawQuery("select * from " + TableName + " WHERE " + PersonId + "='" + personId + "'", null)
}catch (e: SQLiteException){
onCreate(db)
return ArrayList()
}
var id:Int
var name:String
var surname:String
var age:Int
if (cursor!!.moveToFirst()){
while (cursor.isAfterLast==false){
id=cursor.getInt(cursor.getColumnIndex(PersonId))
name=cursor.getString(cursor.getColumnIndex(PersonName))
surname=cursor.getString(cursor.getColumnIndex(PersonSurname))
age=cursor.getInt(cursor.getColumnIndex(Personage))
person.add(Person(id,name,surname,age))
cursor.moveToNext()
}
}
return person
}
@Throws(SQLiteConstraintException::class)
fun deletePerson(personId: String): Boolean {
val db = writableDatabase
val selection = PersonId + " LIKE ?"
val selectionArgs = arrayOf(personId)
db.delete(TableName, selection, selectionArgs)
return true
}
}
view raw MySqlHelper.kt hosted with ❤ by GitHub
package net.dvinfosys.sqlitedemo
data class Person (val id:Int,val name:String,val surname:String,val age:Int)
view raw Person.kt hosted with ❤ by GitHub

Comments

All Post

MINI MILITIA RANK HACK APK FOR ANDROID ROOT & CYDIA iOS

Shortcut Virus?

Android Studio Plugin Development

DV Infosys

Paying with Your Face

Microsoft’s giving you just 10 days now, not 31, to change your mind about Windows 10

Does your iPhone suffer from 'Touch Disease'?

Google’s Quantum Dream May Be Just Around the Corner