[Android] 앱 내에 간단한 데이터 저장하기(SharedPreferences)

Android/Android · 2020. 6. 12. 14:36
반응형

https://survivalcoding.com/p/android_basic

 

될 때까지 안드로이드

될 때까지 안드로이드에 수록된 예제의 라이브 코딩 해설

survivalcoding.com

위 서적을 참고하였습니다.

 

 

 

 이번 포스트에선 앱에 간단한 데이터(text 등)를 저장하는 방법에 대해 설명하겠습니다. 이를 사용하려면 SharedPreferences 객체를 만들어야 합니다. 바로 간단한 앱을 만들어 보겠습니다.

 

 

 activity_main.xml

<?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"
    android:orientation="vertical">

    <EditText
        android:id="@+id/id"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="이메일을 입력하세요"/>

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="비밀번호를 입력하세요"/>

    <CheckBox
        android:id="@+id/checkbox"
        android:text="이메일 저장"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/login"
        android:text="로그인"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

 

MainActivity.java

package hello.world.study;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class MainActivity extends AppCompatActivity {

    private EditText emailEdit;
    private CheckBox checkBox;
    //데이터 저장 객체
    private SharedPreferences preferences;

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

        emailEdit = (EditText) findViewById(R.id.id);
        checkBox = (CheckBox) findViewById(R.id.checkbox);
        //preferences 초기화
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        //저장된 이메일 복원
        Boolean isChecked = preferences.getBoolean("save", false);
        checkBox.setChecked(isChecked);
        if(isChecked) {
            String email = preferences.getString("email","");
            emailEdit.setText(email);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //ShaeredPreferences의 수정 가능한 객체 얻기
        SharedPreferences.Editor editor = preferences.edit();
        //저장할 데이터
        editor.putBoolean("save", checkBox.isChecked());
        editor.putString("email", emailEdit.getText().toString());
        //저장
        editor.apply();
    }
}

 

 정말 간단한 앱인데요, 여기서 체크박스에 체크하시고, 아이디를 입력하고 앱을 재시작하면 아이디가 저장되어있는 것을 볼 수 있습니다. 여기서 주의해야 하실 것이 SharedPreferences는 기기 내에 데이터를 저장(패키지 이름으로 저장)하기 때문에, 앱을 삭제하거나 데이터 지우기를 사용하시면 저장했던 것들이 사라지니 이 점 꼭 유의하시기 바랍니다.

 

 간단하게 앱에서 데이터를 기억하는 방법에 대해 알아봤습니다. 감사합니다.

반응형