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

Kotlin으로 Android 앱의 SharedPreferences 데이터 삭제하는 방법


개요

이 글에서는 Kotlin을 사용해 Android 앱의 SharedPreferences 데이터를 삭제하는 방법을 단계별로 살펴봅니다. 특정 키(key)에 해당하는 값을 제거하고, 삭제 전후의 저장된 값을 화면에 표시하는 간단한 예제 앱을 함께 만들어 보겠습니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다.

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면에는 저장된 값을 보여주는 TextView와, 데이터를 삭제하는 Button이 배치됩니다.

<?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_horizontal"
   android:orientation="vertical"
   android:padding="8dp"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="100dp"
      android:layout_marginBottom="100dp"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:id="@+id/textView"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginBottom="20dp"
      android:textAlignment="center"
      android:textColor="@android:color/background_dark"
      android:textSize="20sp"
      android:textStyle="bold" />
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      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:textColor="@android:color/holo_red_light"
      android:textSize="20sp"
      android:textStyle="bold" />
</LinearLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 앱이 시작되면 SharedPreferences에 선수 이름과 국가를 저장하고, 버튼을 클릭하면 editor.remove()를 호출해 국가(country) 키의 값을 삭제한 뒤 변경된 결과를 화면에 출력합니다.

import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var textView: TextView
   lateinit var tvAfterDelete: TextView
   lateinit var sharedPreferences: SharedPreferences
   lateinit var editor: SharedPreferences.Editor
   lateinit var button: Button
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      textView = findViewById(R.id.textView)
      tvAfterDelete = findViewById(R.id.tvAfterChange)
      button = findViewById(R.id.button)
      title = "KotlinApp"
      sharedPreferences = getPreferences(Context.MODE_PRIVATE)
      editor = sharedPreferences.edit()
      editor.putString(resources.getString(R.string.sharedPref_key_player), "Cristiano Ronaldo")
      editor.putString(resources.getString(R.string.sharedPref_key_country), "Portugal")
      editor.apply()
      val player = sharedPreferences.getString(resources.getString(R.string.sharedPref_key_player), "")
      val country = sharedPreferences.getString(resources.getString(R.string.sharedPref_key_country), "")
      textView.text = "Player : $player\nCountry : $country"
      button.setOnClickListener {
         editor.remove(resources.getString(R.string.sharedPref_key_country))
         editor.apply()
         val playerNow = sharedPreferences.getString(resources.getString(R.string.sharedPref_key_player), "")
         val countryNow = sharedPreferences.getString(resources.getString(R.string.sharedPref_key_country), "")
         tvAfterDelete.text = "Player : $playerNow\nCountry : $countryNow"
      }
   }
}

4단계: 문자열 리소스 추가 (strings.xml)

res/values/strings.xml 파일에 SharedPreferences에서 사용할 키 값을 정의합니다.

<string name="sharedPref_key_player">player_name</string>
<string name="sharedPref_key_country">country_name</string>

5단계: AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.q10">
   <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 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 앱의 기본 화면이 표시됩니다.

처음 화면에는 Player : Cristiano Ronaldo / Country : Portugal이 표시됩니다. 이후 버튼을 클릭하면 country 키의 값이 삭제되어 빈 문자열로 바뀐 것을 확인할 수 있습니다.

Kotlin으로 Android 앱의 SharedPreferences 데이터 삭제하는 방법

Kotlin으로 Android 앱의 SharedPreferences 데이터 삭제하는 방법