2024.01.26(금) TIL

quinones·2024년 1월 26일

리스트 sharedpreferences로 저장하기

@Parcelize
data class SelectedItem(
    val thumbnail:String,
    val siteName:String,
    val time:String,

): Parcelable{
    companion object{
        var myLikeList = mutableListOf<SelectedItem>()
    }
}

나는 이런형식으로 저장해둔 myLikeList를 저장할예정이다.

해당 데이터는 리사이클러뷰를 통해서 화면에 뿌려진 상태이다.

    private fun saveMyLikeList() {
        Log.d("KeepFragment", "Saving MyLikeList")
        val sharedPreferences = requireContext().getSharedPreferences("MyPreferences", 0)
        val editor = sharedPreferences.edit()
        // 데이터를 문자열로 변환하여 저장
        val jsonMyLikeList = Gson().toJson(SelectedItem.myLikeList)
        editor.putString(KEY_MY_LIKE_LIST, jsonMyLikeList)
        editor.apply()
    }

    private fun loadMyLikeList() {
        Log.d("KeepFragment", "Loading MyLikeList")
        val sharedPreferences = requireContext().getSharedPreferences("MyPreferences", 0)
        val jsonMyLikeList = sharedPreferences.getString(KEY_MY_LIKE_LIST, null)
        // 저장된 데이터가 있으면 해당 데이터를 객체로 변환하여 대입
        jsonMyLikeList?.let {
            val type = object : TypeToken<List<SelectedItem>>() {}.type
            SelectedItem.myLikeList = Gson().fromJson(it, type)
        }
    }

save와 load를 따로 만들어준다.
그리고 프래그먼트의 onCreateView에서 loadMyLikeList()를 불러와주고,
onPause()에서 saveMyLikeList()를 불러와줬다.
앱 재실행후에 바로 화면에 뿌려주기 위해서 onCreateView에서

loadMyLikeList()
keepAdapter = KeepAdapter(SelectedItem.myLikeList)
binding.keepRecyclerView.adapter = keepAdapter
binding.keepRecyclerView.layoutManager = GridLayoutManager(context, 2)

바로 어뎁터도 초기화시켜서 리스트형태의 데이터를 저장하고 뿌려주었다.

profile
이우진

0개의 댓글