===== 기초 지식 ===== 데이터를 쿼리하여 정렬하는 것은 관련 UI도 매우 중요하다. UI를 참조할 수 있는 샘플은 구글에서 제공하는 [[https://developer.android.com/develop/ui/compose/lists?hl=ko|목록 및 그리드]]에 대한 [[https://developer.android.com/develop/ui/compose/lists?hl=ko|스니펫 모음]]을 참고하자. 매우 잘 되어 있다. ===== DAO 예제 ===== ==== 1. Kotlin으로 데이터를 다루는 방법 ==== 위 [[https://developer.android.com/develop/ui/compose/lists?hl=ko|스니펫 모음]] 예제를 보면 kotlin으로 데이터를 어떻게 다루는지 이해하기가 쉽다. 데이터베이스가 없는 경우에 데이터를 다루는 예제이므로 일어보면 도움이 된다. class AnimatedOrderedListViewModel : ViewModel() { private val _data = listOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten") private val _displayedItems: MutableStateFlow> = MutableStateFlow(_data) val displayedItems: StateFlow> = _displayedItems fun resetOrder() { _displayedItems.value = _data.filter { it in _displayedItems.value } } fun sortAlphabetically() { _displayedItems.value = _displayedItems.value.sortedBy { it } } fun sortByLength() { _displayedItems.value = _displayedItems.value.sortedBy { it.length } } fun addItem() { // Avoid duplicate items val remainingItems = _data.filter { it !in _displayedItems.value } if (remainingItems.isNotEmpty()) _displayedItems.value += remainingItems.first() } fun removeItem() { _displayedItems.value = _displayedItems.value.dropLast(1) } } ==== 2. Room 데이터베이스에서 데이터 정렬하기 ==== 이제 데이터베이스를 이용할 경우를 살펴보도롣ㄱ 하자 === 가. DAO 만들기 ==== 그렇다면 실제 RoomDatabase를 이요할 경우 데이터를 정렬하는 샘플을 만들어 보자 일단 DAO는 이렇게 만들 수 있을 것이다. package com.dklaw.memorize.database import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Query import androidx.room.Upsert @Dao interface ScoreDAO { @Upsert suspend fun upsertScore(score : Score) @Delete suspend fun deleteScore(score : Score) @Query("SELECT * FROM SCORE") fun getAllScores() : LiveData> @Query("SELECT * FROM SCORE ORDER BY quoteTitle ASC") fun getAllScoresByTitleASC() : LiveData> @Query("SELECT * FROM SCORE ORDER BY quoteTitle DESC") fun getAllScoresByTitleDESC() : LiveData> @Query("SELECT * FROM SCORE ORDER BY createdAt ASC") fun getAllScoresByDateASC() : LiveData> @Query("SELECT * FROM SCORE ORDER BY createdAt DESC") fun getAllScoresByDateDESC() : LiveData> }