본문 바로가기

카테고리 없음

SharedPreferenses

Preference

  • 프로그램의 설정 정보를 영구적으로 저장하는 용도로 사용
  • XML 포맷의 텍스트 파일에 키-값 세트로 정보를 저장
  • SharedPreferences class
    • preference의 데이터(키-값 세트)를 관리하는 클래스
    • 응용 프로그램 내의 액티비티 간에 공유하며, 한쪽 액티비티에서 수정 시 다른 액티비티에서도 수정된 값을 읽을 수 있다
    • 응용 프로그램의 고유한 정보이므로 외부에서는 읽을 수 없다

공유 환경설정의 핸들 가져오기

  • getSharedPreferences (name,mode)
    • 여러개의 Shared Preference파일들을 사용하는 경우
    • name: Preference 데이터를 저장할 xml파일의 이름
    • mode : 파일의 공유 모드
      • MODE_PRIVATE : 생성된 xml파일은 호출한 애플리케이션 내에서만 읽기 쓰기가 가능
      • MODE_WORLD_READABLE,MODE_WORLD_WRITEABLE은 보안상 이유로 API level 17에서 deprecated됩니다
val shared = activity?.getSharedPreferences(
	getString(R.string.preference_file_key), Context.MODE_PRIVATE)

 

  • getPreferences
    • 한개의 Shared Preference 파일을 사용하는 셩우
    • Activity 클래스의 정의된 메소드 이므로 ,Activity 인스턴스를 통해 접근 가능
    • 생성한 액티비티 전용이므로 같은 패키지의 다른 액티비티는 읽을수 없다.
    • 액티비티와 동일한 이름의 xml 파일 생성
      val shared = activity?.getPreferences(Context.MODE_PRIVATE)​

예시

package com.example.mytest

import android.app.Activity
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.mytest.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val view = binding.root
        setContentView(view)

        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()

        edit.putString("name",binding.save.text.toString())
        edit.apply()
    }

    private fun loadData(){
        val pref = getSharedPreferences("pref",0)
        binding.save.setText(pref.getString("name",""))
    }
}

 

<?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:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/save"
        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_margin="32dp"
        android:text="저장하기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/save"/>

</androidx.constraintlayout.widget.ConstraintLayout>

SharedPreferenses 

장점 : 저장하고 꺼내오는 속도가 빨라서 간단한 값을 저장할 때 많이 쓰인다 

 

사용방법

 

데이터 저장하기

 

val sharedPreference = getSharedPreferences("이름",MODE_PRIVATE)

val  editor  :  SharedPreference.Editor = sharedPreference,edit()

editor.putString("키","값")

editor.apply()

 

 

데이터 불러오기

 

val sharded = getSharedPreference("이름", MODE_PRIVATE )

val userId = shared.getString("키 값","기본 값") ? : ""

sharded. getString("키 값","기본 값")

 

 

데이터 삭제하기

 

val shaed = getSharedPreference("이름", MODE_PRIVATE )

val editor = SharedPreference.edit()

 

editor.remove("키 값")

// 전체 삭제는 editor.clear()

editor.commit()

 

단점

1. Synchronous Blocking: SharedPreferences는 동기적으로 작동하며, 값을 읽거나 쓸 때 블로킹될 수 있습니다. 이는 UI 스레드에서 사용할 경우 앱의 응답성을 저하시킬 수 있습니다.

2. No Type Safety: SharedPreferences는 모든 데이터를 String 형태로 저장하며, 별도의 변환 없이 사용자 정의 객체를 저장할 수 없습니다. 이로 인해 데이터 유형에 대한 안정성이 떨어질 수 있습니다.

3. Limited Data Structure: SharedPreferences는 단순한 Key-Value 저장소로서 복잡한 데이터 구조를 지원하지 않습니다. 복잡한 데이터를 저장하려면 번거로운 변환 작업이 필요합니다.

4. Lack of Data Observation: SharedPreferences는 데이터 변경을 감지하거나 이에 대한 알림을 제공하지 않습니다. 따라서 데이터 변경 시 다른 구성 요소들에게 변화를 알리기 위해 추가적인 코드가 필요합니다.

728x90