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

안드로이드에서 SharedPreferences(공유 환경 설정)로 액티비티 간 데이터 전달하기

안드로이드 앱을 개발하다 보면 한 화면(액티비티)에서 입력한 데이터를 다른 화면으로 넘겨야 하는 경우가 자주 있습니다. 일반적으로는 Intent의 extras를 사용하지만, 이번 예제에서는 SharedPreferences(공유 환경 설정)를 활용해 액티비티 간에 데이터를 전달하는 방법을 단계별로 알아보겠습니다.

SharedPreferences는 키-값(key-value) 형태로 간단한 데이터를 저장할 수 있는 API로, 저장된 데이터는 같은 앱 내에서 어디서든 읽고 쓸 수 있기 때문에 액티비티 사이의 데이터 공유에도 활용할 수 있습니다.

1단계 — 새 프로젝트 생성

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

2단계 — 메인 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. EditText로 사용자 입력을 받고, 버튼을 누르면 다음 화면으로 이동하는 구조입니다.

<?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:layout_margin = "16dp"
   android:orientation = "vertical"
   tools:context = ".MainActivity">
   <EditText
      android:id = "@+id/edit_text"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_gravity = "center"
      android:hint = "Enter something to pass"
      android:inputType = "text" />
   <Button
      android:id = "@+id/button"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:layout_gravity = "center"
      android:layout_marginTop = "16dp"
      android:text = "Next" />
</LinearLayout>

3단계 — MainActivity 작성

src/MainActivity.java에 아래 코드를 추가합니다. 버튼 클릭 시 EditText의 값을 SharedPreferences에 "value"라는 키로 저장한 뒤, SecondActivity로 화면을 전환합니다.

package com.example.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final EditText editText = findViewById(R.id.edit_text);
      Button button = findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String value = editText.getText().toString().trim();
            SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("value", value);
            editor.apply();
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            startActivity(intent);
         }
      });
   }
}
핵심 포인트: getSharedPreferences("myKey", MODE_PRIVATE)로 "myKey"라는 이름의 프리퍼런스 파일을 생성하고, editor.putString()apply()를 호출해야 실제로 저장됩니다.

4단계 — 두 번째 레이아웃 작성

res/layout/activity_second.xml 파일에 아래 코드를 추가합니다. 전달받은 값을 표시할 TextView 하나만 배치합니다.

<?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:layout_margin = "16dp"
   android:orientation = "vertical"
   tools:context = ".SecondActivity">
   <TextView
      android:id = "@+id/text_view"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_gravity = "center" />
</LinearLayout>

5단계 — SecondActivity 작성

src/SecondActivity.java에 아래 코드를 추가합니다. onCreate()에서 같은 "myKey" 프리퍼런스를 열어 "value" 키로 저장된 문자열을 읽어와 TextView에 출력합니다.

package com.example.myapplication;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      TextView textView = findViewById(R.id.text_view);
      SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
      String value = sharedPreferences.getString("value","");
      textView.setText(value);
   }
}

6단계 — 매니페스트 등록

AndroidManifest.xml에 SecondActivity를 반드시 등록해야 합니다. 등록하지 않으면 액티비티 전환 시 앱이 강제 종료됩니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
   package = "com.example.myapplication">
   <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>
      <activity android:name = ".SecondActivity"></activity>
   </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 실행 옵션에서 연결된 모바일 기기를 선택하면, 기본 화면이 표시됩니다.

안드로이드에서 SharedPreferences(공유 환경 설정)로 액티비티 간 데이터 전달하기

첫 번째 화면에 원하는 텍스트를 입력하고 Next 버튼을 누르면, 해당 값이 SharedPreferences에 저장되고 두 번째 화면에서 동일한 값이 그대로 출력되는 것을 확인할 수 있습니다.