Android Studio

Android - SharedPreferences

내손은개발 🐾 2024. 3. 25. 14:03

SharedPreferences ?

  • 간단한 값을 저장할 때 주로 사용된다. 초기 설정 값이나 자동 로그인 여부 등 간단한 값을 저장할 때 DB를 사용하면 복잡하기에 SharedPreferences 사용이 적절하다.
  • Key - Value 형태로 저장한다.
  • 애플리케이션을 파일 형태로 데이터를 저장한다.

 

사용

 

1. layout 

main과 작성할 add Activity를 만들어준다.

addActivity의 EditText에서 받아온 text를 mainActivity의 TextView에 띄울 것이다.

추가적으로 앱을 종료했을 때도 저장되도록 하려한다.

activity_main activity_add

코드 ↓

더보기

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

    <TextView
        android:id="@+id/valueTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/goAddButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text="작성하러가기"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/valueTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

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

    <EditText
        android:id="@+id/addEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:layout_marginEnd="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/backButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:hint="이름을 작성해주세요."
        android:text="저장"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/addEditText" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

2. 코드 작성

const.kt 생성
const val INFORMATION = "textInformation"
const val NAME = "name"

데이터 받을 곳 생성

 

AddActivity.kt
    private fun saveData() {
        with(getSharedPreferences(INFORMATION, MODE_PRIVATE).edit()) {
            putString(NAME, binding.addEditText.text.toString())
            apply()
        }
        Toast.makeText(this, "저장완료", Toast.LENGTH_SHORT).show()
    }

binding으로 EditText에서 작성된 내용을 저장하는 것이다.

    private fun goBack() {
        binding.backButton.setOnClickListener {
            saveData()
            finish()
        }
    }

위에 메서드를 불러주고 finish로 종료

 

전체코드 ↓

더보기
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.kotlin_sharedpreference_practice.databinding.ActivityAddBinding

class AddActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAddBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityAddBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        goBack()
    }

    private fun goBack() {
        binding.backButton.setOnClickListener {
            saveData()
            finish()

        }
    }

    private fun saveData() {
        with(getSharedPreferences(INFORMATION, MODE_PRIVATE).edit()) {
            putString(NAME, binding.addEditText.text.toString())
            apply()
        }
        Toast.makeText(this, "저장완료", Toast.LENGTH_SHORT).show()
    }
}

 

 

 

 

MainActivity.kt
    private fun getDataUiUpdate(){
        with(getSharedPreferences(INFORMATION, Context.MODE_PRIVATE)){
            binding.valueTextView.text = getString(NAME,"이름 ?")
        }
    }
    private fun goAdd() {
        binding.goAddButton.setOnClickListener {
            val intent = Intent(this, AddActivity::class.java)
            startActivity(intent)
        }
    }
    override fun onResume() {
        super.onResume()
        getDataUiUpdate()
    }

 

전체코드 ↓

더보기
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.kotlin_sharedpreference_practice.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityMainBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        goAdd()
    }

    private fun goAdd() {
        binding.goAddButton.setOnClickListener {
            val intent = Intent(this, AddActivity::class.java)
            startActivity(intent)
        }
    }

    override fun onResume() {
        super.onResume()
        getDataUiUpdate()
    }

    private fun getDataUiUpdate(){
        with(getSharedPreferences(INFORMATION, Context.MODE_PRIVATE)){
            binding.valueTextView.text = getString(NAME,"이름 ?")
        }
    }
}

 

 

 

 

따로 앱이 종료되더라도 저장된 모습을 안보여줬지만 저장도 잘 된다.

완성 !

 

 

 

추가적으로 지우는 것까지 구현하자면

 

1. 버튼 생성

    <Button
        android:id="@+id/deleteButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="지우기"
        app:layout_constraintStart_toEndOf="@id/goAddButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="@id/goAddButton"/>

 

2. MainActivity.kt

    private fun deleteData() {
        binding.deleteButton.setOnClickListener {
            with(getSharedPreferences(INFORMATION, MODE_PRIVATE).edit()) {
                clear()
                apply()
                getDataUiUpdate()
            }
            Toast.makeText(this, "삭제 완료", Toast.LENGTH_SHORT).show()
        }
    }

 

onCreate()안에 deleteData()를 넣어주면 끝