안드로이드의 데이터를 영구적으로 저장하는 방법은 크게 3가지가 있다.
1. SharedPreferences
2. 데이터베이스로 저장
3. 파일 형태로 저장
데이터를 영구적으로 저장한다는 것은 앱 내에서 데이터를 사용하고 앱을 종료하거나 폰을 껐다 켜도 날아가는 게 아니라 어딘가에 비휘발성으로 저장돼 있는 것을 말한다.
오늘은 이 3가지 방법 중 SharedPreferences를 공부하려고 한다.
Preference는 크게 2가지이다.
1. getSharedPreferences로 여러 개의 Shared Preference파일들을 사용
2. getPreferences로 한개의 Shared Preference 파일을 사용
하지만 한 개를 저장할 일은 거의 없고 여러 개를 사용할 것이기 때문에 보통 getSharedPreferences를 사용한다.
getSharedPreferences
(인자로 name과 mode 2가지를 넘김)여러개의 Shared Preference파일들을 사용하는 경우
name : 프레퍼런스 데이터를 저장할 XML 파일의 이름이다.
mode : 파일의 공유 모드
- MODE_PRIVATE: 생성된 XML 파일은 호출한 애플리케이션 내에서만 읽기 쓰기가 가능
- MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE은 보안상 이유로 API level 17에서 deprecated됨
val sharedPref = activity?.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE)
사용 가능한 데이터 타입
SharedPreferences 클래스
XML 포맷의 텍스트 파일에 키-값 세트로 정보를 저장.
프로그램의 설정 정보 (사용자의 옵션 선택 사항 이나 프로그램의 구성 정보)를 영구적으로 저장하는 용도로 사용
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE)
EditText 를 만들어 text 입력 후, 저장 버튼을 누르면 입력한 text를 저장하고,앱을 다시 열면 저장된 text가 그대로 유지될 수 있도록 해보자.
(SharedPreferences 를 쓰지 않는 일반적인 경우, text가 저장되지 않아 사라진다)
<?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:textColor="#000000"
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="32dp"
android:text="저장하기"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_hello" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.gahyeon.sharedpreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.gahyeon.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) // pref라는 파일 name으로 Preference 생성
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번째 인자는 데이터가 존재하지 않을 경우의 값(불러올 때는 defaultvalue를 지정해줘야 한다.)
binding.etHello.setText(pref.getString("name", ""))
}
}