- 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
- Mobile App Development Guide
- Android SQLite Tutorial — Kotlin
- Project Setup:
- Coding Part
- CRUD Operations of SQLite
- Add Tasks
- Update Tasks
- Delete Tasks
- Read Tasks
- Full Code of this tutorial
- Download Code:
- About author: Mushtaq
- Follow Us
- Current Visitors
- Follow by Email
- Popular Posts
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"/>
Mobile App Development Guide
In this tutorial, we will learn how to implement SQLite Operations in Android with Kotlin . It is similar to the way of implementing SQL.
Android SQLite Tutorial — Kotlin
Android SQLite Tutorial — Kotlin
Android SQLite Tutorial — Kotlin
Android SQLite Tutorial — Kotlin
In this tutorial, we will learn how to implement SQLite Operations in Android with Kotlin . It is similar to the way of implementing SQLite using Java. To learn the basics of Kotlin click here.
Project Setup:
Create new Project with Kotlin Support in Android Studio 3.0 or If you are using Android Studio version below 3.0 then setup Kotlin Plugin.
Coding Part
DatabaseHandler
Create a Kotlin class named as DatabaseHandler.kt. It is used to Handle the database operations of SQLite with Kotlin. The Parent of this class is SQLiteOpenHelper. Paste the following code in DatabaseHandler.kt
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) < override fun onCreate(db: SQLiteDatabase) < val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID INTEGER PRIMARY KEY, $NAME TEXT,$DESC TEXT,$COMPLETED TEXT);" db.execSQL(CREATE_TABLE) >override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) < val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME" db.execSQL(DROP_TABLE) onCreate(db) >>
CRUD Operations of SQLite
Now we need to write methods for handling all database read and write operations. Here we are implementing following methods for our tasks table.
Insert data to Table
fun addTask(tasks: Tasks): Boolean
Get all data from Table
fun task(): List < val taskList = ArrayList() val db = writableDatabase val selectQuery = "SELECT * FROM $TABLE_NAME" val cursor = db.rawQuery(selectQuery, null) if (cursor != null) < if (cursor.moveToFirst()) < do < val tasks = Tasks() tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID))) tasks.name = cursor.getString(cursor.getColumnIndex(NAME)) tasks.desc = cursor.getString(cursor.getColumnIndex(DESC)) tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED)) taskList.add(tasks) >while (cursor.moveToNext()) > > cursor.close() return taskList >
Get particular data from Table
Update data to Table
fun updateTask(tasks: Tasks): Boolean
Delete data from Table
// delete particular data fun deleteTask(_id: Int): Boolean < val db = this.writableDatabase val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLong() db.close() return Integer.parseInt("$_success") != -1 >// delete all data fun deleteAllTasks(): Boolean
Full Code of DatabaseHandler
class DatabaseHandler(context: Context) : SQLiteOpenHelper(context, DatabaseHandler.DB_NAME, null, DatabaseHandler.DB_VERSION) < override fun onCreate(db: SQLiteDatabase) < val CREATE_TABLE = "CREATE TABLE $TABLE_NAME ($ID INTEGER PRIMARY KEY, $NAME TEXT,$DESC TEXT,$COMPLETED TEXT);" db.execSQL(CREATE_TABLE) >override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) < val DROP_TABLE = "DROP TABLE IF EXISTS $TABLE_NAME" db.execSQL(DROP_TABLE) onCreate(db) >fun addTask(tasks: Tasks): Boolean < val db = this.writableDatabase val values = ContentValues() values.put(NAME, tasks.name) values.put(DESC, tasks.desc) values.put(COMPLETED, tasks.completed) val _success = db.insert(TABLE_NAME, null, values) db.close() Log.v("InsertedId", "$_success") return (Integer.parseInt("$_success") != -1) >fun getTask(_id: Int): Tasks < val tasks = Tasks() val db = writableDatabase val selectQuery = "SELECT * FROM $TABLE_NAME WHERE $ID = $_id" val cursor = db.rawQuery(selectQuery, null) cursor?.moveToFirst() tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID))) tasks.name = cursor.getString(cursor.getColumnIndex(NAME)) tasks.desc = cursor.getString(cursor.getColumnIndex(DESC)) tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED)) cursor.close() return tasks >fun task(): List < val taskList = ArrayList() val db = writableDatabase val selectQuery = "SELECT * FROM $TABLE_NAME" val cursor = db.rawQuery(selectQuery, null) if (cursor != null) < if (cursor.moveToFirst()) < do < val tasks = Tasks() tasks.id = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ID))) tasks.name = cursor.getString(cursor.getColumnIndex(NAME)) tasks.desc = cursor.getString(cursor.getColumnIndex(DESC)) tasks.completed = cursor.getString(cursor.getColumnIndex(COMPLETED)) taskList.add(tasks) >while (cursor.moveToNext()) > > cursor.close() return taskList > fun updateTask(tasks: Tasks): Boolean < val db = this.writableDatabase val values = ContentValues() values.put(NAME, tasks.name) values.put(DESC, tasks.desc) values.put(COMPLETED, tasks.completed) val _success = db.update(TABLE_NAME, values, ID + "=?", arrayOf(tasks.id.toString())).toLong() db.close() return Integer.parseInt("$_success") != -1 >fun deleteTask(_id: Int): Boolean < val db = this.writableDatabase val _success = db.delete(TABLE_NAME, ID + "=?", arrayOf(_id.toString())).toLong() db.close() return Integer.parseInt("$_success") != -1 >fun deleteAllTasks(): Boolean < val db = this.writableDatabase val _success = db.delete(TABLE_NAME, null, null).toLong() db.close() return Integer.parseInt("$_success") != -1 >companion object < private val DB_VERSION = 1 private val DB_NAME = "MyTasks" private val TABLE_NAME = "Tasks" private val private val NAME = "Name" private val DESC = "Desc" private val COMPLETED = "Completed" >>
Add Tasks
val tasks: Tasks = Tasks() tasks.name = input_name.text.toString() tasks.desc = input_desc.text.toString() if (swt_completed.isChecked) tasks.completed = "Y" else tasks.completed = "N" success = dbHandler?.addTask(tasks) as Boolean
Update Tasks
val tasks: Tasks = Tasks() tasks.id = intent.getIntExtra("Id", 0) tasks.name = input_name.text.toString() tasks.desc = input_desc.text.toString() if (swt_completed.isChecked) tasks.completed = "Y" else tasks.completed = "N" success = dbHandler?.updateTask(tasks) as Boolean
Delete Tasks
// Delete Task val success = dbHandler?.deleteTask(intent.getIntExtra("Id", 0)) as Boolean // Delete All Tasks dbHandler. deleteAllTasks()
Read Tasks
// Read All Tasks val tasks: Tasks = dbHandler. getTask(intent.getIntExtra("Id",0)) // Read Particular Task dbHandler = DatabaseHandler(this) listTasks = (dbHandler as DatabaseHandler).task()
Full Code of this tutorial
class MainActivity : AppCompatActivity() < var taskRecyclerAdapter: TaskRecyclerAdapter? = null; var fab: FloatingActionButton? = null var recyclerView: RecyclerView? = null var dbHandler: DatabaseHandler? = null var listTasks: List= ArrayList() var linearLayoutManager: LinearLayoutManager? = null override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initViews() initOperations() //initDB() >fun initDB() < dbHandler = DatabaseHandler(this) listTasks = (dbHandler as DatabaseHandler).task() taskRecyclerAdapter = TaskRecyclerAdapter(tasksList = listTasks, context = applicationContext) (recyclerView as RecyclerView).adapter = taskRecyclerAdapter >fun initViews() < val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) fab = findViewById(R.id.fab) as FloatingActionButton recyclerView = findViewById(R.id.recycler_view) as RecyclerView taskRecyclerAdapter = TaskRecyclerAdapter(tasksList = listTasks, context = applicationContext) linearLayoutManager = LinearLayoutManager(applicationContext) (recyclerView as RecyclerView).layoutManager = linearLayoutManager >fun initOperations() < fab?.setOnClickListener < view ->val i = Intent(applicationContext, AddOrEditActivity::class.java) i.putExtra("Mode", "A") startActivity(i) > > override fun onCreateOptionsMenu(menu: Menu): Boolean < menuInflater.inflate(R.menu.menu_main, menu) return true >override fun onOptionsItemSelected(item: MenuItem): Boolean < val if (id == R.id.action_delete) < val dialog = AlertDialog.Builder(this).setTitle("Info").setMessage("Click 'YES' Delete All Tasks") .setPositiveButton("YES", < dialog, i ->dbHandler. deleteAllTasks() initDB() dialog.dismiss() >) .setNegativeButton("NO", < dialog, i ->dialog.dismiss() >) dialog.show() return true > return super.onOptionsItemSelected(item) > override fun onResume() < super.onResume() initDB() >>
class AddOrEditActivity : AppCompatActivity() < var dbHandler: DatabaseHandler? = null var isEditMode = false public override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_edit) supportActionBar?.setDisplayHomeAsUpEnabled(true) initDB() initOperations() >private fun initDB() < dbHandler = DatabaseHandler(this) btn_delete.visibility = View.INVISIBLE if (intent != null && intent.getStringExtra("Mode") == "E") < isEditMode = true val tasks: Tasks = dbHandler. getTask(intent.getIntExtra("Id",0)) input_name.setText(tasks.name) input_desc.setText(tasks.desc) swt_completed.isChecked = tasks.completed == "Y" btn_delete.visibility = View.VISIBLE >> private fun initOperations() < btn_save.setOnClickListener(< var success: Boolean = false if (!isEditMode) < val tasks: Tasks = Tasks() tasks.name = input_name.text.toString() tasks.desc = input_desc.text.toString() if (swt_completed.isChecked) tasks.completed = "Y" else tasks.completed = "N" success = dbHandler?.addTask(tasks) as Boolean >else < val tasks: Tasks = Tasks() tasks.id = intent.getIntExtra("Id", 0) tasks.name = input_name.text.toString() tasks.desc = input_desc.text.toString() if (swt_completed.isChecked) tasks.completed = "Y" else tasks.completed = "N" success = dbHandler?.updateTask(tasks) as Boolean >if (success) finish() >) btn_delete.setOnClickListener( < val dialog = AlertDialog.Builder(this).setTitle("Info").setMessage("Click 'YES' Delete the Task.") .setPositiveButton("YES", < dialog, i ->val success = dbHandler?.deleteTask(intent.getIntExtra("Id", 0)) as Boolean if (success) finish() dialog.dismiss() >) .setNegativeButton("NO", < dialog, i ->dialog.dismiss() >) dialog.show() >) > override fun onOptionsItemSelected(item: MenuItem): Boolean < val if (id == android.R.id.home) < finish() return true >return super.onOptionsItemSelected(item) > >
Download Code:
About author: Mushtaq
I am an Experienced Fullstack Developer with a demonstrated history of working in the information technology and services industry. Skilled in Android, iOS, Xamarin, UWP, Flutter, ASP.Net and RESTfull API’s.
Follow Us
Were this world an endless plain, and by sailing eastward we could for ever reach new distances
Current Visitors
Follow by Email
Popular Posts
- .Net MAUI — Local Storage Preferences
.Net MAUI — Page Navigation
How to Create a Digital Signature Application in Android
Upload File to Server using Retrofit in Android
How to Customize Snack Bar in Android