안드로이드 프로그래밍[Kotiln Code]/sharedPreference

[kotlin ] SharedPreferences : 데이터 저장 하는 방법

훈츠 2020. 1. 30. 12:15
반응형

안드로이드 프로그램에는 생명 주기 라는 것이 있어서, 다른 액티비티로 이동한다던지 앱을 재시작 혹은 화면을 바꿀때 데이터를 적절히 처리 하지 않으면 초기화 되게 되어있습니다. 안드로이드에서 SQL 데이터베이스를 통해서, 혹은 Intent안에 저장하는 방법외에도 SharedPreference 라는것을 이용하여 데이터를 저장할수 있게 설계 되었습니다. 많은 양의 데이터를 저장할때 혹은 앱이 삭제되었을때는 SharedPreference 저장한 영역역시 삭제 되므로 다른 방법을 검토 해야 할것 같습니다. 

 

1. 액티비티 에서 사용 방법 

1
2
3
4
5
6
7
8
9
10
11
12
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
//액티비티 적용시
val pref = this.getPreferences(0// 0 은 (Context.MODE_PRIVATE)와 같음
val editor = pref.edit()
 
//값을 저장 할때는 editor를 사용하고, apply를 적용해야 동작함. 
editor.putBoolean("init"true).apply()
 
//값을 가져 올때는 pref를 사용
pref.getBoolean("init",false)
 
 

 

1.2. 프래그먼트 적용시

1
2
3
4
5
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
//프래그먼트 적용시 선언 법 
val pref =  requireActivity().getPreferences(0)
val editor = pref.edit()
cs

 

1.3. 브로드캐스트 적용시

1
2
3
4
5
6
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
 
//브로드캐스트 리시버
val pref = context.getSharedPreferences(Settings.Global.VALUE,Context.MODE_PRIVATE) // 0 은 (Context.MODE_PRIVATE)와 같음
val editor = pref.edit()
 
cs

 

간단하게 위의 방법으로 액티비티 및 프래그먼트에서 사용할수도 있고, 아예 클래스로 만들어서 사용하는 방법도 있습니다. 다음 세가지 정도 해주면 됩니다.

  1. SharedPreferences Class 생성
  2. App Class 생성해서 SharedPreferences를 가장 먼저 쓸 수 있도록 설정
  3. manifest에 App Class의 이름 등록

2.1 SharedPreferences Class 생성 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
class MySharedPreferences(context: Context) {
 
    val PREFS_FILENAME = "prefs"
    val PREF_KEY_MY_EDITTEXT = "myEditText"
    val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME, 0)
    /* 파일 이름과 EditText를 저장할 Key 값을 만들고 prefs 인스턴스 초기화 */
    //key값을 이용한 저장
    fun setV(key:String, value:String? ){
        prefs.edit().putString(key,value).apply()
    }
    //key값을 이용한 로드
    fun getV(key:String):String?{
        return prefs.getString(key,"")
    }
    var myEditText: String?
        get() = prefs.getString(PREF_KEY_MY_EDITTEXT, "")
        set(value) = prefs.edit().putString(PREF_KEY_MY_EDITTEXT, value).apply()
    /* get/set 함수 임의 설정. get 실행 시 저장된 값을 반환하며 default 값은 ""
     * set(value) 실행 시 value로 값을 대체한 후 저장 */
}
cs

 

2.2 App Class 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
class App : Application() {
 
    companion object {
        lateinit var prefs : MySharedPreferences
    }
    /* prefs라는 이름의 MySharedPreferences 하나만 생성할 수 있도록 설정. */
 
    override fun onCreate() {
        prefs = MySharedPreferences(applicationContext)
        super.onCreate()
    }
}
cs

 

2.3 manifest에 App Class 이름 등록 

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
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sharedpreftest">
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:name=".App"     // 이 부분 추가 
        >
 
        <activity android:name=".Main2Activity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
 

 

4. 사용하고자 하는 영역에서 사용 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Hoons Blog---https://rain2002kr.tistory.com------------------------------------------------------------------코드///
edTest.setText(App.prefs.myEditText)
 
btSave.setOnClickListener({
    App.prefs.myEditText = edTest.text.toString()
    val str  = App.prefs.myEditText
    if(str == ""){
        Toast.makeText(this,"초기화되었습니다.", Toast.LENGTH_LONG).show()
    }else {
        Toast.makeText(this,"${str} 저장 되었습니다.", Toast.LENGTH_LONG).show()
    }
})
 
btReset.setOnClickListener({
    App.prefs.myEditText  = ""
    Toast.makeText(this,"초기화되었습니다.", Toast.LENGTH_LONG).show()
})
cs

 

5. 코드 

https://github.com/rain2002kr/SharedprefTest.git

 

rain2002kr/SharedprefTest

Contribute to rain2002kr/SharedprefTest development by creating an account on GitHub.

github.com

 

반응형