Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 SharedPreferences 사용법 완벽 가이드 – 로그인 정보 저장 예제

SharedPreferences란 무엇인가?

SharedPreferences는 안드로이드에서 가장 기본적인 데이터 저장 방식으로, 사용자 이름·비밀번호·앱 설정 같은 간단한 데이터를 키-값(key-value) 쌍 형태로 앱 내부에 영구적으로 저장합니다. 이 튜토리얼에서는 로그인 화면에 '자격 증명 기억하기' 기능을 구현하면서 SharedPreferences의 실전 활용법을 단계별로 살펴봅니다.

1단계: 새 프로젝트 만들기

Android Studio에서 File → New Project를 선택하고, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml에 아래 코드를 추가합니다. 이름과 비밀번호를 입력받는 EditText 두 개, 로그인 버튼, 그리고 체크박스로 구성된 화면입니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/etName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:layout_marginTop="75dp"
        android:hint="이름 입력"/>
    <EditText
        android:id="@+id/etPassword"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/etName"
        android:ems="10"
        android:layout_centerHorizontal="true"
        android:hint="비밀번호 입력"/>
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로그인"
        android:layout_below="@id/etPassword"
        android:layout_alignStart="@id/etPassword"
        android:layout_marginTop="10dp" />
    <CheckBox
        android:id="@+id/checkBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btnLogin"
        android:layout_marginTop="10dp"
        android:text="자격 증명 기억하기"
        android:layout_alignStart="@id/btnLogin"/>
</RelativeLayout>

3단계: MainActivity 작성

src/MainActivity.java에 다음 코드를 추가합니다. 로그인 버튼 클릭 시 체크박스 상태에 따라 이름과 비밀번호를 SharedPreferences에 저장하거나 삭제하며, 앱 시작 시 저장된 값을 불러와 화면에 복원합니다.

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    EditText name, password;
    Button button;
    CheckBox checkBox;
    String strName, strPassword, strCheckBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = findViewById(R.id.etName);
        password = findViewById(R.id.etPassword);
        button = findViewById(R.id.btnLogin);
        checkBox = findViewById(R.id.checkBox);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        editor = sharedPreferences.edit();
        checkSharedPreference();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkBox.isChecked()) {
                    editor.putString(getString(R.string.checkBox), "True");
                    editor.commit();
                    strName = name.getText().toString();
                    editor.putString(getString(R.string.name), strName);
                    editor.commit();
                    strPassword = password.getText().toString();
                    editor.putString(getString(R.string.password), strPassword);
                    editor.commit();
                } else {
                    editor.putString(getString(R.string.checkBox), "False");
                    editor.commit();
                    editor.putString(getString(R.string.name), "");
                    editor.commit();
                    editor.putString(getString(R.string.password), "");
                    editor.commit();
                }
            }
        });
    }

    private void checkSharedPreference() {
        strCheckBox = sharedPreferences.getString(getString(R.string.checkBox), "False");
        strName = sharedPreferences.getString(getString(R.string.name), "");
        strPassword = sharedPreferences.getString(getString(R.string.password), "");
        name.setText(strName);
        password.setText(strPassword);
        if (strCheckBox.equals("True")) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }
    }
}

4단계: 문자열 리소스 등록

res/values/strings.xml 파일을 열고 아래 코드를 추가합니다. SharedPreferences에 저장될 키들을 문자열 리소스로 관리하면 유지보수가 훨씬 편리합니다.

<resources>
    <string name="app_name">Sample</string>
    <string name="checkBox">Sample.checkbox</string>
    <string name="name">Sample.name</string>
    <string name="password">Sample.password</string>
</resources>

5단계: AndroidManifest.xml 설정

androidManifest.xml에 아래 코드를 추가합니다. 이 예제는 특별한 권한 없이 앱 내부 저장소만 사용하므로 별도의 permission 선언은 필요하지 않습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결한 상태라고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 실행(Run) 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택하세요. 기기에 아래와 같은 기본 화면이 표시됩니다.

안드로이드 SharedPreferences 사용법 완벽 가이드 – 로그인 정보 저장 예제

추가 팁: commit() vs apply()

  • commit(): 동기 방식으로 저장 결과를 boolean 값으로 반환합니다. 저장 완료 여부가 필요한 경우에 적합하지만, UI 스레드에서는 성능 저하가 있을 수 있습니다.
  • apply(): 비동기 방식으로 디스크에 기록하며 즉시 메모리에 반영되므로, 일반적으로 apply() 사용이 권장됩니다.

참고 사항

최신 Android SDK에서는 PreferenceManager.getDefaultSharedPreferences()가 deprecated되었습니다. 새 프로젝트에서는 getSharedPreferences("파일명", MODE_PRIVATE) 방식을 사용하거나, Jetpack의 DataStore 라이브러리 도입을 검토하는 것이 좋습니다.