Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cập nhật ListView sau khi insert dữ liệu SQLite trong Android Kotlin

Hướng dẫn này minh họa cách cập nhật ListView sau khi thêm dữ liệu vào SQLite database trong Android sử dụng Kotlin.

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (activity_main.xml)

<?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="Nhập tên" />

    <EditText
        android:id="@+id/salary"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Nhập lương"
        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="Lưu" />

        <Button
            android:id="@+id/refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Làm mới" />

    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>

</LinearLayout>

Bước 3: Viết code 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<String>()
        arrayList.addAll(helper.getAllContacts())

        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<String>(
            this@MainActivity,
            android.R.layout.simple_list_item_1,
            arrayList
        )
        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, "Đã thêm", Toast.LENGTH_LONG).show()
                } else {
                    Toast.makeText(this, "Thêm thất bại", Toast.LENGTH_LONG).show()
                }
            } else {
                name.error = "Nhập tên"
                salary.error = "Nhập lương"
            }
        }
    }
}

Bước 4: Tạo DatabaseHelper.kt

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, DATABASE_NAME, null, DATABASE_VERSION
) {
    private val TABLE_NAME = "SalaryDetails"

    companion object {
        const val DATABASE_NAME = "salaryDatabase3"
        const val DATABASE_VERSION = 1
    }

    override fun onCreate(db: SQLiteDatabase?) {
        try {
            db?.execSQL("CREATE TABLE $TABLE_NAME (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?, oldVersion: Int, newVersion: Int) {
        db?.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
        onCreate(db)
    }

    fun addData(name: String?, salary: String?): Boolean {
        val db = writableDatabase
        val values = ContentValues().apply {
            put("name", name)
            put("salary", salary)
        }
        db.insert(TABLE_NAME, null, values)
        return true
    }

    fun getAllContacts(): List<String> {
        val db = readableDatabase
        val list = mutableListOf<String>()
        val cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null)
        cursor.moveToFirst()
        while (!cursor.isAfterLast) {
            list.add(cursor.getString(cursor.getColumnIndexOrThrow("name")))
            cursor.moveToNext()
        }
        cursor.close()
        return list
    }
}

Bước 5: Cấu hình AndroidManifest.xml

<?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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Nhập tên và lương, nhấn "Làm mới" để thêm vào DB, sau đó nhấn "Lưu" để cập nhật ListView hiển thị danh sách mới.

Giải thích cơ chế cập nhật ListView

  1. arrayList.clear() - Xóa dữ liệu cũ trong list
  2. arrayList.addAll(...) - Thêm dữ liệu mới từ DB
  3. arrayAdapter.notifyDataSetChanged() - Thông báo adapter dữ liệu đã thay đổi
  4. listView.invalidateViews() - Vẽ lại các view con
  5. listView.refreshDrawableState() - Làm mới trạng thái drawable
Mẹo: Nên sử dụng RecyclerView + DiffUtil cho hiệu năng tốt hơn ListView cổ điển.