일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
- SDLC
- 이미지찌그러짐
- 싱글톤패턴
- stateflow
- 구조패턴
- threadsafety
- NetworkCommunication
- LayeredArchitecture
- SharedFlow
- LazyInitialization
- 아키텍쳐패턴
- 시퀀스다이어그램
- 옵서버
- MVVM
- decoding
- 유스케이스다이어그램
- 클래스다이어그램
- android
- Kotlin
- ArchitecturePatterns
- 전역상태관리
- DistributedSystems
- SystemDesign
- SoftwareArchitecture
- ImageView
- 행위패턴
- scaletype
- 이미지짤림
- ClientServerArchitecture
- RxJava
- Today
- Total
Kyung_Development
Android SharedPreferences로 데이터 누적 및 카운트 관리하기 본문
안드로이드 앱을 개발할 때, 특정 데이터를 저장하고 불러오는 기능이 필요할 때가 많다. 특히 같은 데이터를 여러 번 추가하면 그 개수를 누적하는 방식으로 관리하고 싶을 때가 있다. 예를 들어, 특정 이벤트(A, B, C 등)가 몇 번 발생했는지 기록하고 싶을 때 SharedPreferences를 활용하면 간단하게 해결할 수 있다.
이번 글에서는 기존 데이터가 덮어씌워지는 문제가 발생하지 않도록 하고, 각 항목이 몇 번 저장되었는지 카운트하는 방법을 정리해본다.
1. 기존 SharedPreferences 문제점
보통 SharedPreferences에 리스트를 저장하는 방법은 다음과 같다.
fun setList(context: Context, key: String, values: ArrayList<Int>) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = prefs.edit()
val jsonArray = JSONArray()
for (value in values) {
jsonArray.put(value)
}
editor.putString(key, jsonArray.toString())
editor.apply()
}
위 방식은 새로운 리스트가 추가될 때마다 기존 데이터를 덮어쓴다. 즉, "A"를 저장하고, 다시 "A"를 저장해도 1개만 남는 문제가 있다. 만약 같은 데이터를 추가할 때마다 개수를 증가시키려면, Map 형태(키-값)로 저장하는 방식이 필요하다.
2. 키-값(Map) 형태로 데이터 저장하기
이를 해결하기 위해 각 항목이 몇 번 추가되었는지 카운트하는 SharedPreferences 관리 클래스를 만들어보자.
✅ 개념 정리
- 각 데이터(A, B, C 등)가 몇 번 추가되었는지 기록
- A가 두 번 추가되면 A=2, B가 한 번 추가되면 B=1
- 데이터를 JSON 형태(Map)로 SharedPreferences에 저장
✅ 구현 코드 (SharedPreferences 관리 클래스)
package com.example.preference_list
import android.content.Context
import android.preference.PreferenceManager
import org.json.JSONObject
object PreferenceManagerUtil {
// 저장된 데이터 불러오기 (Map 형태)
fun getDataMap(context: Context, key: String): HashMap<String, Int> {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val json = prefs.getString(key, null)
val dataMap = HashMap<String, Int>()
if (json != null) {
try {
val jsonObject = JSONObject(json)
for (item in jsonObject.keys()) {
dataMap[item] = jsonObject.getInt(item)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
return dataMap
}
// 데이터를 SharedPreferences에 저장
fun setDataMap(context: Context, key: String, dataMap: HashMap<String, Int>) {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = prefs.edit()
val jsonObject = JSONObject()
for ((item, count) in dataMap) {
jsonObject.put(item, count)
}
editor.putString(key, jsonObject.toString())
editor.apply()
}
// 데이터 추가 (기존 개수 유지하면서 증가)
fun addData(context: Context, key: String, item: String) {
val dataMap = getDataMap(context, key)
dataMap[item] = dataMap.getOrDefault(item, 0) + 1
setDataMap(context, key, dataMap)
}
}
이제 데이터를 추가하면 기존 값이 유지되면서 개수가 증가한다!
3. 사용 예제 (MainActivity에서 실행)
SharedPreferences 관리 클래스를 만들었으니, 이제 실제 앱에서 적용해보자. 버튼을 누를 때마다 특정 이벤트(A, B, C 등)가 몇 번 발생했는지 저장하고 확인할 수 있다.
package com.example.preference_list
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val dataKey = "event_count"
// 1. 특정 이벤트 추가 (A 두 번, B 한 번)
PreferenceManagerUtil.addData(this, dataKey, "A")
PreferenceManagerUtil.addData(this, dataKey, "A")
PreferenceManagerUtil.addData(this, dataKey, "B")
// 2. 저장된 데이터 확인
val dataMap = PreferenceManagerUtil.getDataMap(this, dataKey)
Log.d("PreferenceTest", "저장된 데이터 개수: $dataMap")
}
}
4. 실행 결과 확인
📌 첫 번째 실행 결과
D/PreferenceTest: 저장된 데이터 개수: {A=2, B=1}
📌 이후 실행 (새로운 데이터 추가)
만약 다시 실행하면서 addData(this, dataKey, "A")를 한 번 더 호출하면 다음과 같이 업데이트된다.
D/PreferenceTest: 저장된 데이터 개수: {A=3, B=1}
5. 마무리
이제 SharedPreferences를 활용해 데이터를 저장할 때, 기존 데이터가 덮어씌워지지 않고 개수를 누적할 수 있다. 정리하자면:
✅ 데이터를 Map(키-값) 형태로 저장
✅ 같은 항목이 여러 번 추가되면 개수를 증가
✅ 이전 데이터가 유지되면서 업데이트됨
이 방법을 활용하면 특정 이벤트가 몇 번 발생했는지 저장하거나, 버튼 클릭 횟수를 기록하는 기능을 쉽게 구현할 수 있다. 앞으로도 프로젝트에서 SharedPreferences를 더 효율적으로 활용해보자! 🚀
'android > Kotlin' 카테고리의 다른 글
WorkManager 상태 확인 (0) | 2025.01.21 |
---|---|
kotlin 문자열 처리 종류별, .last() (0) | 2025.01.16 |
Kotlin 컬렉션 완벽 가이드: List, 반복 (2) | 2024.11.21 |