반응형

SQLite

설명

  • 안드로이드는 SQLite 데이터베이스를 사용하여 데이터를 관리할 수 있다.

코드

UserDBHelper
// 마지막 파라미터가 버전
// 버전값이 변경되면 onUpgrade 메소드가 호출되어 테이블을 변경하는 작업을 수행
class UserDBHelper(context: Context) : SQLiteOpenHelper(context, "Test.db", null, 1) {
    override fun onCreate(db: SQLiteDatabase?) {
        Log.d("DBHelper", "onCreate")

        val sql = """
        CREATE TABLE user (
            key INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            age INTEGER NOT NULL,
            weight REAL NOT NULL,
            date DATE NOT NULL
        )
        """.trimIndent()

        db?.execSQL(sql)
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        Log.d("DBHelper", "onUpgrade - $oldVersion -> $newVersion")
    }
}
res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/writeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write" />

    <Button
        android:id="@+id/readButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="read" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
MainActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val writeButton = findViewById<Button>(R.id.writeButton)
        val readButton = findViewById<Button>(R.id.readButton)
        val textView = findViewById<TextView>(R.id.textView)

        writeButton.setOnClickListener {
            val helper = UserDBHelper(this)
            val db = helper.writableDatabase
            val sql = "INSERT INTO user (name, age, weight, date) VALUES (?, ?, ?, ?)"
            val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())

            /*
            val values = ContentValues()
            values.put("name", "john")
            values.put("age", 23)
            values.put("weight", 56.6)
            values.put("date", date)
            db.insert("user", null, values)
            */

            db.execSQL(sql, arrayOf("john", 23, 56.6, date))
            db.execSQL(sql, arrayOf("tom", 32, 57.6, date))
            db.close()

            Toast.makeText(baseContext, "저장 완료", Toast.LENGTH_SHORT).show()
        }

        readButton.setOnClickListener {
            val helper = UserDBHelper(this)
            val db = helper.writableDatabase
            val sql = "SELECT * FROM user"
            val c = db.rawQuery(sql, null)

            textView.text = ""

            while (c.moveToNext()) {
                val key = c.getInt(c.getColumnIndex("key"))
                val name = c.getString(c.getColumnIndex("name"))
                val age = c.getInt(c.getColumnIndex("age"))
                val weight = c.getDouble(c.getColumnIndex("weight"))
                val date = c.getString(c.getColumnIndex("date"))

                textView.append("key : $key\n")
                textView.append("name : $name\n")
                textView.append("age : $age\n")
                textView.append("weight : $weight\n")
                textView.append("date : $date\n")
            }

            db.close()
        }
    }
}

참고

ContentProvider

설명

  • 애플리케이션이 저장한 데이터를 다른 애플리케이션이 사용할 수 있도록 제공하는 개념

SQLite 데이터 제공 앱 코드

  • 위 SQLite 예제에 이어 아래 코드 작성
UserDBProvider
class UserDBProvider : ContentProvider() {
    override fun onCreate(): Boolean {
        return false
    }

    override fun getType(uri: Uri): String? {
        TODO("Not yet implemented")
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        val helper = UserDBHelper(context!!)
        val db = helper.writableDatabase

        return db.query("user", projection, selection, selectionArgs, null, null, sortOrder)
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        val helper = UserDBHelper(context!!)
        val db = helper.writableDatabase

        db.insert("user", null, values)

        return uri
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        val helper = UserDBHelper(context!!)
        val db = helper.writableDatabase

        return db.update("user", values, selection, selectionArgs)
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        val helper = UserDBHelper(context!!)
        val db = helper.writableDatabase

        return db.delete("user", selection, selectionArgs)
    }
}
manifests/AndroidManifest.xml
  • provider 등록 필요
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android_example">

    <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/Theme.Androidexample">

        <provider
            android:name=".UserDBProvider"
            android:authorities="com.example.android_example.UserDBProvider"
            android:enabled="true"
            android:exported="true" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <!-- Entry Point -->
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

SQLite 데이터 사용 앱 코드

res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/updateButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="update" />

    <Button
        android:id="@+id/writeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="write" />

    <Button
        android:id="@+id/readButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="read" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
MainActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val updateButton = findViewById<Button>(R.id.updateButton)
        val writeButton = findViewById<Button>(R.id.writeButton)
        val readButton = findViewById<Button>(R.id.readButton)
        val textView = findViewById<TextView>(R.id.textView)

        updateButton.setOnClickListener {
            val uri = Uri.parse("content://com.example.android_example.UserDBProvider")
            val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
            val values = ContentValues()
            values.put("name", "john2")
            values.put("age", 26)
            values.put("weight", 56.6)
            values.put("date", date)
            contentResolver.update(uri, values, "key = ?", arrayOf("1"))
        }

        writeButton.setOnClickListener {
            val uri = Uri.parse("content://com.example.android_example.UserDBProvider")
            val date = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
            val values = ContentValues()
            values.put("name", "john")
            values.put("age", 23)
            values.put("weight", 56.6)
            values.put("date", date)
            contentResolver.insert(uri, values)
        }

        readButton.setOnClickListener {
            val uri = Uri.parse("content://com.example.android_example.UserDBProvider")
            val c = contentResolver.query(uri, null, null, null, null)

            if (c != null) {
                textView.text = ""

                while (c.moveToNext()) {
                    val key = c.getInt(c.getColumnIndex("key"))
                    val name = c.getString(c.getColumnIndex("name"))
                    val age = c.getInt(c.getColumnIndex("age"))
                    val weight = c.getDouble(c.getColumnIndex("weight"))
                    val date = c.getString(c.getColumnIndex("date"))

                    textView.append("key : $key\n")
                    textView.append("name : $name\n")
                    textView.append("age : $age\n")
                    textView.append("weight : $weight\n")
                    textView.append("date : $date\n")
                }
            }
        }
    }
}

참고

반응형

'Development > Android' 카테고리의 다른 글

[Android] MediaPlayer  (0) 2021.02.09
[Android] Resources  (0) 2021.02.09
[Android] Service  (0) 2021.02.09
[Android] BroadcastReceiver  (0) 2021.02.09
[Android] Thread & Handler  (0) 2021.02.09

+ Recent posts