이 튜토리얼에서는 Kotlin을 사용해 Android SQLite 데이터베이스에 값을 삽입한 후, ListView가 최신 데이터를 반영하도록 즉시 갱신하는 방법을 단계별로 살펴봅니다. 핵심은 데이터 삽입 후 어댑터의 notifyDataSetChanged()를 호출하여 화면을 다시 그리는 것입니다.
1단계 – 새 프로젝트 생성
Android Studio에서 File → New Project를 선택하고, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 – 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다. 이름과 급여를 입력받는 EditText 두 개, 저장·새로고침 버튼, 그리고 결과를 표시할 ListView로 구성됩니다.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Name" /> <EditText android:id="@+id/salary" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter Salary" android:inputType="numberDecimal" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:id="@+id/save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save" /> <Button android:id="@+id/refresh" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Refresh" /> </LinearLayout> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content"> </ListView> </LinearLayout>
3단계 – MainActivity.kt 작성
src/MainActivity.kt에 다음 코드를 추가합니다. 저장 버튼을 누르면 입력값의 유효성을 검사한 뒤 DB에 데이터를 삽입하고, 새로고침 버튼을 누르면 DB에서 전체 데이터를 다시 읽어와 어댑터를 갱신합니다.
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<String> = helper.getAllContacts() as ArrayList<String>
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<Any?>(this@MainActivity,
android.R.layout.simple_list_item_1, arrayList as List<Any?>)
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"
}
}
}4단계 – DatabaseHelper 클래스 작성
새 클래스 DatabaseHelper.kt를 만들고 아래 코드를 추가합니다. SQLiteOpenHelper를 상속받아 테이블 생성, 데이터 삽입, 전체 조회 기능을 구현합니다.
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<String> {
val db: SQLiteDatabase = this.readableDatabase
val arrayList = ArrayList<String>()
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
}
}5단계 – AndroidManifest.xml 확인
AndroidManifest.xml에 아래와 같이 MainActivity가 등록되어 있는지 확인합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘
을 클릭하세요. 실행할 기기 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

이름과 급여를 입력한 뒤 Refresh 버튼으로 데이터를 저장하고, Save 버튼을 누르면 ListView가 즉시 갱신되어 새로 추가된 항목이 목록에 나타나는 것을 확인할 수 있습니다.