와챠의 우당탕탕 개발 기록장
[안드로이드] 홍드로이드 #7 Shared Preference 연습 본문
반응형
앱이 종료되고 나서도 입력한 값이 저장되는 예제이다.
저장되는 값은 잠깐 저장하는 가벼운 값, 스위치 on/off 등
파일이 지워져도 상관없는 데이터를 저장하는 편이 좋다.
실제 서버 DB값으로는 사용하기 어렵다!
고 한다.

activity_main.xml는... 그냥 EditText만 덜렁 있음
MainActivity.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.myshared | |
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import android.widget.EditText | |
class MainActivity : AppCompatActivity() { | |
lateinit var plainText : EditText | |
// onCreate - onStart - onResume - onPause - onStop - onDestroy | |
// 액티비티 시작 시 호출됨 | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
plainText = findViewById(R.id.plainText) | |
// 저장된 데이터 로드하기 | |
loadDate() | |
} | |
// 액티비티 종료 직전에 호출됨 | |
override fun onDestroy() { | |
super.onDestroy() | |
// 데이터 저장하기 | |
saveData() | |
} | |
// 데이터 저장하기 | |
fun saveData() { | |
// 안드로이드 앱(지금 이 앱) 내부 폴더 경로에 pref라는 파일로 저장하겠다. | |
val pref = getSharedPreferences("pref", 0) | |
// 수정 모드 | |
val edit = pref.edit() | |
// 데이터 담기(키값, 저장할 문자열 값) | |
edit.putString("str", plainText.text.toString()) | |
edit.apply() // 저장 완료 | |
} | |
// 저장한 데이터 로드하기 | |
fun loadDate() { | |
val pref = getSharedPreferences("pref", 0) | |
// 키값은 str, 키값의 데이터가 존재하지 않을 경우 대체 대이터는 "" | |
plainText.setText(pref.getString("str", "")) | |
} | |
} |
반응형
'코딩 일기장 > Android(Kotlin)' 카테고리의 다른 글
[안드로이드] 홍드로이드 #10 RecyclerView 연습 (0) | 2021.05.04 |
---|---|
[안드로이드] 홍드로이드 #8 WebView 연습 (0) | 2021.05.02 |
[안드로이드] 홍드로이드 #6 Navigation 연습 (0) | 2021.05.01 |
[안드로이드] Firebase 연동(1) (0) | 2021.05.01 |
[안드로이드]Python(Django) <=> MySQL <=> Json(2) (0) | 2021.05.01 |