Kotlin Android Sqlite Example Application
Kotlin Android Sqlite Example Application
We shall look into typical classes that we use for using SQLite database.
DB Contract Contains schema (table name and column names) for program
Class understandability.
DB Helper This class contains methods that do database operations like insert,
Class select, update, delete, etc.
Model Data
Class Used to carry objects (rows of DB table)
This is class file of your Activity from which you call DB Helper’s
Activity Class methods for database activities
Following are the details of the Android Application we created for this
example.
You may keep rest of the values as default and create Android Application with
Kotlin Support.
activity_main.xml
1 package com.tutorialkart.sqlitetutorial
2
3 class UserModel(val userid: String, val name: String, val age: String)
DBContract.kt
1 package com.tutorialkart.sqlitetutorial
2
3 import android.provider.BaseColumns
4
5 object DBContract {
6
7 /* Inner class that defines the table contents */
8 class UserEntry : BaseColumns {
9 companion object {
10 val TABLE_NAME = "users"
11 val COLUMN_USER_ID = "userid"
12 val COLUMN_NAME = "name"
13 val COLUMN_AGE = "age"
14 }
15 }
16 }
UsersDBHelper.kt
1 package com.tutorialkart.sqlitetutorial
2
3 import android.content.ContentValues
4 import android.content.Context
5 import android.database.Cursor
6 import android.database.sqlite.SQLiteConstraintException
7 import android.database.sqlite.SQLiteDatabase
8 import android.database.sqlite.SQLiteException
9 import android.database.sqlite.SQLiteOpenHelper
10
11 import java.util.ArrayList
12
13 class UsersDBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null,
14 DATABASE_VERSION) {
15 override fun onCreate(db: SQLiteDatabase) {
16 db.execSQL(SQL_CREATE_ENTRIES)
17 }
18
19 override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
20 // This database is only a cache for online data, so its upgrade policy is
21 // to simply to discard the data and start over
22 db.execSQL(SQL_DELETE_ENTRIES)
23 onCreate(db)
24 }
25
26 override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
27 onUpgrade(db, oldVersion, newVersion)
28 }
29
30 @Throws(SQLiteConstraintException::class)
31 fun insertUser(user: UserModel): Boolean {
32 // Gets the data repository in write mode
33 val db = writableDatabase
34
35 // Create a new map of values, where column names are the keys
36 val values = ContentValues()
37 values.put(DBContract.UserEntry.COLUMN_USER_ID, user.userid)
38 values.put(DBContract.UserEntry.COLUMN_NAME, user.name)
39 values.put(DBContract.UserEntry.COLUMN_AGE, user.age)
40
41 // Insert the new row, returning the primary key value of the new row
42 val newRowId = db.insert(DBContract.UserEntry.TABLE_NAME, null, values)
43
44 return true
45 }
46
47 @Throws(SQLiteConstraintException::class)
48 fun deleteUser(userid: String): Boolean {
49 // Gets the data repository in write mode
50 val db = writableDatabase
51 // Define 'where' part of query.
52 val selection = DBContract.UserEntry.COLUMN_USER_ID + " LIKE ?"
53 // Specify arguments in placeholder order.
54 val selectionArgs = arrayOf(userid)
55 // Issue SQL statement.
56 db.delete(DBContract.UserEntry.TABLE_NAME, selection, selectionArgs)
57
58 return true
59 }
60
61 fun readUser(userid: String): ArrayList<UserModel> {
62 val users = ArrayList<UserModel>()
63 val db = writableDatabase
64 var cursor: Cursor? = null
65 try {
66 cursor = db.rawQuery("select * from " + DBContract.UserEntry.TABLE_NAME + " WHERE " +
67 DBContract.UserEntry.COLUMN_USER_ID + "='" + userid + "'", null)
68 } catch (e: SQLiteException) {
69 // if table not yet present, create it
70 db.execSQL(SQL_CREATE_ENTRIES)
71 return ArrayList()
72 }
73
74 var name: String
75 var age: String
76 if (cursor!!.moveToFirst()) {
77 while (cursor.isAfterLast == false) {
78 name = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_NAME))
79 age = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_AGE))
80
81 users.add(UserModel(userid, name, age))
82 cursor.moveToNext()
83 }
84 }
85 return users
86 }
87
88 fun readAllUsers(): ArrayList<UserModel> {
89 val users = ArrayList<UserModel>()
90 val db = writableDatabase
91 var cursor: Cursor? = null
92 try {
93 cursor = db.rawQuery("select * from " + DBContract.UserEntry.TABLE_NAME, null)
94 } catch (e: SQLiteException) {
95 db.execSQL(SQL_CREATE_ENTRIES)
96 return ArrayList()
97 }
98
99 var userid: String
100 var name: String
101 var age: String
102 if (cursor!!.moveToFirst()) {
103 while (cursor.isAfterLast == false) {
104 userid = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_USER_ID))
105 name = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_NAME))
106 age = cursor.getString(cursor.getColumnIndex(DBContract.UserEntry.COLUMN_AGE))
107
users.add(UserModel(userid, name, age))
108 cursor.moveToNext()
109 }
110 }
111 return users
112 }
113
114 companion object {
115 // If you change the database schema, you must increment the database version.
116 val DATABASE_VERSION = 1
117 val DATABASE_NAME = "FeedReader.db"
118
119 private val SQL_CREATE_ENTRIES =
120 "CREATE TABLE " + DBContract.UserEntry.TABLE_NAME + " (" +
121 DBContract.UserEntry.COLUMN_USER_ID + " TEXT PRIMARY KEY," +
122 DBContract.UserEntry.COLUMN_NAME + " TEXT," +
123 DBContract.UserEntry.COLUMN_AGE + " TEXT)"
124
125 private val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + DBContract.UserEntry.TABLE_NAME
126 }
127
}
MainAcitivity.kt
1 package com.tutorialkart.sqlitetutorial
2
3 import android.support.v7.app.AppCompatActivity
4 import android.os.Bundle
5 import android.view.View
6 import android.widget.TextView
7 import kotlinx.android.synthetic.main.activity_main.*
8
9 class MainActivity : AppCompatActivity() {
10
11 lateinit var usersDBHelper : UsersDBHelper
12
13 override fun onCreate(savedInstanceState: Bundle?) {
14 super.onCreate(savedInstanceState)
15 setContentView(R.layout.activity_main)
16
17 usersDBHelper = UsersDBHelper(this)
18 }
19
20 fun addUser(v:View){
21 var userid = this.edittext_userid.text.toString()
22 var name = this.edittext_name.text.toString()
23 var age = this.edittext_age.text.toString()
24 var result = usersDBHelper.insertUser(UserModel(userid = userid,name = name,age = age))
25 //clear all edittext s
26 this.edittext_age.setText("")
27 this.edittext_name.setText("")
28 this.edittext_userid.setText("")
29 this.textview_result.text = "Added user : "+result
30 this.ll_entries.removeAllViews()
31 }
32
33 fun deleteUser(v:View){
34 var userid = this.edittext_userid.text.toString()
35 val result = usersDBHelper.deleteUser(userid)
36 this.textview_result.text = "Deleted user : "+result
37 this.ll_entries.removeAllViews()
38 }
39
40 fun showAllUsers(v:View){
41 var users = usersDBHelper.readAllUsers()
42 this.ll_entries.removeAllViews()
43 users.forEach {
44 var tv_user = TextView(this)
45 tv_user.textSize = 30F
46 tv_user.text = it.name.toString() + " - " + it.age.toString()
47 this.ll_entries.addView(tv_user)
48 }
49 this.textview_result.text = "Fetched " + users.size + " users"
50 }
51 }
Conclusion :
In this tutorial – Kotlin Android SQLite, we have learnt how to use SQLite
database (CRUD Operations) in Android Application, and necessary classes
for maintenance, with an Example Android Application