[Android]Kotlin Android whit SQL(코틀린 안드로이드 SQL연동)

2019. 4. 16. 18:56Programming/Android

[시험관속 안드로이드] Kotlin Android whit SQL

앞서 말하지만 시험관속 안드로이드는 튜토리얼이 아닙니다.

이해를 돕고자 설명을 하고 하지 않겠습니다.

특정 발생할 수 있는 버그나 오류에 대하여서만 설명을 하고 그렇지 않다면 코드뷰만을 하도록 하겠습니다.

 

Kotlin Android 개발하다 보면 발생하는 그것 어떻게 하지?

Kotlin 좋다 이거야 그러면 어떻게 쓰지?

그러한 개발자들을 위해서 샘플로 코드를 보여드리기 위해서 작성된 글입다.

샘플코드를 가지고 가셔서 잘 이용만 하신다면 간단한 프로잭트를 완성 할 수 있다는것만 명심하세요~~찡긋

 

kotlin sql이거 한번 써보도록 하죠, 코틀린 안드로이드 SQL연동

 

*코드를 보시고 판단할 수 있는 분들을 위하여 작성된 글입니다.


Project Tree

개발하며 작성하여 사용된 파일들만을 열어둔 사진입니다.

이외의 다른 어떠한 것도 건드리지 않았습니다.


Layout

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="25dp"
        android:textStyle="bold"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <EditText
        android:id="@+id/edt_id"
        android:hint="ID"
        android:inputType="number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/edt_name"
        android:hint="Name"
        android:inputType="text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/edt_email"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="3"
        android:orientation="horizontal">
        
        <Button
            android:id="@+id/btn_add"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Add"/>
        <Button
            android:id="@+id/btn_up"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="UPDATE"/>
        <Button
            android:id="@+id/btn_del"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="DELETE"/>


    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:choiceMode="singleChoice"></ListView>

</LinearLayout>

Main layout.xml 

보시고 판단하여 사용하여주세요

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/row_id"
        android:text="0"
        android:textStyle="bold"
        android:textSize="40dp"
        android:layout_marginLeft="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/row_name"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="name"/>
        <TextView
            android:id="@+id/row_email"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:text="email@gmail.com"/>
    </LinearLayout>
</LinearLayout>

lowlayout.xml 

보시고 참고해서 사용해 주세요.

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.example.samsung.myapplication.Adapter.ListPersonAdapter
import com.example.samsung.myapplication.DBHelper.DBHelper
import com.example.samsung.myapplication.Model.Person
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    internal lateinit var db:DBHelper
    internal var lstPersons:List<Person> = ArrayList<Person>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        db = DBHelper(this)

        refreshData()

        //Event
        btn_add.setOnClickListener {
            val person = Person(
                    Integer.parseInt(edt_id.text.toString()),edt_name.text.toString(),edt_email.text.toString()
            )
            db.addPerson(person)
            refreshData()
        }

        btn_up.setOnClickListener {
            val person = Person(
                    Integer.parseInt(edt_id.text.toString()),edt_name.text.toString(),edt_email.text.toString()
            )
            db.updatePerson(person)
            refreshData()
        }

        btn_del.setOnClickListener {
            val person = Person(
                    Integer.parseInt(edt_id.text.toString()),edt_name.text.toString(),edt_email.text.toString()
            )
            db.deletePerson(person)
            refreshData()

        }
    }

    private fun refreshData() {
       lstPersons = db.allPerson
        val adapter = ListPersonAdapter(this@MainActivity,lstPersons,edt_id, edt_name, edt_email)
        list.adapter = adapter
    }
}

Main
package com.example.samsung.myapplication.Model

class Person {
    var id:Int=0
    var name:String?=null
    var email:String?=null

    constructor(){}

    constructor(id:Int, name:String, email:String){
        this.id=id
        this.name=name
        this.email=email
    }

}

Person

package com.example.samsung.myapplication.DBHelper

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import com.example.samsung.myapplication.Model.Person

class DBHelper (context: Context) :SQLiteOpenHelper(context,DATABASE_NAME, null, DATABADE_VER){

    companion object {
        private val DATABADE_VER = 1
        private  val DATABASE_NAME = "SAMPLEKOTLIN.db"

        //Table
        private val TABLE_NAME = "Person"
        private val COOL_ID = "Id"
        private val COOL_NAME = "Name"
        private val COLL_EMAIL = "Email"

    }

    override fun onCreate(db: SQLiteDatabase?) {
        val CREATE_TABLE_QUERY = ("CREATE TABLE $TABLE_NAME ($COOL_ID INTEGER PRIMARY KEY,$COOL_NAME TEXT,$COLL_EMAIL TEXT)")
        db!!.execSQL(CREATE_TABLE_QUERY);
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        db!!.execSQL("DROP TABLE IF EXISTS $TABLE_NAME")
        onCreate(db!!)
    }

    //CRUD
    val allPerson:List<Person>
            get(){
                val lstPersons = ArrayList<Person>()
                val selectQueryHandler =  "SELECT * FROM $TABLE_NAME"
                val db = this.writableDatabase
                val cursor = db.rawQuery(selectQueryHandler,null)
                if (cursor.moveToFirst())
                {
                    do {
                        val person = Person()
                        person.id = cursor.getInt(cursor.getColumnIndex(COOL_ID))
                        person.name = cursor.getString(cursor.getColumnIndex(COOL_NAME))
                        person.email = cursor.getString(cursor.getColumnIndex(COLL_EMAIL))

                        lstPersons.add(person)
                    }while (cursor.moveToNext())

                }
                db.close()
                return lstPersons

            }

    fun addPerson(person: Person)
    {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(COOL_ID, person.id)
        values.put(COOL_NAME, person.name)
        values.put(COLL_EMAIL, person.email)

        db.insert(TABLE_NAME,null,values)
        db.close()
    }

    fun updatePerson(person: Person):Int
    {
        val db = this.writableDatabase
        val values = ContentValues()
        values.put(COOL_ID, person.id)
        values.put(COOL_NAME, person.name)
        values.put(COLL_EMAIL, person.email)

        return db.update(TABLE_NAME,values,"$COOL_ID=?", arrayOf(person.id.toString()))

    }

    fun deletePerson(person: Person)
    {
        val db = this.writableDatabase


        db.delete(TABLE_NAME, "$COOL_ID=?", arrayOf(person.id.toString()))
        db.close()

    }




}

DBHelper

package com.example.samsung.myapplication.Adapter

import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.EditText
import com.example.samsung.myapplication.MainActivity
import com.example.samsung.myapplication.Model.Person
import com.example.samsung.myapplication.R
import kotlinx.android.synthetic.main.low_layout.view.*

class ListPersonAdapter (internal val activity:Activity,
                         internal val lstPerson: List<Person>,
                         internal val edt_id:EditText,
                         internal val edt_name:EditText,
                         internal val edt_email:EditText):BaseAdapter() {

    internal var inflater:LayoutInflater

    init {
        inflater = activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
      val rowView:View
        rowView = inflater.inflate(R.layout.low_layout,null)

        rowView.row_id.text = lstPerson[position].id.toString()
        rowView.row_name.text = lstPerson[position].name.toString()
        rowView.row_email.text = lstPerson[position].email.toString()

        //Event
        rowView.setOnClickListener{
            edt_id.setText(rowView.row_id.text.toString())
            edt_name.setText(rowView.row_name.text.toString())
            edt_email.setText(rowView.row_email.text.toString())
        }
        return rowView
    }

    override fun getItem(position: Int): Any {
        return lstPerson[position]
    }

    override fun getItemId(position: Int): Long {
        return lstPerson[position].id.toLong()
    }

    override fun getCount(): Int {
        return lstPerson.size
    }
}

ListPersonAdapter

이렇게 구동되는 영상까지.

반응형