문서를 통해 Room의 활용법을 익히고 프로젝트에 적용해보기
자세한 내용은
https://developer.android.com/training/data-storage/room?hl=ko
참고
@Entity(tableName = "memories")
data class Memory(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "memory_id") val id: Int = 0,
@ColumnInfo(name = "memory_date") val date: String,
@ColumnInfo(name = "memory_who") val who: String,
@ColumnInfo(name = "memory_latitude") val latitude: Double,
@ColumnInfo(name = "memory_longitude") val longitude: Double,
@ColumnInfo(name = "memory_location") val location: String,
@ColumnInfo(name = "memory_picture", typeAffinity = ColumnInfo.BLOB) val picture: ByteArray?,
@ColumnInfo(name = "memory_content") val content: String?
)
@Dao
interface MemoryDao {
@Insert
fun insertMemory(vararg memory: Memory)
@Update
fun updateMemory(memory: Memory)
@Delete
fun deleteMemory(memory: Memory)
//선택한 날짜 안에 있는 모든 메모리 데이터 가져오기
@Query("SELECT * FROM memories WHERE memory_date BETWEEN (:firstDate) AND (:lastDate)")
fun loadMemoryForDate(firstDate : String, lastDate : String):List<Memory>
//선택한 지역에 해당하는 모든 메모리 데이터 가져오기
@Query("SELECT * FROM memories WHERE memory_location IN (:location)")
fun loadMemoryBasedOnLocation(location : String) : List<Memory>
//전체 사진 목록 받아오기
@Query("SELECT memory_picture FROM memories")
fun getAllPicture():List<ByteArray>
//전체 메모리 데이터 가져오기
@Query("SELECT * FROM memories")
fun getAllMemories():List<Memory>
//선택한 메모리 데이터 가져오기
@Query("SELECT * FROM memories WHERE memory_id = (:memoryId) LIMIT 1")
fun getCheckedMemory(memoryId : Int) : Memory
}
private lateinit var db : MemoryDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_database_test)
db = Room.databaseBuilder(this, MemoryDatabase::class.java,"memory.db").allowMainThreadQueries().build()
}
override fun onClick(v: View?) {
when(v!!.id){
R.id.btn_insert -> {
Log.d("11111","성공")
db.memoryDao().insertMemory(
Memory(
date = edit_date.text.toString(),
who = edit_who.text.toString(),
latitude = edit_latitude.text.toString().toDouble(),
longitude = edit_longitude.text.toString().toDouble(),
location = edit_location.text.toString(),
picture = null,
content = null
)
)
textView.text = db.memoryDao().getAllMemories().joinToString()
}
R.id.btn_update -> {
db.memoryDao().updateMemory(
Memory(
date = edit_date.text.toString(),
who = edit_who.text.toString(),
latitude = edit_latitude.text.toString().toDouble(),
longitude = edit_longitude.text.toString().toDouble(),
location = edit_location.text.toString(),
picture = null,
content = null
)
)
textView.text = db.memoryDao().getAllMemories().joinToString()
}
R.id.btn_delete -> {
db.memoryDao().deleteMemory(
Memory(
date = edit_date.text.toString(),
who = edit_who.text.toString(),
latitude = edit_latitude.text.toString().toDouble(),
longitude = edit_longitude.text.toString().toDouble(),
location = edit_location.text.toString(),
picture = null,
content = null
)
)
textView.text = db.memoryDao().getAllMemories().joinToString()
}
}
}
}