๊ด€๋ฆฌ ๋ฉ”๋‰ด

JiYoung Dev ๐Ÿ–ฅ

[Android] SharedPreference (2023.07.26) ๋ณธ๋ฌธ

full stack/์•ˆ๋“œ๋กœ์ด๋“œ

[Android] SharedPreference (2023.07.26)

Shinjio 2023. 7. 26. 13:40

์ €์žฅํ•˜๋ ค๋Š” ํ‚ค-๊ฐ’ ์ปฌ๋ ‰์…˜์ด ๋น„๊ต์  ์ž‘์€ ๊ฒฝ์šฐ SharedPreferences API๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. SharedPreferences ๊ฐ์ฒด๋Š” ํ‚ค-๊ฐ’ ์Œ์ด ํฌํ•จ๋œ ํŒŒ์ผ์„ ๊ฐ€๋ฆฌํ‚ค๋ฉฐ ํ‚ค-๊ฐ’ ์Œ์„ ์ฝ๊ณ  ์“ธ ์ˆ˜ ์žˆ๋Š” ๊ฐ„๋‹จํ•œ ๋ฉ”์„œ๋“œ๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ๊ฐ SharedPreferences ํŒŒ์ผ์€ ํ”„๋ ˆ์ž„์›Œํฌ์—์„œ ๊ด€๋ฆฌํ•˜๋ฉฐ ๋น„๊ณต๊ฐœ์ด๊ฑฐ๋‚˜ ๊ณต์œ ์ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

SharedPreferences ์ƒ์„ฑ

 

//url๊ฐ’ ์ €์žฅํ•˜๊ธฐ (SharedPreference -> ๋‚ด๋ถ€ ๋ฉ”๋ชจ๋ฆฌ์— ์ €์žฅ -> ๋ชจ๋“  fragment์—์„œ ์‚ฌ์šฉ๊ฐ€๋Šฅ)
//  - editor ์‚ฌ์šฉ
// ์ž๋™ ๋กœ๊ทธ์ธ์— ํ™œ์šฉ ๊ฐ€๋Šฅ!! (์–ดํ”Œ์„ ๊บผ๋„ ๊ณ„์† ์ €์žฅ๋จ)
val spf = requireActivity().getSharedPreferences("mySPF",Context.MODE_PRIVATE)
//MODE_PRIVATE : ๋‚ด๋ถ€ ์บ์‹œ์— ์ €์žฅ -> ์ €์žฅ๋œ ๊ฐ’์ด ๋…ธ์ถœ๋˜์ง€ ์•Š๋„๋ก
val editor = spf.edit() //์—๋””ํ„ฐ ์ƒ์„ฑ
editor.putString("url", url) //ํ‚ค-์Œ์œผ๋กœ ์ €์žฅ
editor.commit()

 

fragment๊ฐ€ ์•„๋‹Œ ์ผ๋ฐ˜ activity์—์„œ๋Š” getSharedPreferences ๋ฐ”๋กœ ์‚ฌ์šฉ 

 

SharedPreferences ์‚ฌ์šฉ

 

//SharedPreference ๊ฐ€์ ธ์˜ค๊ธฐ
val spf = requireActivity().getSharedPreferences(
    "mySPF",
    Context.MODE_PRIVATE
)
//SharedPreference ์•ˆ์— ์ €์žฅ๋œ ๊ฐ’ ๊บผ๋‚ด์„œ ์‚ฌ์šฉํ•˜๊ธฐ
//getString(ํ‚ค๊ฐ’, ๊ธฐ๋ณธ๊ฐ’)
var url : String? = spf.getString("url", "http://www.google.com")