안드로이드

[안드로이드] 내부 SQLite를 사용해서 목록 만들기

2023. 5. 30. 16:06
글 목차


728x90

진행 할 목록은 다음과 같다

1. xml을 수정해서 뷰를 만듦
2. sql을 수행할 helper class를 만듦
3. 리사이클러 뷰에 들어갈 xml을 만듦
4. 리사이클러 뷰에 사용할 adapter클래스를 만듦
5. MainActivity를 작성

1. xml에서는 리사이클러뷰 하나, text plain하나, 확인버튼 하나를 만든다.

2. helper 클래스를 만든다.

package com.example.myapplication

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

data class Memo(var no: Long?, var content: String, var datetime: Long)

// SQLiteOpenHelper를 상속해서 sql을 다루는 메서드와 프로퍼티를 사용할 수 있게 함
class SqliteHelper(context: Context, name: String, version: Int): SQLiteOpenHelper(context, name, null, version) {
    override fun onCreate(db: SQLiteDatabase?) {
        val create = "create table memo (`no` integer primary key, content text, datetime integer)"
        db?.execSQL(create)
    }

    // 변경사항이 있을 떄 작동하는 함수
    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        TODO("Not yet implemented")
    }

    fun insertMemo(memo: Memo) {
        val wd = writableDatabase

        val values = ContentValues()
        values.put("content", memo.content)
        values.put("datetime", memo.datetime)

        wd.insert("memo", null, values)

        wd.close()
    }

    @SuppressLint("Range")
    fun selectMemo(): MutableList<Memo> {
        val list = mutableListOf<Memo>()
        val rd = readableDatabase
        var cursor = rd.rawQuery("select * from memo", null)

        while(cursor.moveToNext()) {
            val no = cursor.getLong(cursor.getColumnIndex("no"))
            val content = cursor.getString(cursor.getColumnIndex("content"))
            val datetime = cursor.getLong(cursor.getColumnIndex("datetime"))

            val memo = Memo(no, content, datetime)
            list.add(memo)
        }
        cursor.close()
        rd.close()

        return list
    }

    fun updateMemo(memo: Memo) {
        val wd = writableDatabase

        val values = ContentValues()
        values.put("content", memo.content)
        values.put("datetime", memo.datetime)

        wd.update("memo", values, "no = ${memo.no}", null)
        wd.close()
    }

    fun deleteMemo(memo:Memo) {
        val delete = "delete from memo where no = ${memo.no}"

        val wd = writableDatabase
        wd.execSQL(delete)

        wd.delete("memo", "no = ${memo.no}", null)

        wd.close()
    }
}

3. 리사이클러 뷰에 사용할 xml을 만든다

4. adapter 클래스를 만든다.

package com.example.myapplication

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.databinding.ItemRecyclerBinding
import java.text.SimpleDateFormat

class RecyclerAdapter: RecyclerView.Adapter<Holder>() {
    val listData = mutableListOf<Memo>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val binding = ItemRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return Holder(binding)
    }

    override fun getItemCount() = listData.size

    override fun onBindViewHolder(holder: Holder, position: Int) {
        val memo = listData.get(position)
        holder.setMemo(memo)
    }
}

class Holder(val binding: ItemRecyclerBinding) : RecyclerView.ViewHolder(binding.root) {
    fun setMemo(memo: Memo) {
        binding.textNo.text = "${memo.no}"
        binding.textContent.text = "${memo.content}"
        val sdf = SimpleDateFormat("yyyy/MM/dd hh:mm")
        binding.textDatetime.text = "${sdf.format(memo.datetime)}"
    }
}

 

5. MainAcitivity 작성

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.myapplication.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    val DB_NAME = "sqlite.sql"
    val DB_VERSION = 1
    val helper = SqliteHelper(this, DB_NAME, DB_VERSION)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        val adapter = RecyclerAdapter()

        adapter.listData.addAll(helper.selectMemo())
        binding.recyclerMemo.adapter = adapter
        binding.recyclerMemo.layoutManager = LinearLayoutManager(this)

        binding.btnSave.setOnClickListener {
            if (binding.editMemo.text.toString().isNotEmpty()) {
                val memo = Memo(null, binding.editMemo.text.toString(), System.currentTimeMillis())
                helper.insertMemo(memo)

                adapter.listData.clear()
                adapter.listData.addAll(helper.selectMemo())
                adapter.notifyDataSetChanged()
                binding.editMemo.setText("")
            }
        }
    }
}
728x90
[안드로이드] 내부 SQLite를 사용해서 목록 만들기