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

Android 앱에서 SharedPreferences 데이터를 삭제하는 방법

이 글에서는 Android 앱에서 SharedPreferences에 저장된 데이터를 삭제하는 방법을 단계별로 알아봅니다. SharedPreferences는 사용자 설정이나 간단한 값을 기기에 영구적으로 저장할 때 유용하지만, 필요 없어진 데이터를 제거하는 것도 마찬가지로 중요합니다.

Step 1 — 새 프로젝트 생성하기

Android Studio에서 File ⇒ New Project를 선택한 뒤, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.

Step 2 — 레이아웃 파일 작성하기

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면에는 저장된 값과 함께 'Delete Shared Preference' 버튼이 세로로 배치됩니다.

<?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:gravity="center"
    android:orientation="vertical"
    android:padding="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dp"
        android:textAlignment="center"
        android:textSize="20sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete Shared Preference" />

    <TextView
        android:id="@+id/tvAfterChange"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textAlignment="center"
        android:textSize="20sp"
        android:textStyle="bold" />
</LinearLayout>

Step 3 — 문자열 리소스 정의하기

SharedPreferences에 저장할 키 값을 관리하기 위해 res/values/strings.xml에 다음 항목을 추가합니다. 키를 하드코딩하지 않고 리소스로 분리하면 유지보수가 훨씬 쉬워집니다.

<resources>
    <string name="app_name">Sample</string>
    <string name="sharedPref_key_player">player_name</string>
    <string name="sharedPref_key_country">country_name</string>
</resources>

Step 4 — 메인 액티비티 구현하기

src/MainActivity.java에 아래 코드를 작성합니다. 먼저 두 개의 문자열 값을 SharedPreferences에 저장한 뒤, 버튼을 클릭하면 editor.remove() 메서드로 특정 키의 데이터를 삭제하고 그 결과를 화면에 출력합니다.

핵심 포인트는 다음 두 줄입니다:

  • remove(String key) — 지정한 키에 해당하는 값만 삭제합니다.
  • apply() — 변경 사항을 비동기적으로 디스크에 반영합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView textView, tvAfterDelete;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    Button button;

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

        textView = findViewById(R.id.textView);
        tvAfterDelete = findViewById(R.id.tvAfterChange);
        button = findViewById(R.id.button);

        sharedPreferences = getPreferences(Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        // 초기 데이터 저장
        editor.putString(getResources().getString(R.string.sharedPref_key_player), "Cristiano Ronaldo");
        editor.putString(getResources().getString(R.string.sharedPref_key_country), "Portugal");
        editor.apply();

        // 저장된 값 읽어오기
        String country = sharedPreferences.getString(
                getResources().getString(R.string.sharedPref_key_country), "");
        String player = sharedPreferences.getString(
                getResources().getString(R.string.sharedPref_key_player), "");

        textView.setText("SharedPreferences Values\n");
        textView.setText(textView.getText() + "Country : " + country + "\nPlayer : " + player);

        // 버튼 클릭 시 특정 키의 데이터 삭제
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor.remove(getResources().getString(R.string.sharedPref_key_country));
                editor.apply();

                String countryNow = sharedPreferences.getString(
                        getResources().getString(R.string.sharedPref_key_country), "");
                String playerNow = sharedPreferences.getString(
                        getResources().getString(R.string.sharedPref_key_player), "");

                tvAfterDelete.setText("SharedPreferences Values - After Removing Country\n");
                tvAfterDelete.setText(tvAfterDelete.getText()
                        + "Country : " + countryNow + "\nPlayer : " + playerNow);
            }
        });
    }
}

Step 5 — 매니페스트 설정하기

androidManifest.xml은 기본 생성된 내용을 그대로 사용하면 됩니다.

<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(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면, 앱이 설치되고 아래와 같은 초기 화면이 표시됩니다.

Android 앱에서 SharedPreferences 데이터를 삭제하는 방법

버튼을 누르면 'country_name' 키의 값이 삭제되어 빈 문자열로 표시되는 것을 확인할 수 있습니다. 이처럼 remove() 메서드를 활용하면 특정 키만 골라서 삭제할 수 있으며, 만약 저장된 모든 데이터를 한 번에 지우고 싶다면 editor.clear()를 호출한 후 apply()하면 됩니다.