- How to use a simple SQLite database in Kotlin android?
- Android SQLite в Kotlin: подробно про работу с базой данных
- Класс SQLiteOpenHelper
- Конструкторы класса SQLiteOpenHelper
- Методы класса SQLiteOpenHelper
- Класс SQLiteDatabase
- Методы класса SQLiteDatabase
- Пример базы данных Kotlin Android SQLite CRUD
- Activity_main.xml
- MainActivity.kt
- EmpModelClass.kt
- custom_list.xml
- MyListAdapter.kt
- update_dialog.xml
- delete_dialog.xml
- DatabaseHandler.kt
- Kotlin sqlite android studio
- Android SQLite Database in Kotlin
How to use a simple SQLite database in Kotlin android?
This example demonstrates how to use a simple SQLite database in Kotlin android.
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
Step 3 − Add the following code to src/MainActivity.kt
package app.com.q10 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" val context = this val db = DataBaseHandler(context) btnInsert.setOnClickListener < if (editTextName.text.toString().isNotEmpty() && editTextAge.text.toString().isNotEmpty() ) < val user = User(editTextName.text.toString(), editTextAge.text.toString().toInt()) db.insertData(user) clearField() >else < Toast.makeText(context, "Please Fill All Data's", Toast.LENGTH_SHORT).show() >> btnRead.setOnClickListener < val data = db.readData() tvResult.text = "" for (i in 0 until data.size) < tvResult.append( data[i].id.toString() + " " + data[i].name + " " + data[i].age + "
" ) > > > private fun clearField() < editTextName.text.clear() editTextAge.text.clear() >>
Step 4 − Add the following code to src/DataBaseHelper.kt
import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.widget.Toast val DATABASENAME = "MY DATABASE" val TABLENAME = "Users" val COL_NAME = "name" val COL_AGE = "age" val COL_ID = "id" class DataBaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASENAME, null, 1) < override fun onCreate(db: SQLiteDatabase?) < val createTable = "CREATE TABLE " + TABLENAME + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_NAME + " VARCHAR(256)," + COL_AGE + " INTEGER)" db?.execSQL(createTable) >override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) < //onCreate(db); >fun insertData(user: User) < val database = this.writableDatabase val contentValues = ContentValues() contentValues.put(COL_NAME, user.name) contentValues.put(COL_AGE, user.age) val result = database.insert(TABLENAME, null, contentValues) if (result == (0).toLong()) < Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show() >else < Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show() >> fun readData(): MutableList < val list: MutableList= ArrayList() val db = this.readableDatabase val query = "Select * from $TABLENAME" val result = db.rawQuery(query, null) if (result.moveToFirst()) < do < val user = User() user.id = result.getString(result.getColumnIndex(COL_ID)).toInt() user.name = result.getString(result.getColumnIndex(COL_NAME)) user.age = result.getString(result.getColumnIndex(COL_AGE)).toInt() list.add(user) >while (result.moveToNext()) > return list > >
Step 5 − Add the following code to androidManifest.xml
Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Android SQLite в Kotlin: подробно про работу с базой данных
SQLite — это реляционная база данных с открытым исходным кодом, которая используется для выполнения операций с базой данных на устройствах Android, таких как хранение, обработка или извлечение постоянных данных из базы данных.
По умолчанию база данных SQLite встроена в android. Таким образом, нет необходимости выполнять какие-либо задачи по настройке или администрированию базы данных.
Класс SQLiteOpenHelper предоставляет функциональные возможности для использования базы данных Android SQLite в Kotlin.
Класс SQLiteOpenHelper
Класс android.database.sqlite.SQLiteOpenHelper используется для создания базы данных и управления версиями. Для выполнения любой операции с базой данных необходимо обеспечить реализацию методов onCreate() и onUpgrade() класса SQLiteOpenHelper.
Конструкторы класса SQLiteOpenHelper
Есть два конструктора класса SQLiteOpenHelper.
Конструктор | Описание |
---|---|
SQLiteOpenHelper(context: Context, name: String, factory: SQLiteDatabase.CursorFactory, version: Int) | Создает объект SQLiteOpenHelper для создания, открытия и управления базой данных. |
SQLiteOpenHelper((context: Context, name: String, factory: SQLiteDatabase.CursorFactory, version: Int, errorHandler: DatabaseErrorHandler) | Создает объект SQLiteOpenHelper для создания, открытия и управления базой данных. Указывается обработчик ошибок. |
Методы класса SQLiteOpenHelper
В классе SQLiteOpenHelper доступно несколько методов. Некоторые из них упомянуты ниже:
Метод | Описание |
---|---|
public abstract void onCreate(SQLiteDatabase db) | Вызывается только один раз при первом создании базы данных. |
public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) | Вызывается, когда необходимо обновить базу данных. |
public synchronized void close() | Закрывает объект базы данных. |
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) | вызывается, когда базе данных необходимо понизить рейтинг. |
Класс SQLiteDatabase
Он содержит методы, которые должны выполняться в базе данных SQLite, такие как создание, обновление, удаление, выбор и т. д.
Методы класса SQLiteDatabase
В классе SQLiteDatabase есть много методов. Вот некоторые из них:
Метод | Описание |
---|---|
execSQL(String sql): Unit | Выполняет запрос SQL, а не запрос выбора. |
insert(String table, String nullColumnHack, ContentValues values): Long | Вставляет запись в базу данных. В таблице указывается имя таблицы, nullColumnHack не допускает полностью пустых значений. Если второй аргумент равен нулю, Android будет хранить нулевые значения, если значения пусты. Третий аргумент указывает значения, которые необходимо сохранить. |
update(String table, ContentValues values, String whereClause, String[] whereArgs): Int | Обновляет строку. |
query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy): Cursor | Возвращает курсор над набором результатов. |
Пример базы данных Kotlin Android SQLite CRUD
В этом примере мы выполним операцию создания, чтения, обновления и удаления в базе данных Android SQLite.
Activity_main.xml
В файл activity_main.xml добавьте следующий код. В этом файле мы добавили три EditText, один ListView, четыре кнопки для операций сохранения, просмотра, обновления и удаления.
MainActivity.kt
Добавьте следующий код в класс MainActivity.kt. В этом классе функция saveRecord() сохраняет записи. Функция viewRecord() считывает записи и отображает их в ListView, функция updateRecord() обновляет запись на основе id, а функция deleteRecord() удаляет запись. val databaseHandler: DatabaseHandler= DatabaseHandler(this) создает экземпляр класса DatabaseHandler, вызывая логику базы данных SQLite.
package example.javatpoint.com.kotlinsqlitecrud import android.support.v7.app.AppCompatActivity 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 import android.support.v7.app.AlertDialog class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) >//method for saving records in database fun saveRecord(view: View) < val 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 save",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() >> //method for read records from database in ListView fun viewRecord(view: View) < //creating the instance of DatabaseHandler class val databaseHandler: DatabaseHandler= DatabaseHandler(this) //calling the viewEmployee method of DatabaseHandler class to read the records val emp: List = databaseHandler.viewEmployee() val empArrayId = Array(emp.size)val empArrayName = Array(emp.size) val empArrayEmail = Array(emp.size) var index = 0 for(e in emp) < empArrayId[index] = e.userId.toString() empArrayName[index] = e.userName empArrayEmail[index] = e.userEmail index++ >//creating custom ArrayAdapter val myListAdapter = MyListAdapter(this,empArrayId,empArrayName,empArrayEmail) listView.adapter = myListAdapter > //method for updating records based on user id fun updateRecord(view: View) < val dialogBuilder = AlertDialog.Builder(this) val inflater = this.layoutInflater val dialogView = inflater.inflate(R.layout.update_dialog, null) dialogBuilder.setView(dialogView) val edtId = dialogView.findViewById(R.id.updateId) as EditText val edtName = dialogView.findViewById(R.id.updateName) as EditText val edtEmail = dialogView.findViewById(R.id.updateEmail) as EditText dialogBuilder.setTitle("Update Record") dialogBuilder.setMessage("Enter data below") dialogBuilder.setPositiveButton("Update", DialogInterface.OnClickListener < _, _ ->val updateId = edtId.text.toString() val updateName = edtName.text.toString() val updateEmail = edtEmail.text.toString() //creating the instance of DatabaseHandler class val databaseHandler: DatabaseHandler= DatabaseHandler(this) if(updateId.trim()!="" && updateName.trim()!="" && updateEmail.trim()!="") < //calling the updateEmployee method of DatabaseHandler class to update record val status = databaseHandler.updateEmployee(EmpModelClass(Integer.parseInt(updateId),updateName, updateEmail)) if(status >-1) < Toast.makeText(applicationContext,"record update",Toast.LENGTH_LONG).show() >>else < Toast.makeText(applicationContext,"id or name or email cannot be blank",Toast.LENGTH_LONG).show() >>) dialogBuilder.setNegativeButton("Cancel", DialogInterface.OnClickListener < dialog, which ->//pass >) val b = dialogBuilder.create() b.show() > //method for deleting records based on id fun deleteRecord(view: View) < //creating AlertDialog for taking user id val dialogBuilder = AlertDialog.Builder(this) val inflater = this.layoutInflater val dialogView = inflater.inflate(R.layout.delete_dialog, null) dialogBuilder.setView(dialogView) val dltId = dialogView.findViewById(R.id.deleteId) as EditText dialogBuilder.setTitle("Delete Record") dialogBuilder.setMessage("Enter id below") dialogBuilder.setPositiveButton("Delete", DialogInterface.OnClickListener < _, _ ->val deleteId = dltId.text.toString() //creating the instance of DatabaseHandler class val databaseHandler: DatabaseHandler= DatabaseHandler(this) if(deleteId.trim()!="") < //calling the deleteEmployee method of DatabaseHandler class to delete record val status = databaseHandler.deleteEmployee(EmpModelClass(Integer.parseInt(deleteId),"","")) if(status >-1) < Toast.makeText(applicationContext,"record deleted",Toast.LENGTH_LONG).show() >>else < Toast.makeText(applicationContext,"id or name or email cannot be blank",Toast.LENGTH_LONG).show() >>) dialogBuilder.setNegativeButton("Cancel", DialogInterface.OnClickListener < _, _ ->//pass >) val b = dialogBuilder.create() b.show() > >
EmpModelClass.kt
Создание класса модели данных с именем EmpModelClass.kt
package example.javatpoint.com.kotlinsqlitecrud //creating a Data Model Class class EmpModelClass(var userId: Int, val userName:String , val userEmail: String)
custom_list.xml
Создайте собственный макет строки для отображения элементов списка в ListView.
MyListAdapter.kt
Теперь создайте собственный класс адаптера с именем MyListAdapter.kt и расширяйте класс ArrayAdapter, который заполняет модель данных в ListView.
package example.javatpoint.com.kotlinsqlitecrud import android.app.Activity import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.TextView class MyListAdapter(private val context: Activity, private val id: Array, private val name: Array, private val email: Array) : ArrayAdapter(context, R.layout.custom_list, name) < override fun getView(position: Int, view: View?, parent: ViewGroup): View < val inflater = context.layoutInflater val rowView = inflater.inflate(R.layout.custom_list, null, true) val idText = rowView.findViewById(R.id.textViewId) as TextView val nameText = rowView.findViewById(R.id.textViewName) as TextView val emailText = rowView.findViewById(R.id.textViewEmail) as TextView idText.text = "Id: $" nameText.text = "Name: $" emailText.text = "Email: $" return rowView > >
update_dialog.xml
Создайте макет для отображения AlertDialog для записи обновления.
delete_dialog.xml
Создайте макет для отображения AlertDialog для удаления записи.
DatabaseHandler.kt
Создайте класс DatabaseHandler.kt, расширяющий класс SQLiteOpenHelper, и переопределите его функции onCreate(), onUpgrage(). Вставьте данные в базу данных, передав объект ContentValues методу insert().
package example.javatpoint.com.kotlinsqlitecrud 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 fun viewEmployee():List< val empList:ArrayList = ArrayList() val selectQuery = "SELECT * FROM $TABLE_CONTACTS" val db = this.readableDatabase var cursor: Cursor? = null try< cursor = db.rawQuery(selectQuery, null) >catch(e: SQLiteException) < db.execSQL(selectQuery) return ArrayList() >var userId: Int var userName: String var userEmail: String if(cursor.moveToFirst()) < do < userId = cursor.getInt(cursor.getColumnIndex("id")) userName = cursor.getString(cursor.getColumnIndex("name")) userEmail = cursor.getString(cursor.getColumnIndex("email")) val emp= EmpModelClass(userId = userId, userName = userName, userEmail = userEmail) empList.add(emp) >while(cursor.moveToNext()) > return empList > //method to update data fun updateEmployee(emp: EmpModelClass):Int < 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 Email // Updating Row val success = db.update(TABLE_CONTACTS, contentValues,"id="+emp.userId,null) //2nd argument is String containing nullColumnHack db.close() // Closing database connection return success >//method to delete data fun deleteEmployee(emp: EmpModelClass):Int< val db = this.writableDatabase val contentValues = ContentValues() contentValues.put(KEY_ID, emp.userId) // EmpModelClass UserId // Deleting Row val success = db.delete(TABLE_CONTACTS,"id async" src="https://static.javatpoint.com/kotlin/images/kotlin-android-sqlite-tutorial-output1.png" alt="Kotlin Android SQLite" width="249" height="442"/>
Kotlin sqlite android studio
Android SQLite Database in Kotlin
The name of the database in Android is SQLite. SQLite is the name of the opensource SQL database that stores the data in the text file in the device. Android has its implementation.
Here, We will be learning about SQLite Database and we will also implement an application.
Let’s start with the implementation:We will be developing an app where a user can store a string, and it will display on the TextView on screen.Let’s first create our main screen
Android provides us with the SQLiteOpenHelper class which helps us to interact with the SQLite Database. This class includes methods like create, insert, delete and update for data CRUD.
Let’s create a class called Name which will act as our model class
class Name < var id: Int = 0 var userName: String? = null constructor(id: Int, userName: String) < this.id = id this.userName = userName >constructor(userName: String) < this.userName = userName >>
Let’s crea.te an OpenHelper class
class MindOrksDBOpenHelper(context: Context, factory: SQLiteDatabase.CursorFactory?) : SQLiteOpenHelper(context, DATABASE_NAME, factory, DATABASE_VERSION) < override fun onCreate(db: SQLiteDatabase) < val CREATE_PRODUCTS_TABLE = ("CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT" + ")") db.execSQL(CREATE_PRODUCTS_TABLE) >override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) < db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME) onCreate(db) >fun addName(name: Name) < val values = ContentValues() values.put(COLUMN_NAME, name.userName) val db = this.writableDatabase db.insert(TABLE_NAME, null, values) db.close() >fun getAllName(): Cursor? < val db = this.readableDatabase return db.rawQuery("SELECT * FROM $TABLE_NAME", null) >companion object < private val DATABASE_VERSION = 1 private val DATABASE_NAME = "mindorksName.db" val TABLE_NAME = "name" val COLUMN_ID = "_id" val COLUMN_NAME = "username" >>
Now, we will implement our add to database button
btnAddToDb.setOnClickListener
and also, our get all names from database button
btnShowDatafromDb.setOnClickListener < tvDisplayName.text = "" val dbHandler = MindOrksDBOpenHelper(this, null) val cursor = dbHandler.getAllName() cursor. moveToFirst() tvDisplayName.append((cursor.getString(cursor.getColumnIndex(MindOrksDBOpenHelper.COLUMN_NAME)))) while (cursor.moveToNext()) < tvDisplayName.append((cursor.getString(cursor.getColumnIndex(MindOrksDBOpenHelper.COLUMN_NAME)))) tvDisplayName.append("\n") >cursor.close() > class MainActivity : AppCompatActivity() < override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btnAddToDb.setOnClickListener < val dbHandler = MindOrksDBOpenHelper(this, null) val user = Name(etName.text.toString()) dbHandler.addName(user) Toast.makeText(this, etName.text.toString() + "Added to database", Toast.LENGTH_LONG).show() >btnShowDatafromDb.setOnClickListener < tvDisplayName.text = "" val dbHandler = MindOrksDBOpenHelper(this, null) val cursor = dbHandler.getAllName() cursor. moveToFirst() tvDisplayName.append((cursor.getString(cursor.getColumnIndex(MindOrksDBOpenHelper.COLUMN_NAME)))) while (cursor.moveToNext()) < tvDisplayName.append((cursor.getString(cursor.getColumnIndex(MindOrksDBOpenHelper.COLUMN_NAME)))) tvDisplayName.append("\n") >cursor.close() > > >
Let’s try to run this app. Great Work!! You are saving the data in the database and showing it on the screen. Try to implement the delete query and explore more on this. Let us know on our slack and twitter channel.