UroA 개발 블로그

[Android] SharedPreference 사용하기 ② 본문

Programming/Android

[Android] SharedPreference 사용하기 ②

UroA 2015. 11. 25. 13:24

SharedPreference 사용하기 ②

 

 

이번에는 직접 예제 코드를 작성해 보겠습니다.

 

https://github.com/kdhx92/Android_PreferenceShared_test 에서도 확인 가능합니다.

 

 

① < activity_main.xml > : main의 레이아웃

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3ddb"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">

<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="이름 :"
android:textSize="20dp" />

<EditText
android:id="@+id/editName"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="8"
android:maxLength="10"
android:singleLine="true"
android:textSize="20dp" />

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">

<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="전공 :"
android:textSize="20dp" />

<EditText
android:id="@+id/editMajor"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="8"
android:maxLength="10"
android:singleLine="true"
android:textSize="20dp" />

</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">

<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="파트 :"
android:textSize="20dp" />

<CheckBox
android:id="@+id/chkDevelop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="개발" />

<CheckBox
android:id="@+id/chkDesign"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="디자인" />

<CheckBox
android:id="@+id/chkPM"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="기획" />


</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">

<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="성별 :"
android:textSize="20dp" />

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<RadioButton
android:id="@+id/radioMale"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="50dp"
android:layout_weight="1"
android:text="남" />

<RadioButton
android:id="@+id/radioFemale"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="여" />

</RadioGroup>

</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">

<TextView
android:layout_width="100dp"
android:layout_height="match_parent"
android:gravity="center"
android:text="설정 :"
android:textSize="20dp" />

<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/seekBar"
android:layout_gravity="center"/>


</LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center">

<Button
android:id="@+id/btnSave"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:text="save"
android:layout_marginRight="20dp"/>

<Button
android:id="@+id/btnReset"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:layout_marginRight="20dp"
android:text="Reset" />

<Button
android:id="@+id/btnLoad"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:text="Load" />


</LinearLayout>



</LinearLayout>
</RelativeLayout>

 

② < MainActivity.java >
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Toast;

/**
* UI 상의 사용자가 입력한 값들을 저장하기 위해 SharedPreferences를 사용한 실습입니다.
* 아래의 주석부터 '상태'라는 단어는
* [UI 상의 사용자가 입력한 값(SharedPreferences에 저장할 값)]
* 이라고 생각하시면 됩니다.
*/
public class MainActivity extends AppCompatActivity {

SharedPreferences sharedPreferences;

EditText editName, editMajor;
CheckBox chkDevelop, chkDesign, chkPM;
RadioGroup radioGroup;
Button btnSave, btnLoad, btnReset;
SeekBar seekBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

initPreferences(); //SharedPreferences 초기화
initView(); //View 초기화
btn_Event(); //버튼 클릭 시의 이벤트
loadState(); //상태를 불러오는 메소드

/**
*상태 초기화(버튼이벤트가 아니라 onCreate에 있으므로 액티비티가 실행될 때 SharedPreferences로 저장한 값을 불러옵니다.
*실습 때에는 버튼을 눌렀을 때만 상태를 불러옵니다.
*/

}

/**
* btn_Event()
*
* 버튼 클릭 시의 이벤트
* btnSave : saveState() -> 상태를 저장하는 메소드 호출
* btnLoad : loadState() -> 상태를 불러오는 메소드 호출
* btnReset : 화면 상의 뷰들의 값을 초기화
*/
private void btn_Event() {

btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveState(); //상태를 저장하는 메소드
Toast.makeText(getApplicationContext(), "저장되었습니다.", Toast.LENGTH_SHORT).show();
}
});

btnLoad.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadState(); //상태를 불러오는 메소드
}
});

btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editName.setText("");
editMajor.setText("");
chkDevelop.setChecked(false);
chkDesign.setChecked(false);
chkPM.setChecked(false);
radioGroup.check(0);
seekBar.setProgress(0);
}
});

}

/**
* loadState()
*
* 상태를 불러오는 메소드입니다.
* sharedPreferences.getString("key", defaultValue) key는 식별자, defaultValue는 해당 key에 값이 없을 때 디폴트로 가져오는 값
* getInt
* getBoolean 등등
* 해당하는 자료형에 따라 메소드가 달라집니다.
* EditText의 경우 String 형으로 저장이 됩니다.
* CheckBox의 경우는 Boolean 형으로 저장이 됩니다.
* seekBar의 경우는 Int 형으로 저장이 됩니다.
*/

private void loadState() {
editName.setText(sharedPreferences.getString("name", ""));
editMajor.setText(sharedPreferences.getString("major",""));
chkDevelop.setChecked(sharedPreferences.getBoolean("chkDevelop", false));
chkDesign.setChecked(sharedPreferences.getBoolean("chkDesign", false));
chkPM.setChecked(sharedPreferences.getBoolean("chkPM", false));
radioGroup.check(sharedPreferences.getInt("radioGroup", 0));
seekBar.setProgress(sharedPreferences.getInt("seekBar",0));
}

/**
* saveState()
*
* 상태를 저장하는 메소드입니다.
* SharedPreferences 데이터에 변화를 주려면 Editor를 사용해야 합니다.
* SharedPreferences.Editor editor = sharedPreferences.edit(); -> 변화를 주는 메소드를 작성하기 전 반드시 editor를 생성합니다.
*
* editor.putString("key", value) key는 식별자, value는 해당 key(식별자)에 대응하는 값
* putInt
* putBoolean 등등
* 해당하는 자료형에 따라 메소드가 달라집니다.
* EditText의 경우 String 형
* CheckBox의 경우는 Boolean 형
* seekBar의 경우는 Int 형
*
* 마지막에 반드시 commit() 메소드를 호출해야 SharedPreferences에 저장이 됩니다.
*/

private void saveState() {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name",editName.getText().toString());
editor.putString("major", editMajor.getText().toString());
editor.putBoolean("chkDevelop", chkDevelop.isChecked());
editor.putBoolean("chkDesign", chkDesign.isChecked());
editor.putBoolean("chkPM", chkPM.isChecked());
editor.putInt("radioGroup", radioGroup.getCheckedRadioButtonId());
editor.putInt("seekBar", seekBar.getProgress());
editor.commit();
}

/**
* initPreferences()
*
* SharedPreferences를 초기화하는 메소드
* sharedPreferences = getSharedPreferences("이름", 모드);
* 이름은 파일명 -> SharedPreferences의 저장경로는 해당 단말기 "data/data/[패키지 이름]/shared_prefs/이름.xml"입니다.
* 모드는 접근 권한입니다.
* MODE_PRIVATE 모드로 설정하면 해당 앱에서만 SharedPreferences 데이터에 접근 가능합니다.
*/
private void initPreferences() {
sharedPreferences = getSharedPreferences("pref", MODE_PRIVATE);
}

private void initView() {
editName = (EditText)findViewById(R.id.editName);
editMajor = (EditText)findViewById(R.id.editMajor);
chkDevelop = (CheckBox)findViewById(R.id.chkDevelop);
chkDesign = (CheckBox)findViewById(R.id.chkDesign);
chkPM = (CheckBox)findViewById(R.id.chkPM);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
btnSave = (Button)findViewById(R.id.btnSave);
btnLoad = (Button)findViewById(R.id.btnLoad);
btnReset = (Button)findViewById(R.id.btnReset);
seekBar = (SeekBar)findViewById(R.id.seekBar);
}
}
Comments