본문으로 바로가기

SQLite을 이용한 custom database 사용하기 -2 ( Android)

category Android_app 2021. 2. 2. 14:34

1> read/write 버튼 클릭시 화면에 표시하는 기능을 추가하겠습니다.

 

UI TextView 관련 추가사항은 다음과 같습니다.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_margin="10dp"
    android:gravity="left">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/log_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </ScrollView>
</LinearLayout>

 

 

MainActivity 수정사항은 다음과 같습니다. 

>> 이해에 불필요한 코드 제거했습니다. 이해안되는 부분은 1편 참고하세요.

     leevisual.tistory.com/19

 

 

class MainActivity : AppCompatActivity() {
    private lateinit var logMsg : TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        ..... 중략

        logMsg = findViewById(R.id.log_text)

        val btnReadDb = findViewById<Button>(R.id.read_db)
        val btnWriteDb = findViewById<Button>(R.id.write_db)

        btnReadDb.setOnClickListener {
            var strName =  editName.text
            val projection = arrayOf(BaseColumns._ID,
                MyOwnDbHelper.MyContract.MyEntry.COLUMN_NAME_TITLE,
                MyOwnDbHelper.MyContract.MyEntry.COLUMN_NAME_SCORE )

            val selection = "${MyOwnDbHelper.MyContract.MyEntry.COLUMN_NAME_TITLE} = ?"

            val selectionArgs = arrayOf("${strName.toString()}")
            val cursor = readEngDb.query(
                MyOwnDbHelper.MyContract.MyEntry.TABLE_NAME,   // The table to query
                projection,             // The array of columns to return (pass null to get all)
                selection,              // The columns for the WHERE clause
                selectionArgs,          // The values for the WHERE clause
                null,                   // don't group the rows
                null,                   // don't filter by row groups
                null               // The sort order
            )

            with(cursor) {
                if(cursor.count > 0) {
                    while (moveToNext()) {
                        val score = getInt(getColumnIndexOrThrow(MyOwnDbHelper.MyContract.MyEntry.COLUMN_NAME_SCORE))
                        editScore.setText(score.toString())
                        logMsg.append("Select query " + strName.toString() + " " + score.toString() + "\n")
                    }
                }else {
                    logMsg.append("Select query " + strName.toString() + " is not existed. \n")
                }
            }
        }

        btnWriteDb.setOnClickListener {
            var name =  editName.text
            val score = editScore.text

            // Create a new map of values , where column names are the keys
            val values = ContentValues().apply{
                put(MyOwnDbHelper.MyContract.MyEntry.COLUMN_NAME_TITLE, name.toString())
                put(MyOwnDbHelper.MyContract.MyEntry.COLUMN_NAME_SCORE, score.toString().toInt())
            }

            // Insert the new row,  returning the primary key value of the new row
            val newRowId = writeEngDb.insert(MyOwnDbHelper.MyContract.MyEntry.TABLE_NAME, null,values)
            logMsg.append("Insert id =$newRowId " + name.toString() + " " + score.toString() + "\n")
        }

    }

}

 

 

 >> TextView 의 append() 함수만 잘 사용하면 되겠죠..

 

 2> database 안의 모든 데이터를 표시해 보겠습니다.

   >> button onClick함수만 추가하겠습니다.

 

 btnShowAll.setOnClickListener {
   logMsg.append("Show all datas in the database. \n\n")
   val cursor: Cursor = readEngDb.rawQuery("select * from " + MyOwnDbHelper.MyContract.MyEntry.TABLE_NAME + "", null)
   with(cursor){
       while (moveToNext()){
           val score = getInt(getColumnIndexOrThrow(MyContract.MyEntry.COLUMN_NAME_SCORE))
           val name = getString(getColumnIndexOrThrow(MyContract.MyEntry.COLUMN_NAME_TITLE))
           val id = getInt(getColumnIndexOrThrow(BaseColumns._ID))
           logMsg.append("id =$id , name = $name , score =$score \n")
       }
   }
   logMsg.append("\n")
 }

 

 >> rawQuery() 사용하기

 

   >> 결과는 아래와 같습니다.

 

 

3> 특정 컬럼 제거하기

 

btnDeleteColumn.setOnClickListener {
    Log.d(TAG,"onClick() for btnDeleteColumn")
    var strName =  editName.text
    val projection = arrayOf(BaseColumns._ID,
            MyContract.MyEntry.COLUMN_NAME_TITLE,
            MyContract.MyEntry.COLUMN_NAME_SCORE )

    val selection = "${MyContract.MyEntry.COLUMN_NAME_TITLE} = ?"

    val selectionArgs = arrayOf("${strName.toString()}")
    val cursor = readEngDb.query(
            MyContract.MyEntry.TABLE_NAME,   // The table to query
            projection,             // The array of columns to return (pass null to get all)
            selection,              // The columns for the WHERE clause
            selectionArgs,          // The values for the WHERE clause
            null,                   // don't group the rows
            null,                   // don't filter by row groups
            null               // The sort order
    )

    with(cursor) {
        if(cursor.count > 0) {
            while (moveToNext()) {
                val id = getInt(getColumnIndexOrThrow(BaseColumns._ID))
                Log.d(TAG, "id = $id")
                writeEngDb.delete( MyContract.MyEntry.TABLE_NAME, "_id=$id",null)
                logMsg.append("Delete column of id =$id \n")
            }
        }else {
            Log.d(TAG, "$strName is not existed.")
            logMsg.append("Failed to find " + strName.toString() +". \n")
        }
    }

}

 

 

 delete() 함수 사용하기

  >> column 제거후 id 가 일렬적이지 않으니 참고하세요.
       기존 id 1,2,3,4,5,6,7 이 있었으면 id 4 번을 삭제후 총 컬럼 id 는 1,2,3,5,6,7 이고
       컬럼추가시 id 8부터 입력 됩니다. 7번 지우고 추가시는 7번으로 들어갑니다.

 

3> 모든 컬럼 제거하기

btnDeleteAllColumns.setOnClickListener {
    writeEngDb.delete( MyContract.MyEntry.TABLE_NAME, null,null)
    logMsg.append("Delete all columns.  \n")
}

 

>> delete 문의 whereClause 에 null 을 넣어주면 모든 컬럼을 지워주네요.

     새로 컬럼 추가시 id 는 1번부터 시작합니다.

 

 

반응형