안드로이드를 사용하다 보면 데이터를 저장해서 사용해야 할 때가 있다.
서버를 통해서 DB에 저장을 할 수도 있지만 간단하고 크지 않은 데이터는 안드로이드 내부에 있는 DB를 사용해서 저장하는 게 더 좋다고 생각한다.
그중에서 저번에는 제트팩의 room 을 사용해 봤고
이번에는 안드로이드 자체에서 제공하는 sharedPreferences를 정리해보려고 한다.
1. SharedPreferences란?
https://developer.android.com/reference/android/content/SharedPreferences
SharedPreferences | Android Developers
developer.android.com
안드로이드 공식문서에서는 다음과 같이 설명해 준다.
공식문서 해석
Interface for accessing and modifying preference data returned by Context.getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. Objects that are returned from the various get methods must be treated as immutable by the application.
대충 해석을 해보면,
context.getSharedPreferences에서 반환한 기본 preference 데이터에 접근하고 수정하기 위한 인터페이스라고 보면 된다.
특정 preference의 집합에 대해 모든 클라이언트가 공유하는 단일 인스턴스가 있고
프리퍼런스의 수정은 에디터를 통해서 하고
다양한 메서드에서 반환된 객체는 불변으로 처리된다고 한다.
데이터의 양이 많거나 중요 데이터의 경우 서버나 DB에 저장해야겠지만, 간단한 설정 값이나 문자열 같은 데이터를 저장하기 위해 DB를 사용하는 것은 부담스럽기 때문에 SharedPreferences를 사용하는 것이 적합하다.
2. 특징
- SharedPreferences는 데이터를 파일로 저장하는데, 이 파일은 앱 폴더 내에 저장되기 때문에 앱을 삭제하면 당연하게도 데이터 파일도 삭제가 된다.
파일 경로 : data/data/(package_name)/shared_prefs/SharedPreference
- key - value 형식
- 보통 초기 설정값이나 자동로그인 여부 등 간단한 값을 저장하기 위해 사용
3. 사용법
//객체 선언
val shared = getSharedPreferences("shared",0)
// 데이터 불러오기
shared.getString("key",defValue)
shared.getInt("key",defValue)
//이외에도 다양한 get메서드들이 존재
//데이터 저장
val edit = shared.edit()
edit.putString("key","value")
edit.putInt("key",value)
edit.apply()
4. 예제
이름하고 핸드폰번호를 edittext로 입력받고
저장버튼을 누르면 sharedPreferences에 데이터를 저장해 놓고
불러오기 버튼을 누르면 sharedPreferneces 안에 저장된 데이터를 textView에 띄워주는 아주 간단한 예제를 만들어 보겠습니다.
1. xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="90dp"
android:layout_marginTop="175dp"
android:layout_marginEnd="111dp"
android:ems="10"
android:inputType="text"
android:hint="Name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:ems="10"
android:hint="폰번호"
android:inputType="phone"
app:layout_constraintEnd_toEndOf="@+id/editTextName"
app:layout_constraintStart_toStartOf="@+id/editTextName"
app:layout_constraintTop_toBottomOf="@+id/editTextName" />
<TextView
android:id="@+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="109dp"
android:text="이름"
android:textSize="40sp"
app:layout_constraintEnd_toEndOf="@+id/editTextPhone"
app:layout_constraintStart_toStartOf="@+id/editTextPhone"
app:layout_constraintTop_toBottomOf="@+id/editTextPhone" />
<TextView
android:id="@+id/textViewPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="27dp"
android:text="폰번호"
android:textSize="40sp"
app:layout_constraintEnd_toEndOf="@+id/textViewName"
app:layout_constraintStart_toStartOf="@+id/textViewName"
app:layout_constraintTop_toBottomOf="@+id/textViewName" />
<Button
android:id="@+id/buttonSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="저장"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="@+id/textViewPhone"
app:layout_constraintStart_toStartOf="@+id/textViewPhone"
app:layout_constraintTop_toBottomOf="@+id/textViewPhone" />
<Button
android:id="@+id/buttonLoad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:text="불러오기"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="@+id/textViewPhone"
app:layout_constraintHorizontal_bias="0.306"
app:layout_constraintStart_toStartOf="@+id/textViewPhone" />
</androidx.constraintlayout.widget.ConstraintLayout>
2. MainActivity
간단하게 뷰바인딩을 사용했습니다.
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//뷰바인딩
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.buttonSave.setOnClickListener {
saveButton(binding)
}
binding.buttonLoad.setOnClickListener {
loadButton(binding)
}
}
private fun saveButton(binding:ActivityMainBinding){
//쉐어드 저장
val shared = getSharedPreferences("shared",0)
val edit = shared.edit()
edit.putString("name",binding.editTextName.text.toString())
edit.putInt("phone",binding.editTextPhone.text.toString().toInt())
edit.apply()
//에딧텍스트 빈칸처리
binding.editTextName.setText("")
binding.editTextPhone.setText("")
}
private fun loadButton(binding: ActivityMainBinding){
//쉐어드 로드
val shared = getSharedPreferences("shared",0)
binding.textViewName.text = shared.getString("name","")
//핸드폰 번호 저장시 정수형이기 때문에 맨 앞에 0 추가
binding.textViewPhone.text = "0${shared.getInt("phone",0).toString()}"
}
}
3. 결과
같이 보면 좋은 글
https://github.com/eukkbro/shared
GitHub - eukkbro/shared
Contribute to eukkbro/shared development by creating an account on GitHub.
github.com
2024.04.25 - [안드로이드] - [Android] AAC Room 사용해보기
[Android] AAC Room 사용해보기
클라이언트 내부 데이터베이스를 사용해서 여러 가지 기능들을 수행할 수 있습니다.대표적으로 SharedPreference와 roomDB를 이야기할 수 있는데 이 중에서 안드로이드 제트팩의 구성요소이자 AAC 중
goharry.tistory.com
끝!
'안드로이드' 카테고리의 다른 글
[Android] MVC 패턴 예제! (0) | 2024.05.04 |
---|---|
[Android] 디자인 패턴 이해 (MVC/MVP/MVVM) (0) | 2024.04.30 |
[Android] AAC Room 사용해보기 (0) | 2024.04.25 |
[SCRCPY] 안드로이드 기기 USB, WIFI를 통한 미러링 , 다중 미러링 (1) | 2024.04.03 |
[Android] 노란 경고 무시하지 말자 2 - Hardcoded string "텍스트", should use @string resource (0) | 2024.03.30 |