Android/공부
[안드로이드] 데이터 저장하기 2
꾸끄꾸꾸
2020. 6. 22. 18:32
SharedPreferences를 사용해 데이터 저장하는 앱 만들어보기 2
1. xml
1. activity_main.xml
-
화면에 EditText와 글씨 색을 바꿀 버튼, 저장 버튼과 제거 버튼을 추가해준다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:padding="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="저장하기"/>
<Button
android:id="@+id/btn_remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="제거하기"/>
</LinearLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="내용을 입력하세요"
android:id="@+id/editText"
android:inputType="textPersonName"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="RED"/>
<Button
android:id="@+id/btn_blue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="BLUE"/>
<Button
android:id="@+id/btn_green"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="GREEN"/>
</LinearLayout>
</LinearLayout>
2. java
1. MainActivity.java
-
화면 구성에 필요한 레이아웃 객체와 SharedPreferences 선언하기
public class MainActivity extends AppCompatActivity {
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private int SelectedColor;
EditText editText;
Button btn_red, btn_blue, btn_green, btn_save, btn_remove;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.editText);
btn_red = findViewById(R.id.btn_red);
btn_blue = findViewById(R.id.btn_blue);
btn_green = findViewById(R.id.btn_green);
btn_save = findViewById(R.id.btn_save);
btn_remove = findViewById(R.id.btn_remove);
// 버튼이벤트
setListenerColorbtn();
setListenerPreferencebtn();
// 객체 초기화
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
// 데이터 초기화값 지정
initializeValue();
}
-
글씨 색 변경 버튼 이벤트 리스너
// EditText의 글자색 변경
private void setListenerColorbtn() {
View.OnClickListener Listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_red:
SelectedColor = Color.RED; //데이터에 글씨색도 저장하기 위한 값
editText.setTextColor(Color.RED);
break;
case R.id.btn_blue:
SelectedColor = Color.BLUE; //데이터에 글씨색도 저장하기 위한 값
editText.setTextColor(Color.BLUE);
break;
case R.id.btn_green:
SelectedColor = Color.GREEN; //데이터에 글씨색도 저장하기 위한 값
editText.setTextColor(Color.GREEN);
break;
}
}
};
btn_red.setOnClickListener(Listener);
btn_blue.setOnClickListener(Listener);
btn_green.setOnClickListener(Listener);
-
SharedPreferences 데이터 저장 및 제거 버튼 이벤트 리스너
// 데이터 저장 & 제거 이벤트
private void setListenerPreferencebtn() {
View.OnClickListener Listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_save:
Toast.makeText(getApplicationContext(), "저장완료", Toast.LENGTH_SHORT).show();
editor.putInt("color", SelectedColor);
editor.putString("text", editText.getText().toString());
editor.apply();
break;
case R.id.btn_remove:
Toast.makeText(getApplicationContext(), "제거완료", Toast.LENGTH_SHORT).show();
editor.remove("color");
editor.remove("text");
editor.apply();
break;
}
}
};
btn_save.setOnClickListener(Listener);
btn_remove.setOnClickListener(Listener);
-
SharedPreferences 데이터 가져오기
// 데이터가져오기
private void initializeValue() {
editText.setText(preferences.getString("text", ""));
editText.setTextColor(preferences.getInt("color", Color.BLACK));
▼ preferences의 첫번째 인자는 가져 올 데이터의 key값이고, 두번째 인자는 key값에 해당하는 데이터가 없을 경우 default로 가져올 데이터 값을 지정해준다.
3. 결과화면
-
EditText에 데이터를 입력하고 색상 변경 버튼을 누르면 EditText의 글자색이 변경되고, 저장하기 버튼을 통해 데이터를 저장시킬 수 있다. 앱을 재실행 시켰을 때는 저장했던 데이터가 호출되어 화면에 표시된다.