{"id":10088,"date":"2023-07-04T08:44:50","date_gmt":"2023-07-04T05:14:50","guid":{"rendered":"http:\/\/milmit.net\/teaching-sqlite-database-in-kotlin\/"},"modified":"2023-07-04T08:44:50","modified_gmt":"2023-07-04T05:14:50","slug":"teaching-sqlite-database-in-kotlin","status":"publish","type":"post","link":"https:\/\/milmit.net\/en\/teaching-sqlite-database-in-kotlin\/","title":{"rendered":"Teaching SQLite database in Kotlin"},"content":{"rendered":"<p>We will teach the SQLite database in Kotlin. The sqlite database is one of the most famous databases in Android. It is used to store data. Using the sqlite database in Kotlin is very similar to Java. Follow us to learn how to use the sqlite database. take<\/p>\n<p>You don&#8217;t need to add a special library to use the Sqlite database.<br \/>\nThe first step to use the sqlite database is to create a DatabaseHandler or DatabaseHelper. In fact, by using these types of classes, the operations of inserting and updating will be easier to read.<br \/>\nEnter your layer called activity_main and put the following codes.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\r\n&lt;LinearLayout xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\"\r\n   xmlns:app=\"http:\/\/schemas.android.com\/apk\/res-auto\"\r\n   xmlns:tools=\"http:\/\/schemas.android.com\/tools\"\r\n   android:layout_width=\"match_parent\"\r\n   android:layout_height=\"match_parent\"\r\n   android:orientation=\"vertical\"\r\n   tools:context=\".MainActivity\"&gt;\r\n   &lt;LinearLayout\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:orientation=\"vertical\"&gt;\r\n   &lt;EditText\r\n      android:id=\"@+id\/editTextName\"\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:layout_margin=\"10dp\"\r\n      android:padding=\"8dp\" \/&gt;\r\n   &lt;EditText\r\n      android:id=\"@+id\/editTextAge\"\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:layout_margin=\"10dp\"\r\n      android:autofillHints=\"Age\"\r\n      android:inputType=\"number\"\r\n      android:padding=\"8dp\"\r\n      android:textColor=\"@android:color\/background_dark\" \/&gt;\r\n   &lt;Button\r\n      android:id=\"@+id\/btnInsert\"\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:layout_margin=\"10dp\"\r\n      android:padding=\"8dp\"\r\n      android:text=\"Add data\" \/&gt;\r\n   &lt;\/LinearLayout&gt;\r\n   &lt;LinearLayout\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:gravity=\"center\"\r\n      android:orientation=\"horizontal\"\r\n      android:weightSum=\"3\"&gt;\r\n   &lt;Button\r\n      android:id=\"@+id\/btnRead\"\r\n      android:layout_width=\"0dp\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:layout_margin=\"10dp\"\r\n      android:layout_weight=\"1\"\r\n      android:padding=\"8dp\"\r\n      android:text=\"Read\" \/&gt;\r\n   &lt;\/LinearLayout&gt;\r\n   &lt;ScrollView\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"match_parent&gt;\r\n   &lt;TextView\r\n      android:id=\"@+id\/tvResult\"\r\n      android:layout_width=\"match_parent\"\r\n      android:layout_height=\"wrap_content\"\r\n      android:padding=\"8dp\"\r\n      android:textSize=\"16sp\"\r\n      android:textStyle=\"bold\" \/&gt;\r\n   &lt;\/ScrollView&gt;\r\n&lt;\/LinearLayout&gt;<\/pre>\n<p>Above we have two input fields that enter the user&#8217;s information in the SQlite database and a button that shows the information entered in the database.<br \/>\nCreate a class called DataBaseHelper.kt and put the following code in it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import android.content.ContentValues\r\nimport android.content.Context\r\nimport android.database.sqlite.SQLiteDatabase\r\nimport android.database.sqlite.SQLiteOpenHelper\r\nimport android.widget.Toast\r\nval DATABASENAME = \"MY DATABASE\"\r\nval TABLENAME = \"Users\"\r\nval COL_NAME = \"name\"\r\nval COL_AGE = \"age\"\r\nval COL_ID = \"id\"\r\nclass DataBaseHandler(var context: Context) : SQLiteOpenHelper(context, DATABASENAME, null,\r\n1) {\r\n   override fun onCreate(db: SQLiteDatabase?) {\r\n      val createTable = \"CREATE TABLE \" + TABLENAME + \" (\" + COL_ID + \" INTEGER PRIMARY KEY AUTOINCREMENT,\" + COL_NAME + \" VARCHAR(256),\" + COL_AGE + \" INTEGER)\"\r\n      db?.execSQL(createTable)\r\n   }\r\n   override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {\r\n      \/\/onCreate(db);\r\n   }\r\n   fun insertData(user: User) {\r\n      val database = this.writableDatabase\r\n      val contentValues = ContentValues()\r\n      contentValues.put(COL_NAME, user.name)\r\n      contentValues.put(COL_AGE, user.age)\r\n      val result = database.insert(TABLENAME, null, contentValues)\r\n      if (result == (0).toLong()) {\r\n         Toast.makeText(context, \"Failed\", Toast.LENGTH_SHORT).show()\r\n      }\r\n      else {\r\n         Toast.makeText(context, \"Success\", Toast.LENGTH_SHORT).show()\r\n      }\r\n   }\r\n   fun readData(): MutableList&lt;User&gt; {\r\n      val list: MutableList&lt;User&gt; = ArrayList()\r\n      val db = this.readableDatabase\r\n      val query = \"Select * from $TABLENAME\"\r\n      val result = db.rawQuery(query, null)\r\n      if (result.moveToFirst()) {\r\n         do {\r\n            val user = User()\r\n            user.id = result.getString(result.getColumnIndex(COL_ID)).toInt()\r\n            user.name = result.getString(result.getColumnIndex(COL_NAME))\r\n            user.age = result.getString(result.getColumnIndex(COL_AGE)).toInt()\r\n            list.add(user)\r\n         }\r\n         while (result.moveToNext())\r\n      }\r\n      return list\r\n   }\r\n}<\/pre>\n<p>onCreate creates the database.<br \/>\nonUpgrade: If the database is updated, the database will be dropped once and then created from scratch.<br \/>\ninsertData: Insertion is done by this method.<br \/>\nreadData: shows the information stored in the database.<br \/>\nTo use this class, we enter MainActivity.kt and call the subclass.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import androidx.appcompat.app.AppCompatActivity\r\nimport android.os.Bundle\r\nimport android.widget.Toast\r\nimport kotlinx.android.synthetic.main.activity_main.*\r\nclass MainActivity : AppCompatActivity() {\r\n   override fun onCreate(savedInstanceState: Bundle?) {\r\n      super.onCreate(savedInstanceState)\r\n      setContentView(R.layout.activity_main)\r\n      title = \"KotlinApp\"\r\n      val context = this\r\n      val db = DataBaseHandler(context)\r\n      btnInsert.setOnClickListener {\r\n         if (editTextName.text.toString().isNotEmpty() &amp;&amp;\r\n            editTextAge.text.toString().isNotEmpty()\r\n         ) {\r\n            val user = User(editTextName.text.toString(), editTextAge.text.toString().toInt())\r\n            db.insertData(user)\r\n            clearField()\r\n         }\r\n         else {\r\n            Toast.makeText(context, \"Please Fill All Data's\", Toast.LENGTH_SHORT).show()\r\n         }\r\n      }\r\n      btnRead.setOnClickListener {\r\n         val data = db.readData()\r\n         tvResult.text = \"\"\r\n         for (i in 0 until data.size) {\r\n            tvResult.append(\r\n               data[i].id.toString() + \" \" + data[i].name + \" \" + data[i].age + \"\\n\"\r\n            )\r\n         }\r\n      }\r\n   }\r\n   private fun clearField() {\r\n      editTextName.text.clear()\r\n      editTextAge.text.clear()\r\n   }\r\n}<\/pre>\n<p>The above code receives the information from EditText and inserts the received information into the database, and it is also possible to see the stored data.<\/p>\n<p>be successful and victorious.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We will teach the SQLite database in Kotlin. The sqlite database is one of the most famous databases in Android. It is used to store data. Using the sqlite database in Kotlin is very similar to Java. Follow us to learn how to use the sqlite database. take You don&#8217;t need to add a special [&hellip;]<\/p>\n","protected":false},"author":4,"featured_media":4933,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-10088","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry"],"_links":{"self":[{"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/posts\/10088","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/comments?post=10088"}],"version-history":[{"count":0,"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/posts\/10088\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/media\/4933"}],"wp:attachment":[{"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/media?parent=10088"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/categories?post=10088"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/milmit.net\/en\/wp-json\/wp\/v2\/tags?post=10088"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}