Preference란?
SharedPreferences는 간단한 값을 저장할 때 주로 사용한다. 초기 설정 값이나 자동 로그인 여부 등 간단한 값을 저장할 때 DB를 사용하면 복잡하기 때문에 SharedPreferences를 사용하면 적합하다.
프로그램의 설정 정보를 영구적으로 저장하는 용도로 사용.
XML 포맷의 텍스트 파일에 키와 값을 세트로 저장하는 구조.
SharedPreferences 클래스
Preferences의 데이터(key-value set)를 관리하는 클래스
응용 프로그램내의 액티비티간에 공유하며, 한쪽 액티비티에서 수정 시
다른 액티비티에서도 수정된 값을 읽을 수 있다.
응용 프로그램의 고유한 정보이므로 외부에서는 읽을 수 없다.
getSharedPreferences(name, mode)
name: preference data를 저장할 XML파일의 이름
mode: 파일의 공유 모드
MODE_PRIVATE: 생성된 XML 파일은 호출한 애플리케이션 내에서만 읽기 쓰기 가능(SharedPreferences를 쓰지 않는 일반적인 경우, text가 저장되지 않아 사라진다)
간단한 예제를 통해 사용방법을 알아보자.
activity_main.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/et_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:text="저장 하기"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_hello"/>
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.sharedpreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.sharedpreferences.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btnSave.setOnClickListener {
saveData()
Toast.makeText(this, "Data Saved.", Toast.LENGTH_SHORT).show()
}
loadData()
}
private fun saveData() {
val pref = getSharedPreferences("pref", 0)
val edit = pref.edit() // 수정 모드
// 1번째 인자는 키, 2번째 인자는 실제 담아둘 값
edit.putString("name", binding.etHello.text.toString())
edit.apply() // 저장완료
}
private fun loadData() {
val pref = getSharedPreferences("pref", 0)
// 1번째 인자는 키, 2번째 인자는 데이터가 존재하지 않을경우의 값
binding.etHello.setText(pref.getString("name", ""))
}
}
결과물
오올 이제 TIL에 gif까지 쓰시다니 세상에나!!
점점 TIL 퀄리티가 높아지는 것 같네요!!