Android
 Computer >> コンピューター >  >> プログラミング >> Android

【Kotlin】Android SQLiteでデータ挿入後にListViewを更新する方法を徹底解説

はじめに

このチュートリアルでは、Kotlinを使用してAndroidアプリのSQLiteデータベースに値を挿入した後、ListView(リストビュー)を即座に更新する方法を解説します。従業員の「名前」と「給与」を入力してSQLiteに保存し、その内容をリストビューに表示・反映させるシンプルなサンプルアプリを題材にします。

ステップ1:新規プロジェクトの作成

まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。

ステップ2:レイアウトファイル(activity_main.xml)の編集

res/layout/activity_main.xml に以下のコードを追加します。名前と給与を入力するための2つのEditText、保存用・更新用の2つのButton、そしてデータ一覧を表示するListViewを縦方向のLinearLayoutに配置しています。

レイアウトのサンプルコード

<?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 に以下のコードを追加します。ここでのポイントは、データ操作後にアダプターに対して notifyDataSetChanged() を呼び出すことです。これにより、ListViewがSQLiteの最新データを反映した状態に更新されます。

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.kt クラスの作成

続いて、新しいクラス「DatabaseHelper.kt」を作成し、以下のコードを追加します。このクラスはSQLiteOpenHelperを継承しており、データベースの作成・バージョン管理、データの挿入(addData)、全件取得(getAllContacts)といった処理を担います。

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」アイコン【Kotlin】Android SQLiteでデータ挿入後にListViewを更新する方法を徹底解説(緑色の再生ボタン)をクリックします。デバイス選択画面で自分のモバイル端末を選択すると、端末上にアプリの初期画面が表示されます。

【Kotlin】Android SQLiteでデータ挿入後にListViewを更新する方法を徹底解説


  1. 【Android開発】ListViewのArrayListに要素を追加・表示する方法を実例付きで解説

    AndroidでListViewのArrayListに要素を挿入する方法 この記事では、AndroidアプリにおいてEditTextに入力したテキストをArrayListに追加し、その内容をListViewに表示する方法を、実際のコード例とともに段階的に解説します。 手順1:新しいプロジェクトを作成する まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。 手順2:レイアウトファイル(activity_main.xml)にコードを追加する 次に、res/l

  2. 【Android開発】ListViewの項目を動的に更新する方法をわかりやすく解説

    はじめに Androidアプリ開発では、リスト表示に使われる「ListView」の内容を実行中に書き換えたい場面がよくあります。例えば、ユーザーがリストの項目をタップしたときに、その項目の値を別の値に変更するといった処理です。 本記事では、ListViewの項目をタップすると、その値が「100」に動的に更新されるサンプルアプリを題材に、具体的な実装手順を初心者向けに解説します。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから File → New Project を選択して新しいプロジェクトを作成します。必要な項目(