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

안드로이드 액티비티 간 데이터 전달 방법 – Intent와 Bundle 활용 가이드

이 튜토리얼에서는 안드로이드 애플리케이션에서 Intent(인텐트)Bundle(번들)을 활용해 두 개의 액티비티(Activity) 사이에 데이터를 전달하는 방법을 단계별로 알아봅니다. 첫 번째 화면에서 사용자가 입력한 이름과 선택한 연령 그룹을 두 번째 화면으로 전달해 맞춤형 메시지를 표시하는 실전 예제를 함께 만들어 보겠습니다.

핵심 개념 이해하기

안드로이드에서 액티비티 간 데이터 전달은 기본적으로 Intent 객체를 통해 이루어집니다. Intent는 새로운 액티비티를 시작하는 역할을 하며, putExtra() 메서드를 사용해 문자열, 숫자 등 다양한 데이터를 함께 담을 수 있습니다. 특히 여러 개의 값을 한꺼번에 전달할 때는 Bundle 객체에 데이터를 묶어서 인텐트에 추가하는 방식이 코드도 깔끔해지고 유지보수에도 유리합니다.

구현 단계

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

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

2단계 — 첫 번째 화면 레이아웃 작성

res/layout/activity_first.xml 파일에 아래 코드를 추가합니다. 이름을 입력하는 EditText, 연령 그룹을 선택하는 Spinner, 제출 버튼으로 구성된 화면입니다.

<?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"
   android:id="@+id/activity_first"
   android:paddingTop="60dp"
   tools:context=".FirstActivity">
   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp">
         <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25"/>
         <EditText
            android:id="@+id/editTxtName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.75"
            android:ems="10" />
      </LinearLayout>
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp"
         android:paddingTop="16dp">
         <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25" />
         <Spinner
            android:id="@+id/ageGroupSpinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_weight="0.75"/>
      </LinearLayout>
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingTop="16dp">
         <View
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50" />
         <Button
            android:id="@+id/btnSubmit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.20"/>
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>

3단계 — 두 번째 화면 레이아웃 작성

res/layout/activity_second.xml 파일에 아래 코드를 추가합니다. 전달받은 데이터를 화면에 표시할 TextView가 포함되어 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="https://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/activity_second"
   android:paddingTop="60dp">
   <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical">
      <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal"
         android:paddingLeft="10sp">
         <TextView
            android:id="@+id/displayMsg"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.25" />
      </LinearLayout>
   </LinearLayout>
</RelativeLayout>

4단계 — FirstActivity.java 작성

src/FirstActivity.java 파일에 아래 코드를 추가합니다. 제출 버튼을 클릭하면 이름 입력값을 검증하고, 이름과 연령 그룹을 Bundle에 담아 SecondActivity로 전달하는 로직입니다.

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class FirstActivity extends AppCompatActivity {
   Button btnSubmit = null;
   EditText editTxtName = null;
   private static final String STING_EMPTY = "";
   private static int ageGroup = 0;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_first);
      btnSubmit = (Button) findViewById(R.id.btnSubmit);
      btnSubmit.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            editTxtName = (EditText) findViewById(R.id.editTxtName);
            if (STING_EMPTY.equals(editTxtName.getText().toString())) {
               Toast.makeText(FirstActivity.this, "Name Cannot be empty!",
               Toast.LENGTH_LONG).show();
            } else {
               Spinner ageGroupSpinner = (Spinner)findViewById(R.id.ageGroupSpinner);
               ageGroupSpinner.setOnItemSelectedListener(
               new AdapterView.OnItemSelectedListener() {
                  @Override
                  public void onItemSelected(AdapterView<?> adapterView, View view,
                  int i, long l) {
                     // 드롭다운에서 연령 그룹이 변경되면 해당 값을 저장합니다
                     ageGroup = i;
                  }
                  @Override
                  public void onNothingSelected(AdapterView<?> adapterView) {
                  }
               });
               // SecondActivity를 시작할 새로운 인텐트를 생성합니다
               Intent i = new Intent(FirstActivity.this,SecondActivity.class);
               // 입력값을 Bundle에 담아 SecondActivity로 전달합니다
               Bundle b = new Bundle();
               b.putString("name",editTxtName.getText().toString());
               b.putInt("ageGroup",ageGroup);
               // 인텐트에 userBundle을 설정합니다
               i.putExtra("userBundle",b);
               startActivity(i);
            }
         }
      });
   }
}

5단계 — SecondActivity.java 작성

src/SecondActivity.java 파일에 아래 코드를 추가합니다. 인텐트로 전달받은 Bundle에서 데이터를 꺼내고, 연령 그룹에 따라 다른 메시지를 조합해 화면에 출력합니다.

package com.example.sample;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      // 전달받은 인텐트를 가져옵니다
      Intent i = getIntent();
      // 인텐트 내부에 저장된 Bundle을 가져옵니다
      Bundle b = i.getBundleExtra("userBundle");
      TextView displayMsg = (TextView) findViewById(R.id.displayMsg);
      String message = "Hi, " + b.getString("name") + " ";
      int ageGroup = b.getInt("ageGroup");
      switch (ageGroup){
         case 0: message = message + "Enjoy your life";
         break;
         case 1: message = message + "Don't take life too seriously.. Have fun!";
         break;
         case 2: message = message + "Celebrate your life with old memories!";
         break;
      }
      displayMsg.setText(message);
   }
}

6단계 — AndroidManifest.xml에 액티비티 등록

Manifests/AndroidManifest.xml 파일에 아래 코드를 추가합니다. SecondActivity가 반드시 매니페스트에 등록되어 있어야 정상적으로 호출됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
   package="com.example.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=".FirstActivity">
         <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에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 상단 툴바의 안드로이드 액티비티 간 데이터 전달 방법 – Intent와 Bundle 활용 가이드 실행(Run) 아이콘을 클릭하세요. 기기 목록에서 본인의 모바일 기기를 선택하면, 아래와 같은 기본 화면이 표시됩니다.

안드로이드 액티비티 간 데이터 전달 방법 – Intent와 Bundle 활용 가이드

안드로이드 액티비티 간 데이터 전달 방법 – Intent와 Bundle 활용 가이드