Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- StatefulWidget
- appbar
- 프로그래머스
- margin
- 프래그먼트
- 반복문
- 상속
- padding
- 변수
- 액티비티 생명주기
- Kotlin
- button
- setState
- Flutter
- 추상메소드
- 두 수의 나눗셈
- If
- 안드로이드 스튜디오
- 리스트뷰
- spacer
- SizedBox
- 람다식
- Widget
- 지연초기화
- StatelessWidget
- 뷰바인딩
- 빌드 프로세스
- 패스트캠퍼스
- 인스턴스
- expanded
Archives
- Today
- Total
Y_Ding
SharedPreferences 본문
데이터를 안드로이드에 저장하는 방법에 대해 알아보자
앱을 종료하거나 다시 시작하더라도 어딘가에 데이터가 저장되어 있는 것
데이터를 영구적으로 저장하는 방법 중 하나가 Preference
Preference
- 프로그램의 설정 정보를 영구적으로 저장하는 용도로 사용
- 예시 : 앱에서 알림을 울리냐 안울리냐, 자동 로그인을 할거냐 안할거냐 등
- xml포맷으로 텍스트 파일에 키-값 세트로 정보 저장 (예: 알람-true)
SharedPreferences 클래스
- 프리퍼런스의 데이터(키-값 세트)를 관리하는 클래스
- 액티비티 간에 공유, 한쪽 액티비티에서 수정하면 다른 액티비티에서도 수정된 값을 읽을 수 있음
- 응용 프로그램의 고유한 정보이기 때문에 외부에서는 읽을 수 없음
Preference 사용 방법
- getSharedPreferences(name(키), mode(값))
- 여러가지 데이터들을 한 번에 저장
- 보통 getSharedPreferences를 사용 ( 한개의 데이터를 저장하는 일이 거의 없음)
- name : 프리퍼런스 데이터를 저장할 xml 파일의 이름
- mode : 파일의 공유 모드
- MODE_PRIVATE : 호출한 애플리케이션 내에서만 읽기, 쓰기가 가능
- MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE 은 API level 17부터 더이상 사용되지 않음( 보안상의 이유)
- 사용 가능한 데이터 타입: Boolean, Float, Int, Long, String
val sharedPref = activity?.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE)
- getPreferences
- 한개의 Shared Preference 파일을 사용하는 경우 (한개의 데이터만 저장)
- 잘 사용하지 않음
val shardPref = activity?.getPreferences(Context.MODE_PRIVATE)
실습하기
- EditText를 만들어 text를 입력 후, 저장 버튼을 누르면 입력한 text를 저장하고, 앱을 다시 열면 저장된 text가 그대로 유지될 수 있도록 하는 실습 해보기
MainActivity.kt
package com.example.sharedpreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.sharedpreferences.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btnSave.setOnClickListener{
saveData()
Toast.makeText(this, "Data Saved.", Toast.LENGTH_SHORT).show()
}
loadData()
}
private fun saveData() {
// pref란 이름의 파일명을 만들어줌
val pref = getSharedPreferences("pref", 0)
val edit = pref.edit()
// 1번째 인자는 key, 2번째 인자는 실제 담아둘 값
// name이라는 key에다가 editText의 내용을 넣어줌
edit.putString("name", binding.etHello.text.toString())
edit.apply() //저장완료
}
//데이터를 불러오는 것
private fun loadData() {
val pref = getSharedPreferences("pref", 0)
// key 값으로 getString으로 불러와서 setText로 etHello(xml editText id)에 넣어줌
// getString을 쓸 때는 defaultValue를 지정해주어야 함 (set을 하지 않은 상태로 get을 먼저할 수도 있기 때문에)
// getString("name", "") : "name" 은 key , ""는 defValue
binding.etHello.setText(pref.getString("name", ""))
}
}
activity_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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/et_hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:textColor="#000000"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="저장하기"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/et_hello" />
</androidx.constraintlayout.widget.ConstraintLayout>
데이터가 잘 저장되었는지 확인하고 싶다면?
- Android Studio에서 Device File Explorer -> data -> 프로젝트 파일 -> shared_prefs -> xml파일 클릭
- 파일 안에 내가 입력한 '안녕하세요!' 라는 데이터가 입력되어 있는 것을 확인할 수 있음
- shared_prefs 파일이 안보인다면 프로젝트 파일명 우클릭 후 Synchronize를 클릭
'TodayILearned > Android&Kotlin' 카테고리의 다른 글
안드로이드 앱의 기본 구조 (2) | 2023.09.14 |
---|---|
Room (0) | 2023.09.13 |
팀프로젝트 TIL (0) | 2023.09.07 |
팀프로젝트 TIL (0) | 2023.09.06 |
앱개발 숙련 TIL - Notification (0) | 2023.08.25 |