본문 바로가기
Kotlin/Kotlin 문법

ANDROID SharedPreferences 사용

by MonoSoft 2020. 9. 25.
728x90
반응형

ANDROID SharedPreferences 사용

 

앱의 설정값을 저장할 용도로 많이 사용하는 것

 

 

package com.monosoft.sharedpreferencessample

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {

val SP_NAME = "my_sp_storage"

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

//writeSharedPreference("name","마이클")
val value = readSharedPreference("name")
Log.d("프리퍼런스","name = $value")
}

fun writeSharedPreference(key:String, value:String) {
val sp = getSharedPreferences(SP_NAME, Context.MODE_PRIVATE) //저장소,모드
val editor = sp.edit()
editor.putString(key,value)
//editor.put
editor.apply()
}

fun readSharedPreference(key:String) : String {
val sp = getSharedPreferences(SP_NAME, Context.MODE_PRIVATE) //저장소,모드
return sp.getString("name", "") ?: ""
}
}

 

728x90
반응형

댓글