How to update listview after insert values in Android sqlite using Kotlin?

This example demonstrates how to update listview after insert values in Android sqlite using Kotlin.

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.

Example











Step 3 − Add the following code to src/MainActivity.kt

import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private lateinit var save: Button
   private lateinit var refresh: Button
   private lateinit var name: EditText
   private lateinit var salary: EditText
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val helper = DatabaseHelper(this)
      val arrayList: ArrayList = helper.getAllContacts() as ArrayList
      name = findViewById(R.id.name)
      salary = findViewById(R.id.salary)
      save = findViewById(R.id.save)
      refresh = findViewById(R.id.refresh)
      val listView: ListView = findViewById(R.id.listView)
      val arrayAdapter: ArrayAdapter = ArrayAdapter(this@MainActivity,
      android.R.layout.simple_list_item_1, arrayList as List)
      listView.adapter = arrayAdapter
         save.setOnClickListener {
            arrayList.clear()
            arrayList.addAll(helper.getAllContacts())
            arrayAdapter.notifyDataSetChanged()
            listView.invalidateViews()
            listView.refreshDrawableState()
         }
         refresh.setOnClickListener {
            if (name.text.toString().isNotEmpty() && salary.text.toString().isNotEmpty()) {
            if (helper.addData(name.text.toString(), salary.text.toString())) {
               Toast.makeText(this, "Inserted", Toast.LENGTH_LONG).show()
            } else {
               Toast.makeText(this, "NOT Inserted", Toast.LENGTH_LONG).show()
            }
         } else {
            name.error = "Enter NAME"
            salary.error = "Enter Salary"
         }
      }
   }
}

Step 4 − Create a new class DataBaseHelper.kt and add the following code

import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import java.io.IOException
class DatabaseHelper(context: Context) :
SQLiteOpenHelper(context, dataBaseName, null, dataBaseVersion) {
   private val contactsTableName = "SalaryDetails"
   companion object {
      const val dataBaseName = "salaryDatabase3"
      const val dataBaseVersion = 1
   }
   override fun onCreate(db: SQLiteDatabase?) {
      try {
         db?.execSQL("create table $contactsTableName(id INTEGER PRIMARY KEY, name text,salary text          )")
      } catch (e: SQLiteException) {
         try {
            throw IOException(e)
         } catch (e1: IOException) {
            e1.printStackTrace()
         }
      }
   }
   override fun onUpgrade(db: SQLiteDatabase?, p1: Int, p2: Int) {
      db?.execSQL("DROP TABLE IF EXISTS $contactsTableName")
      onCreate(db)
   }
   fun addData(s: String?, s1: String?): Boolean {
      val db = this.writableDatabase
      val contentValues = ContentValues()
      contentValues.put("name", s)
      contentValues.put("salary", s1)
      db.insert(contactsTableName, null, contentValues)
      return true
   }
   fun getAllContacts(): Collection {
      val db: SQLiteDatabase = this.readableDatabase
      val arrayList = ArrayList()
      val res: Cursor = db.rawQuery("select * from $contactsTableName", null)
      res.moveToFirst()
      while (!res.isAfterLast) {
         arrayList.add(res.getString(res.getColumnIndex("name")));
         res.moveToNext();
      }
      return arrayList
   }
}

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.

Updated on: 2020-07-21T12:44:14+05:30

751 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements