Kotlin Android SQLite TutorialSQLite is an open-source relational database that is used to perform database operations on Android devices such as storing, manipulating or retrieving persistent data from the database. By default SQLite database is embedded in android. So, there is no need to perform any database setup or administration task. The SQLiteOpenHelper class provides the functionality to use the SQLite database. SQLiteOpenHelper classThe android.database.sqlite.SQLiteOpenHelper class is used for database creation and version management. For performing any database operation, you have to provide the implementation of onCreate() and onUpgrade() methods of SQLiteOpenHelper class. Constructors of SQLiteOpenHelper classThere are two constructors of SQLiteOpenHelper class.
Methods of SQLiteOpenHelper classThere are several methods available in the SQLiteOpenHelper class. Some of them are mentioned below:
SQLiteDatabase classIt contains methods to be performed on the SQLite database such as create, update, delete, select etc. Methods of SQLiteDatabase classThere are many methods in the SQLiteDatabase class. Some of them are as follows:
Kotlin Android SQLite Database CRUD ExampleIn this example, we will perform create, read, update and delete operation on Android SQLite database. activity_main.xmlIn the activity_main.xml file add the following code. In this file, we added three EditText, one ListView, four Button for saving, view, update and delete operation. MainActivity.ktAdd the following code in the MainActivity.kt class. In this class, the saveRecord() function saves the records. The viewRecord() function reads the record and displays them into ListView, the updateRecord() function updates the record on the basis on id, and deleteRecord() function deletes the record. The val databaseHandler: DatabaseHandler= DatabaseHandler(this) creates the instance of DatabaseHandler class calls the SQLite database logic. EmpModelClass.ktCreating a data model class named as EmpModelClass.kt custom_list.xmlCreate a custom row layout for displaying the list items in the ListView. MyListAdapter.ktNow, create a custom adapter class named as MyListAdapter.kt and extends ArrayAdapter class which populates the data model into the ListView. update_dialog.xmlCreate a layout for display AlertDialog for update record. delete_dialog.xmlCreate a layout for display AlertDialog for delete record. DatabaseHandler.ktCreate the DatabaseHandler.kt class that extends SQLiteOpenHelper class and override its onCreate(), onUpgrage() functions. Insert data into the database by passing a ContentValues object to the insert() method. Output: Next Topic# |