Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

정렬 기능 추가 #59

Open
wants to merge 3 commits into
base: CJE
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions app/src/main/java/com/gdsc/todo/model/ToDoRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ import com.gdsc.todo.model.entity.MyToDoList
class ToDoRepository(application: Application) {

// lazy? application?
private val toDoDao: ToDoDao by lazy{
private val toDoDao: ToDoDao by lazy {
val db = ToDoDatabase.getInstance(application)!!
db.getToDoDao()
}

private val myToDoSet: List<MyToDoList> = toDoDao.getAll()


fun getAllToDo(): List<MyToDoList>{
fun getAllToDo(): List<MyToDoList> {
return myToDoSet
}

fun insert(newToDo: MyToDoList){
fun insert(newToDo: MyToDoList) {
toDoDao.insert(newToDo)
}

fun delete(toDo: MyToDoList){
fun delete(toDo: MyToDoList) {
toDoDao.delete(toDo)
}
}
8 changes: 4 additions & 4 deletions app/src/main/java/com/gdsc/todo/model/db/ToDoDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import com.gdsc.todo.model.dao.ToDoDao
// 반드시 RoomDatabase를 상속받은 추상클래스를 만들어야 한다.
// 추상 클래스로 만든 인스턴스는 주로 싱글톤으로 만든다.
// 같은 시간에 여러 개의 인스턴스에서 데이터베이스에 접근하는 것을 막기 위함이다.
@Database(entities = [MyToDoList::class], version = 6)
abstract class ToDoDatabase: RoomDatabase() {
@Database(entities = [MyToDoList::class], version = 9)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앱을 재실행하지 못하고 재설치를 해야되는 에러가 생기지는 않았나요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

룸 마이그레이션
SQL문을 거쳐서 마이그레이션하는 방식도 있습니다.

abstract class ToDoDatabase : RoomDatabase() {
abstract fun getToDoDao(): ToDoDao

// 데이터베이스 객체를 인스턴스 할 때 싱글톤으로 구현
Expand All @@ -23,8 +23,8 @@ abstract class ToDoDatabase: RoomDatabase() {
// 데이터베이스 객체를 반환
@Synchronized
fun getInstance(context: Context): ToDoDatabase? {
if(instance == null){
synchronized(ToDoDatabase::class){
if (instance == null) {
synchronized(ToDoDatabase::class) {
instance = Room.databaseBuilder(
context.applicationContext,
ToDoDatabase::class.java,
Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/com/gdsc/todo/model/entity/MyToDoList.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import androidx.room.PrimaryKey
@Entity
data class MyToDoList(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
@ColumnInfo(name="title") val title: String,
@ColumnInfo(name="content") val content: String
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "content") val content: String,
@ColumnInfo(name = "date") val date: String
)
15 changes: 10 additions & 5 deletions app/src/main/java/com/gdsc/todo/ui/AddToDo/AddToDoActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,12 @@ class AddToDoActivity : AppCompatActivity() {
binding = DataBindingUtil.setContentView(this, R.layout.activity_add_to_do)
setContentView(binding.root)

viewModel = ViewModelProvider(this , ViewModelProvider.AndroidViewModelFactory(getApplication())).get(
ToDoViewModel::class.java)
viewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(getApplication())
).get(
ToDoViewModel::class.java
)
binding.addToDoViewModel = viewModel

// 뒤로가기 버튼 생성
Expand All @@ -44,7 +48,7 @@ class AddToDoActivity : AppCompatActivity() {
// 툴바의 뒤로가기 버튼 이벤트
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
when(id){
when (id) {
android.R.id.home -> {
startToDoActivity()
return true
Expand All @@ -68,11 +72,12 @@ class AddToDoActivity : AppCompatActivity() {
finish()
}

private fun addAfterCheck()= when(viewModel.checkEmpty()){
private fun addAfterCheck() = when (viewModel.checkEmpty()) {
true -> {
viewModel.addButtonClick()
startToDoActivity()
} else -> {
}
else -> {
showEmptyToDoError()
}
}
Expand Down
78 changes: 72 additions & 6 deletions app/src/main/java/com/gdsc/todo/ui/ToDo/ToDoActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,45 @@ package com.gdsc.todo.ui.ToDo
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast
import android.widget.Toolbar
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.gdsc.todo.R
import com.gdsc.todo.ui.ToDoViewModel
import com.gdsc.todo.databinding.ActivityToDoBinding
import com.gdsc.todo.model.db.ToDoDatabase
import com.gdsc.todo.model.entity.MyToDoList
import com.gdsc.todo.ui.AddToDo.AddToDoActivity

const val TAG2 = "ToDoActivity"
const val ISSORTED = "isSorted"

class ToDoActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var toDoAdapter: ToDoAdapter
private lateinit var viewModel: ToDoViewModel
private var titleIsSorted: Boolean = false
private var dateIsSorted: Boolean = false

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityToDoBinding.inflate(layoutInflater)
setContentView(binding.root)

recyclerView = binding.todoRecyclerView
viewModel = ViewModelProvider(this , ViewModelProvider.AndroidViewModelFactory(getApplication())).get(
ToDoViewModel::class.java)
setSupportActionBar(binding.todoToolbar)

viewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory(getApplication())
).get(
ToDoViewModel::class.java
)
setRecyclerView()

binding.mainAddButton.setOnClickListener {
Expand All @@ -34,7 +50,10 @@ class ToDoActivity : AppCompatActivity() {
}

fun setRecyclerView() {
toDoAdapter = ToDoAdapter(viewModel.myToDoSet, viewModel)
when (titleIsSorted || dateIsSorted) {
true -> toDoAdapter = ToDoAdapter(viewModel.sortMyToDoSet, viewModel)
false -> toDoAdapter = ToDoAdapter(viewModel.myToDoSet, viewModel)
}
toDoAdapter.notifyDataSetChanged()
recyclerView.apply {
adapter = toDoAdapter
Expand All @@ -48,22 +67,69 @@ class ToDoActivity : AppCompatActivity() {

override fun onRestart() {
super.onRestart()
viewModel.getAll()
setRecyclerView()

}

override fun onDestroy() {
super.onDestroy()
ToDoDatabase.destroyInstance()
}

private fun startAddToDoActivity(){
private fun startAddToDoActivity() {
val intent = Intent(this, AddToDoActivity::class.java)
startActivity(intent)
finish()
}

private fun checkEvent(toDo: MyToDoList){
private fun checkEvent(toDo: MyToDoList) {
viewModel.deleteToDo(toDo)
}

// toolbar에 menu.xml 추가
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu, menu)
return true
}

// toolbar에 추가된 항목 클릭 시 이벤트 처리
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.sort_title -> checkTitleSorted()
R.id.sort_date -> checkDateSorted()
}
return super.onOptionsItemSelected(item)
}

private fun checkTitleSorted() {
when (titleIsSorted) {
true -> {
Log.d(ISSORTED, titleIsSorted.toString())
titleIsSorted = false
setRecyclerView()
}
false -> {
Log.d(ISSORTED, titleIsSorted.toString())
viewModel.sortTitle()
titleIsSorted = true
dateIsSorted = false
setRecyclerView()
}
}
}

private fun checkDateSorted() {
when (dateIsSorted) {
true -> {
dateIsSorted = false
setRecyclerView()
}
false -> {
viewModel.sortDate()
dateIsSorted = true
titleIsSorted = false
setRecyclerView()
}
}
}
}
22 changes: 13 additions & 9 deletions app/src/main/java/com/gdsc/todo/ui/ToDo/ToDoAdapter.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,33 +13,37 @@ const val TAG = "ToDoAdapter"
class ToDoAdapter(
private val myToDoSet: List<MyToDoList>,
private val viewModel: ToDoViewModel
): RecyclerView.Adapter<ToDoAdapter.ToDoViewHolder>() {
class ToDoViewHolder(val binding: ItemTodoBinding): RecyclerView.ViewHolder(binding.root){
) : RecyclerView.Adapter<ToDoAdapter.ToDoViewHolder>() {
class ToDoViewHolder(val binding: ItemTodoBinding) : RecyclerView.ViewHolder(binding.root) {

// 체크박스 클릭 시 데이터 삭제
fun checking(toDo: MyToDoList, viewModel: ToDoViewModel){
fun checking(toDo: MyToDoList, viewModel: ToDoViewModel) {
binding.checked.setOnCheckedChangeListener { _, _ ->
Log.d(TAG, binding.checked.isChecked.toString())
if(binding.checked.isChecked){
Thread{
if (binding.checked.isChecked) {
Thread {
viewModel.deleteToDo(toDo)
}.start()
}
}
}
}

override fun getItemCount(): Int{
override fun getItemCount(): Int {
Log.d("size", myToDoSet.size.toString())
if(myToDoSet.isNotEmpty()){
if (myToDoSet.isNotEmpty()) {
return myToDoSet.size
}
return 0
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ToDoViewHolder =
ToDoViewHolder(ItemTodoBinding.inflate(LayoutInflater.from(parent.context),
parent, false))
ToDoViewHolder(
ItemTodoBinding.inflate(
LayoutInflater.from(parent.context),
parent, false
)
)

override fun onBindViewHolder(holder: ToDoViewHolder, position: Int) {
holder.binding.item = myToDoSet[position]
Expand Down
36 changes: 25 additions & 11 deletions app/src/main/java/com/gdsc/todo/ui/ToDoViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,46 +10,60 @@ import com.gdsc.todo.model.entity.MyToDoList
class ToDoViewModel(application: Application) : AndroidViewModel(application) {

private var _myToDoSet = ArrayList<MyToDoList>()
private var _sortMyToDoSet = ArrayList<MyToDoList>()

val myToDoSet: List<MyToDoList>
get() = _myToDoSet
val sortMyToDoSet: List<MyToDoList>
get() = _sortMyToDoSet
var title = ""
var content = ""
var date = ""

private val repository: ToDoRepository by lazy{
private val repository: ToDoRepository by lazy {
ToDoRepository(application)
}

init {
Log.d(TAG, "init")
getAll()
// _sortMyToDoSet = _myToDoSet 얕은 복사(기존 객체에 영향 O)
_sortMyToDoSet.addAll(_myToDoSet) // 깊은 복사(기존 객체에 영향 X)
Comment on lines +30 to +31
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

삽질하기 좋은 개념인데 잘 이해가 되셨길ㅎㅎ

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cloneable

}

fun getAll(){
Thread{
fun getAll() {
Thread {
_myToDoSet = repository.getAllToDo() as ArrayList<MyToDoList>
}.start()
Thread.sleep(TIME)
}

fun addButtonClick(){
Thread{
val newToDo = MyToDoList(title = title.toString(), content = content.toString())
fun addButtonClick() {
Thread {
val newToDo = MyToDoList(title = title, content = content, date = "~" + date)
repository.insert(newToDo)
}.start()
Thread.sleep(TIME) // 있어야 제목이 저장됨(왜?)
}

fun deleteToDo(toDo: MyToDoList){
Thread{
fun deleteToDo(toDo: MyToDoList) {
Thread {
repository.delete(toDo)
}.start()
}

fun checkEmpty() = title!="" && content!=""
fun checkEmpty() = title != "" && content != ""

companion object{
fun sortTitle() {
_sortMyToDoSet.sortBy { it.title }
}

fun sortDate() {
_sortMyToDoSet.sortBy { it.date }
}

companion object {
const val TAG = "ToDoViewModel"
const val TIME: Long = 1000
const val TIME: Long = 500
}
}
5 changes: 5 additions & 0 deletions app/src/main/res/drawable/sort.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M3,18h6v-2L3,16v2zM3,6v2h18L21,6L3,6zM3,13h12v-2L3,11v2z"/>
</vector>
5 changes: 5 additions & 0 deletions app/src/main/res/drawable/sort_date.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M9,11L7,11v2h2v-2zM13,11h-2v2h2v-2zM17,11h-2v2h2v-2zM19,4h-1L18,2h-2v2L8,4L8,2L6,2v2L5,4c-1.11,0 -1.99,0.9 -1.99,2L3,20c0,1.1 0.89,2 2,2h14c1.1,0 2,-0.9 2,-2L21,6c0,-1.1 -0.9,-2 -2,-2zM19,20L5,20L5,9h14v11z"/>
</vector>
5 changes: 5 additions & 0 deletions app/src/main/res/drawable/sort_title.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<vector android:height="24dp" android:tint="#FFFFFF"
android:viewportHeight="24" android:viewportWidth="24"
android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M21,11h-1.5v-0.5h-2v3h2V13H21v1c0,0.55 -0.45,1 -1,1h-3c-0.55,0 -1,-0.45 -1,-1v-4c0,-0.55 0.45,-1 1,-1h3c0.55,0 1,0.45 1,1V11zM8,10v5H6.5v-1.5h-2V15H3v-5c0,-0.55 0.45,-1 1,-1h3C7.55,9 8,9.45 8,10zM6.5,10.5h-2V12h2V10.5zM13.5,12c0.55,0 1,0.45 1,1v1c0,0.55 -0.45,1 -1,1h-4V9h4c0.55,0 1,0.45 1,1v1C14.5,11.55 14.05,12 13.5,12zM11,10.5v0.75h2V10.5H11zM13,12.75h-2v0.75h2V12.75z"/>
</vector>
15 changes: 14 additions & 1 deletion app/src/main/res/layout/activity_add_to_do.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,23 @@
android:text="@={addToDoViewModel.title}"/>

<EditText
android:id="@+id/addTodo_content"
android:id="@+id/addTodo_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/addTodo_title"
android:layout_marginStart="13dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="13dp"
android:layout_marginBottom="13dp"
android:background="@android:color/transparent"
android:hint="Deadline(mmdd)"
android:text="@={addToDoViewModel.date}" />

<EditText
android:id="@+id/addTodo_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/addTodo_date"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"
android:background="@android:color/transparent"
Expand Down
Loading