안드로이드

[안드로이드] sharedPreference 사용예제

2023. 5. 30. 12:51


728x90
getSharedPreference를 사용하면 되는듯

val shared = getSharedPreferences("파읾령", Context.MODE_PRIVATE)
// 이걸 사용하며 앱 저장공간에 xml파일이 생성되는데 이 xml파일이 map과 같은 자료구조역할을 함
Context.MODE_PRIVATE는 그냥 적어주는 거

val firstOpen = shared.getBoolean("first_open", false)
// 이걸 사용하면 shared라는 xml파일 내용중 first_open이라는 키를 찾아서 리턴함 first_open이라는
키를 못찾는다면 두번째 인자를 리턴함

val editor = shared.edit()
editor.putBoolean("first_open", true)
editor.commit()
이걸 사용해서 shared라는 xml파일에 값을 저장할 수 있음

 

이러한 개념을 사용한 예제 코드

package com.example.myapplication

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.example.myapplication.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    val binding by lazy {ActivityMainBinding.inflate(layoutInflater)}

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

        val shared = getSharedPreferences("파읾령", Context.MODE_PRIVATE)

        val firstOpen = shared.getBoolean("first_open", false)
        if (firstOpen) {
            binding.text.visibility = View.GONE
        }
        val editor = shared.edit()
        editor.putBoolean("first_open", true)
        editor.commit()
    }
}
728x90
안드로이드
[안드로이드] sharedPreference 사용예제