Read on Kotlin SQLite Multiple Tables Android Tutorial with example.
In this tutorial, you will learn how to manage SQLite database with two or more multiple tables in one single database.
We will learn how to insert and get data from multiple tables in SQLite database in android using kotlin.
First of all, see the following video for final outcome.
See the below image which shows the tables of the SQLite Database.
In total, there are three tables : users, users_city, users_hobby
We connect all these three tables with each other using the column “id”
For example, in the users table, we have two columns : id and name . You can see that for id 1, name is the peter.
Now see the users_hobby table, there are also two columns here : id and hobby. For id 1, hobby is spider man so that we can say that peter’s hobby is spider man.
Now go to users_city table, it has two columns : id and city. For id 1, city is new york so that we can conclude that peter’s city is new york.
Step 1. Fresh Kotlin Project
Make brand new project in the android studio. Here, be sure to select empty activity as the default activity.
Also, you should set the primary source language as the Kotlin.
Step 2. Database Helper Class
First of all, create a new kotlin class and give it a name like DatabaseHelper.kt
You should add the below coding lines in DatabaseHelper.kt
import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.util.Log import java.util.ArrayList class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { val allUsers: ArrayList<UserModel> get() { val userModelArrayList = ArrayList<UserModel>() val selectQuery = "SELECT * FROM $TABLE_USER" val db = this.readableDatabase val c = db.rawQuery(selectQuery, null) if (c.moveToFirst()) { do { val userModel = UserModel() userModel.setIds(c.getInt(c.getColumnIndex(KEY_ID))) userModel.setNames(c.getString(c.getColumnIndex(KEY_FIRSTNAME))) val selectHobbyQuery = "SELECT * FROM " + TABLE_USER_HOBBY + " WHERE " + KEY_ID + " = " + userModel.getIds() Log.d("oppp", selectHobbyQuery) val cHobby = db.rawQuery(selectHobbyQuery, null) if (cHobby.moveToFirst()) { do { userModel.setHobbys(cHobby.getString(cHobby.getColumnIndex(KEY_HOBBY))) } while (cHobby.moveToNext()) } val selectCityQuery = "SELECT * FROM " + TABLE_USER_CITY + " WHERE " + KEY_ID + " = " + userModel.getIds() val cCity = db.rawQuery(selectCityQuery, null) if (cCity.moveToFirst()) { do { userModel.setCitys(cCity.getString(cCity.getColumnIndex(KEY_CITY))) } while (cCity.moveToNext()) } userModelArrayList.add(userModel) } while (c.moveToNext()) } return userModelArrayList } init { Log.d("table", CREATE_TABLE_STUDENTS) } override fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_TABLE_STUDENTS) db.execSQL(CREATE_TABLE_USER_HOBBY) db.execSQL(CREATE_TABLE_USER_CITY) } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("DROP TABLE IF EXISTS '$TABLE_USER'") db.execSQL("DROP TABLE IF EXISTS '$TABLE_USER_HOBBY'") db.execSQL("DROP TABLE IF EXISTS '$TABLE_USER_CITY'") onCreate(db) } fun addUser(name: String, hobby: String, city: String) { val db = this.writableDatabase //adding user name in users table val values = ContentValues() values.put(KEY_FIRSTNAME, name) // db.insert(TABLE_USER, null, values); val id = db.insertWithOnConflict(TABLE_USER, null, values, SQLiteDatabase.CONFLICT_IGNORE) //adding user hobby in users_hobby table val valuesHobby = ContentValues() valuesHobby.put(KEY_ID, id) valuesHobby.put(KEY_HOBBY, hobby) db.insert(TABLE_USER_HOBBY, null, valuesHobby) //adding user city in users_city table val valuesCity = ContentValues() valuesCity.put(KEY_ID, id) valuesCity.put(KEY_CITY, city) db.insert(TABLE_USER_CITY, null, valuesCity) } fun updateUser(id: Int, name: String, hobby: String, city: String) { val db = this.writableDatabase // updating name in users table val values = ContentValues() values.put(KEY_FIRSTNAME, name) db.update(TABLE_USER, values, "$KEY_ID = ?", arrayOf(id.toString())) // updating hobby in users_hobby table val valuesHobby = ContentValues() valuesHobby.put(KEY_HOBBY, hobby) db.update(TABLE_USER_HOBBY, valuesHobby, "$KEY_ID = ?", arrayOf(id.toString())) // updating city in users_city table val valuesCity = ContentValues() valuesCity.put(KEY_CITY, city) db.update(TABLE_USER_CITY, valuesCity, "$KEY_ID = ?", arrayOf(id.toString())) } fun deleteUSer(id: Int) { // delete row in students table based on id val db = this.writableDatabase //deleting from users table db.delete(TABLE_USER, "$KEY_ID = ?", arrayOf(id.toString())) //deleting from users_hobby table db.delete(TABLE_USER_HOBBY, "$KEY_ID = ?", arrayOf(id.toString())) //deleting from users_city table db.delete(TABLE_USER_CITY, "$KEY_ID = ?", arrayOf(id.toString())) } companion object { var DATABASE_NAME = "user_database" private val DATABASE_VERSION = 1 private val TABLE_USER = "users" private val TABLE_USER_HOBBY = "users_hobby" private val TABLE_USER_CITY = "users_city" private val KEY_ID = "id" private val KEY_FIRSTNAME = "name" private val KEY_HOBBY = "hobby" private val KEY_CITY = "city" /*CREATE TABLE students ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phone_number TEXT......);*/ private val CREATE_TABLE_STUDENTS = ("CREATE TABLE " + TABLE_USER + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_FIRSTNAME + " TEXT );") private val CREATE_TABLE_USER_HOBBY = ("CREATE TABLE " + TABLE_USER_HOBBY + "(" + KEY_ID + " INTEGER," + KEY_HOBBY + " TEXT );") private val CREATE_TABLE_USER_CITY = ("CREATE TABLE " + TABLE_USER_CITY + "(" + KEY_ID + " INTEGER," + KEY_CITY + " TEXT );") } }
Diving In Above
See the last part in above code which is the object { … }
Here, I have declared many variables like DATABASE_NAME, TABLE_USER, KEY_HOBBY etc. which are giving the name to the various aspects like database, table name, table’s column name etc.
A variable CREATE_TABLE_STUDENTS is defining the SQL query to create a new table and the name of the table is users.
Similarly, CREATE_TABLE_USER_HOBBY and CREATE_TABLE_USER_CITY will have the SQL statements which will create the tables users_hobby and users_city respectively.
Now see the following code
val allUsers: ArrayList<UserModel> get() { val userModelArrayList = ArrayList<UserModel>() val selectQuery = "SELECT * FROM $TABLE_USER" val db = this.readableDatabase val c = db.rawQuery(selectQuery, null) if (c.moveToFirst()) { do { val userModel = UserModel() userModel.setIds(c.getInt(c.getColumnIndex(KEY_ID))) userModel.setNames(c.getString(c.getColumnIndex(KEY_FIRSTNAME))) val selectHobbyQuery = "SELECT * FROM " + TABLE_USER_HOBBY + " WHERE " + KEY_ID + " = " + userModel.getIds() Log.d("oppp", selectHobbyQuery) val cHobby = db.rawQuery(selectHobbyQuery, null) if (cHobby.moveToFirst()) { do { userModel.setHobbys(cHobby.getString(cHobby.getColumnIndex(KEY_HOBBY))) } while (cHobby.moveToNext()) } val selectCityQuery = "SELECT * FROM " + TABLE_USER_CITY + " WHERE " + KEY_ID + " = " + userModel.getIds() val cCity = db.rawQuery(selectCityQuery, null) if (cCity.moveToFirst()) { do { userModel.setCitys(cCity.getString(cCity.getColumnIndex(KEY_CITY))) } while (cCity.moveToNext()) } userModelArrayList.add(userModel) } while (c.moveToNext()) } return userModelArrayList }
Above function will fetch all the records from all three tables. This method will fire three queries to get the rows from all three tables.
After getting the results it will store them into one arraylist which is made with objects of the UserModel class. We will create UserModel class later.
Now focus on the below structure
fun addUser(name: String, hobby: String, city: String) { val db = this.writableDatabase //adding user name in users table val values = ContentValues() values.put(KEY_FIRSTNAME, name) // db.insert(TABLE_USER, null, values); val id = db.insertWithOnConflict(TABLE_USER, null, values, SQLiteDatabase.CONFLICT_IGNORE) //adding user hobby in users_hobby table val valuesHobby = ContentValues() valuesHobby.put(KEY_ID, id) valuesHobby.put(KEY_HOBBY, hobby) db.insert(TABLE_USER_HOBBY, null, valuesHobby) //adding user city in users_city table val valuesCity = ContentValues() valuesCity.put(KEY_ID, id) valuesCity.put(KEY_CITY, city) db.insert(TABLE_USER_CITY, null, valuesCity) }
A method addUser() will insert the record into the database. This method has three parameters : name, hobby and city.
It will use these parameters to a record in the database. Compiler will use db.insert() statements three times to add records in three tables.
Now read the below source lines
fun updateUser(id: Int, name: String, hobby: String, city: String) { val db = this.writableDatabase // updating name in users table val values = ContentValues() values.put(KEY_FIRSTNAME, name) db.update(TABLE_USER, values, "$KEY_ID = ?", arrayOf(id.toString())) // updating hobby in users_hobby table val valuesHobby = ContentValues() valuesHobby.put(KEY_HOBBY, hobby) db.update(TABLE_USER_HOBBY, valuesHobby, "$KEY_ID = ?", arrayOf(id.toString())) // updating city in users_city table val valuesCity = ContentValues() valuesCity.put(KEY_CITY, city) db.update(TABLE_USER_CITY, valuesCity, "$KEY_ID = ?", arrayOf(id.toString())) }
This code is for updateUser() method. It also has four parameters: id, name, hobby and city.
Compiler will use id to find which row it need to update. id is present in all three tables. So, logic for updation is same for all three tables.
To update name, compiler will use id to find the row in users table. Similarly, it will use id to update hobby and city in users_hobby and users_city tables respectively.
Now following is the code for deleteUser() method.
fun deleteUSer(id: Int) { // delete row in students table based on id val db = this.writableDatabase //deleting from users table db.delete(TABLE_USER, "$KEY_ID = ?", arrayOf(id.toString())) //deleting from users_hobby table db.delete(TABLE_USER_HOBBY, "$KEY_ID = ?", arrayOf(id.toString())) //deleting from users_city table db.delete(TABLE_USER_CITY, "$KEY_ID = ?", arrayOf(id.toString())) }
This method is getting only one variable in the parameter : id.
Compiler will find the row in all three tables which has the equal id value as of the parameter id value.
Then it will simply delete those rows and that is all to delete records from the SQLite database.
Now look at the onCreate() and onUpgrade() methods. I have given detailed information here in this tutorial on these methods : Kotlin SQLite Database android example
Step 3. Separate XML file And Model
We will have one list view in this example. For this we need one separate xml file and also a model class.
So let us, create them. Go to app->res->layout directory and make a new file called lv_item.xml
You should add the following lines in lv_item.xml
<?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:padding="10dp" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#000" android:orientation="vertical"> <TextView android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:layout_marginTop="10dp" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceMedium" android:paddingLeft="10dp" android:text="Name" /> <TextView android:id="@+id/hobby" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceMedium" android:paddingLeft="10dp" android:text="Hobby" /> <TextView android:id="@+id/city" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:gravity="center_vertical" android:textAppearance="?android:attr/textAppearanceMedium" android:paddingLeft="10dp" android:text="City" /> </LinearLayout> <View android:layout_width="match_parent" android:layout_height="1dp" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:background="@color/colorAccent"/> </LinearLayout>
This layout file will help us to create the view of the every single row of the listview.
Now make a new Kotlin file named “UserModel.kt” and write down the below code in it
import java.io.Serializable /** * Created by Parsania Hardik on 26-Apr-17. */ class UserModel : Serializable { var name: String? = null var hobby: String? = null var city: String? = null var id: Int = 0 fun getCitys(): String { return city.toString() } fun setCitys(city: String) { this.city = city } fun getIds(): Int { return id } fun setIds(id: Int) { this.id = id } fun getNames(): String { return name.toString() } fun setNames(name: String) { this.name = name } fun getHobbys(): String { return hobby.toString() } fun setHobbys(hobby: String) { this.hobby = hobby } }
This file has four variables : id, name, hobby, city.
It also has getter and setter methods for all these four variables. These methods will help for the data maintenance during the initialization of the list view.
Step 4. Adapter for List view
Create a new Kotlin class. Set it’s name as CustomAdapter.kt
You need to add the following source lines in CustomAdapter.kt
import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import java.util.ArrayList /** * Created by Parsania Hardik on 26-Apr-17. */ class CustomAdapter(private val context: Context, private val userModelArrayList: ArrayList<UserModel>) : BaseAdapter() { override fun getCount(): Int { return userModelArrayList.size } override fun getItem(position: Int): Any { return userModelArrayList[position] } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { var convertView = convertView val holder: ViewHolder if (convertView == null) { holder = ViewHolder() val inflater = context .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater convertView = inflater.inflate(R.layout.lv_item, null, true) holder.tvname = convertView!!.findViewById(R.id.name) as TextView holder.tvhobby = convertView.findViewById(R.id.hobby) as TextView holder.tvcity = convertView.findViewById(R.id.city) as TextView convertView.tag = holder } else { // the getTag returns the viewHolder object set as a tag to the view holder = convertView.tag as ViewHolder } holder.tvname!!.text = "Name: " + userModelArrayList[position].getNames() holder.tvhobby!!.text = "Hobby: " + userModelArrayList[position].getHobbys() holder.tvcity!!.text = "City: " + userModelArrayList[position].getCitys() return convertView } private inner class ViewHolder { var tvname: TextView? = null var tvhobby: TextView? = null var tvcity: TextView? = null } }
Adapter will provide the data to the list view.
Look at the getView() method in above code. Compiler will inflate the lv_item.xml file so that every row of list view look like this XML file.
It will also find the three text views from this XML file and will set the text in these text views.
Step 5. Getting All Records
Now we will get all the records from SQLite database using Kotlin.
For this, make a new activity and it should have the name like GetAllUsersActivity
In your activity_get_all_users.xml file, add the below lines
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:layout_marginTop="10dp" android:textSize="20sp" android:textColor="#000" android:text="Data from SQLite"/> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/lv"> </ListView> </LinearLayout>
This XML file have one text view and list view.
Now your GetAllUsersActivity.kt file should have the following coding lines
import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ListView import java.util.ArrayList class GetAllUsersActivity : AppCompatActivity() { private var listView: ListView? = null private var userModelArrayList: ArrayList<UserModel>? = null private var customAdapter: CustomAdapter? = null private var databaseHelper: DatabaseHelper? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_get_all_users) listView = findViewById(R.id.lv) as ListView databaseHelper = DatabaseHelper(this) userModelArrayList = databaseHelper!!.allUsers customAdapter = CustomAdapter(this, userModelArrayList!!) listView!!.adapter = customAdapter listView!!.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val intent = Intent(this@GetAllUsersActivity, UpdateDeleteActivity::class.java) intent.putExtra("user", userModelArrayList!![position]) startActivity(intent) } } }
First of all, compiler will create some objects of various classes like list view, custom adapter, database helper and userModelArraylist (This arraylist contains the objects of the UserModel class)
Then it will execute the allUsers function to get all the records from the SQLite database.
After this, it will initialize the custom adapter object and will bind it to the list view.
When the user clicks on the listview, compiler will open the UpdateDeleteActivity. So let us create this activity.
Step 6. Delete and Update SQLite Database
Make a new activity and set the name as UpdateDeleteActivity.
In your activity_update_delete.xml file, you should write the following
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/colorAccent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Name" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:textColor="#000" android:textSize="20sp"/> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/etname" android:background="#fff" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Name"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hobby" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:textColor="#000" android:textSize="20sp"/> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/ethobby" android:background="#fff" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter Hobby"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="City" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:textColor="#000" android:textSize="20sp"/> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/etcity" android:background="#fff" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:hint="Enter City"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:id="@+id/btnupdate" android:text="update"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:id="@+id/btndelete" android:text="delete"/> </LinearLayout>
Above file have three text views, three edit texts and two buttons.
Now below is the source lines for UpdateDeleteActivity.kt
import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.EditText import android.widget.Toast class UpdateDeleteActivity : AppCompatActivity() { private var userModel: UserModel? = null private var etname: EditText? = null private var ethobby: EditText? = null private var etcity: EditText? = null private var btnupdate: Button? = null private var btndelete: Button? = null private var databaseHelper: DatabaseHelper? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_update_delete) val intent = intent userModel = intent.getSerializableExtra("user") as UserModel databaseHelper = DatabaseHelper(this) etname = findViewById(R.id.etname) as EditText ethobby = findViewById(R.id.ethobby) as EditText etcity = findViewById(R.id.etcity) as EditText btndelete = findViewById(R.id.btndelete) as Button btnupdate = findViewById(R.id.btnupdate) as Button etname!!.setText(userModel!!.getNames()) ethobby!!.setText(userModel!!.getHobbys()) etcity!!.setText(userModel!!.getCitys()) btnupdate!!.setOnClickListener { databaseHelper!!.updateUser( userModel!!.getIds(), etname!!.text.toString(), ethobby!!.text.toString(), etcity!!.text.toString() ) Toast.makeText(this@UpdateDeleteActivity, "Updated Successfully!", Toast.LENGTH_SHORT).show() val intent = Intent(this@UpdateDeleteActivity, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } btndelete!!.setOnClickListener { databaseHelper!!.deleteUSer(userModel!!.getIds()) Toast.makeText(this@UpdateDeleteActivity, "Deleted Successfully!", Toast.LENGTH_SHORT).show() val intent = Intent(this@UpdateDeleteActivity, MainActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(intent) } } }
In this file, compiler will first set the values of name, hobby and city into the three edit texts.
Now if user wants o update any thing then he can change the value of the edit text.
After updating the values in the edit text, user needs to press Update button to update the records in the SQLite database.
For deleting the record, user simply have to click on the Delete button.
Step 7. Final Change in Main Activity
You have two files at the starting of the project : activity_main.xml and MainActivity.kt
Below are the lines of activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@color/colorAccent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textColor="#fff" android:textSize="20sp" android:layout_marginTop="10dp" android:text="Enter Name, Hobby,City to store in SQLite" /> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/etname" android:background="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:hint="Enter Name"/> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/ethobby" android:background="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:hint="Enter Hobby"/> <EditText android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/etcity" android:background="#fff" android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:hint="Enter City"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnstore" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:text="Store"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnget" android:layout_marginLeft="20dp" android:layout_marginTop="10dp" android:text="Get All Users from SQLite"/> </LinearLayout>
It has one text view, three edit texts and two buttons.
User can enter name, hobby and city in the edit texts.
Following is the lines for MainActivity.kt
import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast class MainActivity : AppCompatActivity() { private var btnStore: Button? = null private var btnGetall: Button? = null private var etname: EditText? = null private var ethobby: EditText? = null private var etcity: EditText? = null private var databaseHelper: DatabaseHelper? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) databaseHelper = DatabaseHelper(this) btnStore = findViewById(R.id.btnstore) as Button btnGetall = findViewById(R.id.btnget) as Button etname = findViewById(R.id.etname) as EditText ethobby = findViewById(R.id.ethobby) as EditText etcity = findViewById(R.id.etcity) as EditText btnStore!!.setOnClickListener { databaseHelper!!.addUser(etname!!.text.toString(), ethobby!!.text.toString(), etcity!!.text.toString()) etname!!.setText("") ethobby!!.setText("") etcity!!.setText("") Toast.makeText(this@MainActivity, "Stored Successfully!", Toast.LENGTH_SHORT).show() } btnGetall!!.setOnClickListener { val intent = Intent(this@MainActivity, GetAllUsersActivity::class.java) startActivity(intent) } } }
User will first enter the details like name, hobby and city. Then it will hit the Store button to insert the records into the SQLite database.
After inserting the records, it will empty all three edit texts.
When the user press the Get All Users From SQLite button, compiler will open the GetAllUsersActivity.
Download Code For Kotlin SQLite Multiple Tables
https://github.com/demonuts/Kotlin-SQLite-Multiple-Tables-Android-Example-Tutorial-One-Database