ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] SharedPreferences
    카테고리 없음 2024. 5. 1. 14:20

    사용 이유

    로컬에서만 사용할 데이터이거나 간단한 데이터의 경우 SharedPreferences를 사용하여 저장한다.

    저장 방식은 xml이며 key-value 쌍으로 저장된다.


    사용법

    기본적으로 Context 클래스에 있는 getSharedPreferences 함수를 사용합니다.

     

    getSharedPreferences 함수의 인자엔 파일 이름과 모드가 들어갑니다.

    이 함수로 데이터를 담고 있는 SharedPreferences를 얻어올 수 있습니다.

    val sharedPreferences = getSharedPreferences("TestData", MODE_PRIVATE)

     

    Mode 설명
    MODE_PRIVATE 해당 앱 내에서만 접근 가능
    MODE_WORLD_READABLE (deprecated) 외부 앱에서 읽기 가능
    MODE_WORLD_WRITEABLE (deprecated) 외부 앱에서 쓰기 가능

    SharedPreferences에서 데이터를 얻는 방법은 getString, getInt 등등이 있다.

    함수의 인자엔 key와 기본 값이 들어갑니다.

    val text = sharedPreferences.getString("key", "defaultValue")

     

    위처럼 적게 된다면 "key"를 통해 데이터를 가져오는데

    만약 데이터가 없을 경우 "defaultValue"를 반환하게 됩니다.


    SharedPreferences에서 데이터를 저장하는 방법은 Editor를 열어 데이터를 넣고 저장하는 방식입니다.

    putString과 같은 함수로 데이터를 넣을 수 있는데 인자로 key와 value가 필요합니다.

    val editor = sharedPreferences.edit()
    editor.putString("key", "value")
    editor.apply() // or editor.commit()

     

    위 예시처럼 데이터를 넣고 꼭 apply() 또는 commit() 함수를 실행해줘야 데이터가 저장됩니다.

    apply() 함수는 메모리 상에 있는 데이터에 변경된 값을 즉시 반영하지만 디스크엔 비동기적으로 반영이 됩니다.

    commit() 함수는 메모리와 디스크에 동기적으로 반영을 하기 때문에 메인 스레드에서 호출하는 것을 지양해야 합니다.


    예시 코드

    <?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/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="입력바람"
            android:inputType="text"
            android:textColor="#000000"
            android:textSize="24sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@+id/button"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.935" />
    
        <Button
            android:id="@+id/button"
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:layout_marginBottom="300dp"
            android:text="저장하기"
            android:textSize="30sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
    class MainActivity : AppCompatActivity() {
    
        private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    
        private val sharedPreferences by lazy { getSharedPreferences("TestData", MODE_PRIVATE) }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(binding.root)
    
            binding.button.setOnClickListener {
                saveData()
                Toast.makeText(this@MainActivity, "데이터 저장 완료", Toast.LENGTH_SHORT).show()
            }
            loadData()
        }
    
        private fun saveData() {
            val editor = sharedPreferences.edit()
            editor.putString("input", binding.editText.text.toString())
            editor.apply()
        }
    
        private fun loadData() {
            binding.editText.setText(sharedPreferences.getString("input", ""))
        }
    }

Designed by Tistory.