Android Jetpack

dataStore - 2

----___<<<<< 2022. 8. 15. 05:35

// dataStore
implementation "androidx.datastore:datastore-preferences:1.0.0"

// ViewModelScope
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"

 

class MainActivity : AppCompatActivity() {

    private val TAG = MainActivity::class.java.simpleName

    lateinit var viewModel : MainViewModel
    lateinit var viewModelFactory: MainViewModelFactory

    private val customAdapter : CustomAdapter by lazy {
        CustomAdapter()
    }

    private val Context.dataStore by preferencesDataStore("data_store_ex")

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModelFactory = MainViewModelFactory(dataStore)
        viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)

        val upBtn = findViewById<Button>(R.id.ascending)
        val downBtn = findViewById<Button>(R.id.descending)

        val rv = findViewById<RecyclerView>(R.id.rv)

        upBtn.setOnClickListener {
            viewModel.ascending()
        }

        downBtn.setOnClickListener {
            viewModel.descending()
        }

        viewModel.liveTextList.observe(this, Observer {
            Log.d(TAG, it.toString())

            customAdapter.setData(it as List<DataSet>)

        })

        rv.adapter = customAdapter
        rv.layoutManager = LinearLayoutManager(this)
    }

}

 

class MainViewModel(private val dataStoreVal : DataStore<Preferences>) : ViewModel() {

    private val TAG = MainViewModel::class.java.simpleName

    private var _mutableTextList = MutableLiveData<List<DataSet>>()
    val liveTextList : LiveData<List<DataSet>>
        get() = _mutableTextList

    val ORDER_KEY = stringPreferencesKey("ORDER_SORT")

    init {
        Log.d(TAG, "init")
        initSort()
    }


    fun initSort() = viewModelScope.launch {
        dataStoreVal.edit { preferences ->
            val currentCounterValue = preferences[ORDER_KEY] ?: "null"
            sort(currentCounterValue)
        }
    }

    fun ascending() = viewModelScope.launch {

        val ascending = "ascending"

        dataStoreVal.edit { preferences ->
            preferences[ORDER_KEY] = ascending
        }

        sort(ascending)

    }

    fun descending() = viewModelScope.launch {

        val descending = "descending"

        dataStoreVal.edit { preferences ->
            preferences[ORDER_KEY] = descending
        }

        sort(descending)

    }

    fun sort(value : String){
        when(value) {
            "ascending" -> {

                Log.d(TAG, "ascending")

                _mutableTextList.value = DataSetRepo.dataSetList.sortedBy {
                    it.priority
                }

            }
            "descending" -> {

                Log.d(TAG, "descending")

                _mutableTextList.value = DataSetRepo.dataSetList.sortedBy {
                    it.priority
                }.reversed()

            }
            else -> {

            }
        }
    }

}

class MainViewModelFactory(private val dataStore : DataStore<Preferences>) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(MainViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return MainViewModel(dataStore) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

 

class CustomAdapter : RecyclerView.Adapter<CustomAdapter.ViewHolder>() {

    private val TAG = CustomAdapter::class.java.simpleName

    private var dataSetList = listOf<DataSet>()

    class ViewHolder(view : View) : RecyclerView.ViewHolder(view){

        val taskName : TextView = view.findViewById(R.id.taskName)
        val priority : TextView = view.findViewById(R.id.priority)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomAdapter.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.row_item, parent, false)

        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: CustomAdapter.ViewHolder, position: Int) {

        holder.taskName.text = dataSetList[position].taskName
        holder.priority.text = dataSetList[position].priority.toString()

//        holder.itemView.setOnClickListener {
//            Log.d(TAG, dataSetList[position].toString())
//        }
    }

    override fun getItemCount(): Int {
        return dataSetList.size
    }

    fun setData(data: List<DataSet>){
        dataSetList = data
        notifyDataSetChanged()
    }
}

 

data class DataSet (
    val taskName : String,
    val priority : Int
)

object DataSetRepo {

    val dataSetList = listOf(

        DataSet(
            "숨쉬기",
            5
        ),
        DataSet(
            "놀기",
            11
        ),
        DataSet(
            "운동하기",
            15
        ),
        DataSet(
            "잠자기",
            27
        ),

    )

}

 

 

 

 

 

 

- 참조

 

https://developer.android.com/codelabs/android-preferences-datastore?hl=ko#1 

 

Preferences Datastore를 사용하여 작업하기  |  Android Developers

이 Codelab에서는 샘플 앱을 수정하여 SharedPreferences를 대체하는 새로운 향상된 데이터 저장소 솔루션인 Jetpack Preferences Datastore를 통합합니다.

developer.android.com

 

'Android Jetpack' 카테고리의 다른 글

DataBinding - 1 (two - way binding)  (0) 2023.01.16
Simple Paging3  (0) 2022.12.24
dataStore - 1  (0) 2022.08.06
BindingAdapter + databinding  (0) 2022.08.05
ROOM TypeConverter  (0) 2022.07.23