안드로이드 개발 질문/답변
(글 수 45,052)
여기에 질문을 올렸다가 밥 아저씨님이 알려주신 링크 따라가서 예제 보고 만들었는데요..
▽ 요 링크입니다.
그대로 따라했는데 전혀 저장이 안되네요;;
Back Key로 앱 껐다가 다시 실행시켰는데 계속 처음 상태로 뜹니다..
체크 한거 글자 쓴거 하나도 안 떠요 ㅠ
왜 그런지 아시는 분 조언 부탁드립니다 ㅠ
package com.preftest;
import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.widget.CheckBox; import android.widget.EditText;
public class PrefTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Shared Preference를 불러옴
SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
EditText edit1 = (EditText)findViewById(R.id.EditText);
CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
// 저장된 값들을 불러옴
String text = pref.getString("EditText", "");
Boolean chk1 = pref.getBoolean("Check1", false);
Boolean chk2 = pref.getBoolean("Check2", false);
edit1.setText(text);
check1.setChecked(chk1);
check2.setChecked(chk2);
}
// 어플리케이션이 화면에서 사라질 때
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
// UI 상태를 저장
SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit(); // Editor를 불러옴
EditText edit1 = (EditText)findViewById(R.id.EditText);
CheckBox check1 = (CheckBox)findViewById(R.id.CheckBox01);
CheckBox check2 = (CheckBox)findViewById(R.id.CheckBox02);
// 저장할 값들을 입력
editor.putString("editText", edit1.getText().toString());
editor.putBoolean("check1", check1.isChecked());
editor.putBoolean("check2", check2.isChecked());
// 저장
editor.commit();
}
}



저장할때의 key값과 불러올때의 key값이 일치하지 않는군요.
아래와 같이 변경해 주시면 될 것 같습니다.
그리고 onStop()에서 저장한 값들은, onResume()에서 불러오는 것이 더 낫지 않을까요?
// 저장된 값들을 불러옴
String text = pref.getString("editText", "");
Boolean chk1 = pref.getBoolean("check1", false);
Boolean chk2 = pref.getBoolean("check2", false);