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

안드로이드에서 SharedPreferences로 데이터를 저장하고 불러오는 방법 완벽 가이드

이 튜토리얼에서는 안드로이드 앱에서 SharedPreferences를 사용해 사용자 데이터(이름, 이메일 등)를 저장하고, 저장된 값을 다시 불러오고, 필요할 때 삭제하는 방법을 단계별로 알아봅니다. SharedPreferences는 간단한 키-값(key-value) 형태의 데이터를 로컬에 영구적으로 보관할 때 가장 널리 쓰이는 방식입니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 생성에 필요한 모든 세부 정보를 입력해 주세요.

2단계: 레이아웃 파일 작성 (activity_main.xml)

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이름과 이메일을 입력받는 EditText 두 개와, 저장(Save), 삭제(Clear Data), 불러오기(Retrieve Data) 기능을 담당하는 버튼 세 개로 구성되어 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress" />
    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="text" />
    <Button
        android:layout_marginTop="50dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Save"
        android:text="Save" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Clear"
        android:text="Clear Data" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="Retrieve"
        android:text="Retrieve Data" />
</LinearLayout>

3단계: 메인 액티비티 구현 (MainActivity.java)

src/MainActivity.java 파일에 아래 코드를 추가합니다. 핵심 로직은 다음과 같습니다.

  • onCreate(): 앱 시작 시 SharedPreferences에 저장된 값이 있으면 자동으로 화면에 표시합니다.
  • Save(): 입력된 이름과 이메일을 SharedPreferences에 저장합니다.
  • Retrieve(): 저장된 데이터를 다시 읽어와 화면에 출력합니다.
  • Clear(): 화면의 입력값을 비워줍니다.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    EditText etName, etEmail;
    SharedPreferences sharedPreferences;
    public static final String myPreference = "myPref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etName = findViewById(R.id.etName);
        etEmail = findViewById(R.id.etEmail);
        sharedPreferences = getSharedPreferences(myPreference, Context.MODE_PRIVATE);
        if (sharedPreferences.contains(Name)) {
            etName.setText(sharedPreferences.getString(Name, ""));
        }
        if (sharedPreferences.contains(Email)) {
            etEmail.setText(sharedPreferences.getString(Email, ""));
        }
    }
    public void Clear(View view) {
        etName = findViewById(R.id.etName);
        etEmail = findViewById(R.id.etEmail);
        etName.setText("");
        etEmail.setText("");
        Toast.makeText(MainActivity.this, "Cleared", Toast.LENGTH_LONG).show();
    }
    public void Retrieve(View view) {
        etName = findViewById(R.id.etName);
        etEmail = findViewById(R.id.etEmail);
        sharedPreferences = getSharedPreferences(myPreference, Context.MODE_PRIVATE);
        if (sharedPreferences.contains(Name)) {
            etName.setText(sharedPreferences.getString(Name, ""));
        }
        if (sharedPreferences.contains(Email)) {
            etEmail.setText(sharedPreferences.getString(Email, ""));
        }
        Toast.makeText(MainActivity.this, "Retrieved", Toast.LENGTH_LONG).show();
    }
    public void Save(View view) {
        String name = etName.getText().toString();
        String email = etEmail.getText().toString();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(Name, name);
        editor.putString(Email, email);
        editor.apply();
        Toast.makeText(MainActivity.this, "Saved", Toast.LENGTH_LONG).show();
    }
}

4단계: 매니페스트 설정 (AndroidManifest.xml)

androidManifest.xml 파일에 아래 코드를 추가합니다. MainActivity가 앱의 런처(Launcher) 액티비티로 등록되어 있는지 확인하세요.

<?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로 데이터를 저장하고 불러오는 방법 완벽 가이드

안드로이드에서 SharedPreferences로 데이터를 저장하고 불러오는 방법 완벽 가이드

마무리 정리

이 예제를 통해 배운 핵심 내용은 다음과 같습니다.

  • getSharedPreferences(name, mode)로 SharedPreferences 인스턴스를 가져올 수 있습니다.
  • edit().putString(key, value).apply() 메서드 체인으로 데이터를 저장합니다.
  • getString(key, defaultValue)로 저장된 값을 읽어옵니다.
  • contains(key)로 특정 키의 존재 여부를 확인할 수 있습니다.

SharedPreferences는 로그인 상태 유지, 사용자 환경설정 저장 등 소량의 데이터를 다룰 때 매우 유용하니, 실제 프로젝트에도 적극 활용해 보시기 바랍니다.