안드로이드 스튜디오

안드로이드 스튜디오 데이터 저장하기 (SharedPreferences)

;세미콜론; 2020. 5. 3. 11:50
반응형
<?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"
    tools:context=".MainActivity">

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

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="패스워드를 입력하세요"
        android:inputType="textPassword" />

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

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="로그인" />
</LinearLayout>
package com.example.savedata;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText myemail;
    private CheckBox mysavecheck;

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

        myemail = (EditText) findViewById(R.id.email);
        mysavecheck = (CheckBox) findViewById(R.id.save);

        myPre = PreferenceManager.getDefaultSharedPreferences(this);
        //객체 초기화

        Boolean isChecked = myPre.getBoolean("save",false);
        mysavecheck.setChecked(isChecked);
        if (isChecked){
            String email = myPre.getString("email","");
            myemail.setText(email);
        } //저장된 이메일 다시 불러오기
    }

    @Override
    protected void onDestroy() { //액티비티가 종료될 때 호출되는 콜백 메서드
        super.onDestroy();

        SharedPreferences.Editor editor = myPre.edit();//객체 생성
        editor.putBoolean("save",mysavecheck.isChecked());
        editor.putString("email",myemail.getText().toString());//저장 내용
        editor.apply();// 저장
    }
}

 

 

반응형