Preference Example
SharedPreference 기본 선언 형태는 다음과 같다.
SharedPreferences pref = getSharedPreferences("isTrue", MainActivity.MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); |
MODE_PRIVATE는 파일 생성 모드이며 기본값이다. 해당 파일은 호출한 앱에서만 접근이 가능하다.
pref.getBoolean("isTrue", false); |
저장된 데이터를 가져오는 방법.
editor.putBoolean("isTrue", true); editor.commit(); |
데이터를 저장하는 방법.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" 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="com.preferenceexam.mystoryg.preferenceexam.MainActivity">
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Do you want to learn preference?" />
<CheckBox android:id="@+id/check1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/check_true" />
<CheckBox android:id="@+id/check2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/check_false" />
</LinearLayout> |
MainActivity.java
package com.preferenceexam.mystoryg.preferenceexam;
import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.CheckBox; import android.widget.Checkable;
public class MainActivity extends Activity { CheckBox checkTrue; CheckBox checkFalse; SharedPreferences pref; SharedPreferences.Editor editor; boolean isTrue;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
checkTrue = (CheckBox) findViewById(R.id.check1); checkFalse = (CheckBox) findViewById(R.id.check2); pref = getSharedPreferences("isTrue", MainActivity.MODE_PRIVATE); editor = pref.edit();
isTrue = pref.getBoolean("isTrue", false);
if (isTrue) { checkTrue.setChecked(true); checkFalse.setChecked(false); } else { checkTrue.setChecked(false); checkFalse.setChecked(true); }
checkTrue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkTrue.setChecked(true); checkFalse.setChecked(false); editor.putBoolean("isTrue", true); editor.commit(); } });
checkFalse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkTrue.setChecked(false); checkFalse.setChecked(true); editor.putBoolean("isTrue", false); editor.commit(); } }); }
} |
![](https://t1.daumcdn.net/cfile/tistory/26111A465873AF8A27)
![](https://t1.daumcdn.net/cfile/tistory/22122C465873AF8B25)