2010년 7월 28일 수요일

SharedPreference

레이아웃 : main.xml


http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

 android:id="@+id/EditText" 
 android:hint="글자를 입력하세요!" 
 android:layout_width="fill_parent">
 
 


 android:text="체크박스1" 
 android:layout_height="wrap_content" 
 android:layout_width="fill_parent">
 


 android:layout_height="wrap_content" 
 android:text="체크박스2" 
 android:layout_width="fill_parent">

코드 : prefExample.java
01.package com.androidhuman.Preferences;
02. 
03.import android.app.Activity;
04.import android.content.SharedPreferences;
05.import android.os.Bundle;
06.import android.widget.CheckBox;
07.import android.widget.EditText;
08. 
09.public class prefExample extends Activity {
10./** Called when the activity is first created. */
11.@Override
12.public void onCreate(Bundle savedInstanceState) {
13.super.onCreate(savedInstanceState);
14.setContentView(R.layout.main);
15. 
16.SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); // Shared Preference를 불러옵니다.
17.EditText edit1 = (EditText)findViewById(R.id.EditText);
18.CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
19.CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
20. 
21.// 저장된 값들을 불러옵니다.
22.String text = pref.getString("editText""");
23.Boolean chk1 = pref.getBoolean("check1"false);
24.Boolean chk2 = pref.getBoolean("check2"false);
25. 
26.edit1.setText(text);
27.check1.setChecked(chk1);
28.check2.setChecked(chk2);
29.}
30. 
31.public void onStop(){ // 어플리케이션이 화면에서 사라질때
32.super.onStop();
33.SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE); // UI 상태를 저장합니다.
34.SharedPreferences.Editor editor = pref.edit(); // Editor를 불러옵니다.
35. 
36.EditText edit1 = (EditText)findViewById(R.id.EditText);
37.CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
38.CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
39. 
40.// 저장할 값들을 입력합니다.
41.editor.putString("editText", edit1.getText().toString());
42.editor.putBoolean("check1", check1.isChecked());
43.editor.putBoolean("check2", check2.isChecked());
44. 
45.editor.commit(); // 저장합니다.
46.}
47.}

이 어플리케이션의 목적, SharedPreferences을 사용하는 목적은 "액티비티를 종료시켜도 사용자는 모르게" 하는 것입니다.
액티비티 라이프사이클에 따라서, 액티비티가 종료될 때 당시 UI상태를 기억하고 있다가 사용자가 다시 그 액티비티 (어플리케이션)을 실행시킬 때 저장된 상태를 그대~로 불러와서, 마치 사용자는 "아무 일도 일어나지 않은 것처럼" 계속 작업을 할 수 있죠.

일단, Shared Preferences가 어떻게 생긴 놈인지부터 알아보겠습니다.
Shared Preferences는 예전 Intent에 정보를 넣어서 보낼 때 처럼 키(key)와 값(Value) 한 쌍으로 이루어져 있습니다. 


자, 그럼 이제부터 Shared Preferences를 이용하여 데이터를 저장하는 과정에 대해 알아봅시다.

1. Shared Preferences 객체 생성하기
Intent 객체를 만들고, 그 안에 필요한 데이터를 넣어 보냈던 것 처럼 Shared Preferences 또한 객체를 생성해 주어야 합니다.

1.// "pref"라는 가진 Shared Preferences 객체를 생성합니다.
2.SharedPreferences pref = getSharedPreferences("Pref", Activity.MODE_PRIVATE);


2. Shared Preferences를 수정할 수 있는 에디터 생성 및 편집
SharedPreferences 겍체를 수정하려면, Editor 객체를 받아와야 합니다.

1.SharedPreferences.Editor editor = pref.edit(); // 에디터를 받아옵니다.
01.EditText edit1 = (EditText)findViewById(R.id.EditText);
02.CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
03.CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
04. 
05.editor.putString("editText", edit1.getText().toString()); // 데이터를 입력합니다.
06.editor.putBoolean("check1", check1.isChecked());
07.editor.putBoolean("check2", check2.isChecked());
08. 
09.editor.commit(); // 편집을 종료하고 저장합니다.
 SharedPreferences에서의 데이터 입력도 put (_키_, _값_) 형식을 따르고 있습니다.
사용 가능한 메소드로는 putString, putInt, putLong, putFloat, putBoolean이 있습니다. 이 형식에 맞추어 입력한 후, commit()메소드를 이용하여 데이터 편집을 마치고 저장합니다.

이 과정은 액티비티가 종료되는 과정, 즉 onStop()에서 일어나기에 onCreate()메소드를 오버라이드 하는 것처럼 onStop()메소드를 오버라이딩해야 합니다. onStop()메소드를 오버로딩하면 다음과 같이 됩니다.

01.public void onStop(){
02.super.onStop();
03.SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
04.SharedPreferences.Editor editor = pref.edit();
05. 
06. 
07.EditText edit1 = (EditText)findViewById(R.id.EditText);
08.CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
09.CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
10. 
11.editor.putString("editText", edit1.getText().toString());
12.editor.putBoolean("check1", check1.isChecked());
13.editor.putBoolean("check2", check2.isChecked());
14. 
15.editor.commit();
16.}

저장하는 것은 배웠으니, 이제 불러오는 것을 배워야겠죠?
불러오는 것은 그리 어렵지 않습니다. 아까 저장한 SharedPreferences 객체로부터 저장된 UI정보를 불러오기만 하면 됩니다. 
01.public void onCreate(Bundle savedInstanceState) {
02.super.onCreate(savedInstanceState);
03.setContentView(R.layout.main);
04. 
05.SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
06.EditText edit1 = (EditText)findViewById(R.id.EditText);
07.CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
08.CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
09. 
10.edit1.setText(pref.getString("editText"""));
11.check1.setChecked(pref.getBoolean("check1"false));
12.check2.setChecked(pref.getBoolean("check2"false));
13.}

아까 데이터를 저장할 때는 putExtra()를 썼던 것과 달리 데이터를 받아올 떄에는 get 메소드를 쓰면 됩니다.
get 메소드의 원형은 get(_키_, _기본값_) 입니다. 일단 키에 해당하는 데이터를 찾지만, 없을 경우엔 두번째 파라미터에 들어간 내용으로 초기화되게 됩니다.


*추가내용 : 2009/05/26
SharedPreference는 어떤 식으로 저장될까요? 파일? 데이터베이스?
정답은 파일입니다. DDMS를 통해 data/data/패키지이름/shared_prefs 폴더에 위에서 지정한 Preferences의 이름으로 저장됩니다.