경험의 기록

안드로이드에서는 설정같은 Key/Value 형태로 데이터를 저장할 수 있는 간단한 정보를 저장하기 위하여 SharedPreference 를 사용할 수 있다.

 

 

선언하기

// 모드 0 = Context.MODE_PRIVATE
        val pref = this.getPreferences(0)
        val pref = this.getSharedPreferences("a",0) // 여러개 쓸때
        val editor = pref.edit()

getPreferences 는 별도의 파일명을 지정하지 않고 액티비티 이름의 파일 내에 저장한다. 데이터를 저장할 곳이 하나만 필요할 때 사용할 수 있다.

getSharedPreferences 파일명에 대한 정보를 매개변수로 지정하므로 해당 이름으로 XML 파일을 만들어, 다른 액티비티나 컴포넌트들이 데이터를 공유해서 이용할 수 있다. 데이터를 각각의 파일로 나눠 저장할 때 사용한다.

또한 SharedPreferences를 수정하기 위해선 에디터를 별도로 선언해주어야 한다.

 

 

데이터 다루기

// 데이터 불러오기
pref.getString("키","밸류")

// 데이터 저장하기
editor.putString("키","밸류").apply()

// 데이터 삭제하기
editor.remove("키").apply()

// 데이터 초기화하기
editor.clear().apply()

SharedPreferences 의 수정은 editor가 대신하게 되며 editor가 변경한 것을 적용하려면

commitapply를 사용해야한다.

 

  • commit : 동기 방식으로 메모리 내의 SharedPreferences 를 변경하고, 성공시 true 리턴
  • apply : 비동기 방식으로 메모리 내의 SharedPreferences 를 즉시 변경, 작업 실패 알림X

반환값이 필요없는 일반적인 경우에 apply를 쓰는것이 효율적이다.

 

 


사용예시

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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="112dp"
        android:text="저장할 내용을 입력해주세요."
        app:layout_constraintEnd_toEndOf="parent"
        android:textSize="24sp"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:inputType="textPersonName"
        android:hint="입력창"
        android:paddingStart="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        android:paddingLeft="20dp" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="56dp"
        android:text="저장된 텍스트"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="52dp"
        android:text="삭제"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

MainActivity.kt

package org.techtown.sharedpreference

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.core.widget.addTextChangedListener
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 모드 0 = Context.MODE_PRIVATE
        val pref = this.getPreferences(0)
//        val pref = this.getSharedPreferences("a",0) // 여러개 쓸때
        val editor = pref.edit()

        // Save 키를 가진 값 불러옴
        textView2.text = pref.getString("Save","내용 없음")

        // Save 키를 가진 값 삭제
        button.setOnClickListener {
            editor.remove("Save").apply()
            textView2.text = pref.getString("Save","저장된 값 없음")
        }

        editText.addTextChangedListener(object : TextWatcher{
            // 입력 후에 작동
            override fun afterTextChanged(p0: Editable?) {
                // 텍스트가 바뀌면 Save 키에 값 넣음
                editor.putString("Save",editText.text.toString()).apply()
                // Save 키를 가진 값 불러옴
                textView2.text = pref.getString("Save","내용 없음")
            }

            // 입력 전에 작동
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            // 텍스트 변화 시 작동
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })



    }
}

텍스트창에 입력한 텍스트가 실시간으로 밑의 텍스트뷰에 반영되고,

앱을 종료 후 다시 실행해도 텍스트뷰에 내용이 유지되는 앱을 만들었다.

 

github.com/HanYeop/AndroidStudio-Practice/tree/master/SharedPreference

 

HanYeop/AndroidStudio-Practice

AndroidStudio Practice. Contribute to HanYeop/AndroidStudio-Practice development by creating an account on GitHub.

github.com

 

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading