이 글에서는 인텐트(Intent)를 사용해 안드로이드에서 한 액티비티(Activity)에서 다른 액티비티로 데이터를 전달하는 방법을 단계별로 알아봅니다.
인텐트는 안드로이드의 핵심 구성 요소 중 하나로, 액티비티 간 화면 전환을 요청하는 메시징 객체입니다. 여기에 putExtra() 메서드로 키-값 형태의 부가 데이터를 담으면, 대상 액티비티에서 그 값을 꺼내 사용할 수 있습니다. 이번 예제에서는 첫 번째 화면에서 입력한 텍스트를 두 번째 화면으로 전달해 표시하는 간단한 앱을 만들어 보겠습니다.
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.java 작성
버튼을 클릭하면 EditText에 입력된 값을 읽어와 인텐트에 담은 후 SecondActivity를 시작합니다. 데이터를 담을 때는 반드시 putExtra()를 사용해야 하며, 잘못된 메서드를 쓰면 컴파일 오류가 발생합니다.
package com.example.myapplication;
import android.content.Intent;
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();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("value", value);
startActivity(intent);
}
});
}
}
참고: 최신 프로젝트에서는 android.support.v7.app.AppCompatActivity 대신 androidx.appcompat.app.AppCompatActivity를 사용하는 것이 좋습니다.
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.java 작성
getIntent().getExtras()로 전달된 데이터 묶음(Bundle)을 꺼낸 뒤, "value" 키에 해당하는 문자열을 TextView에 설정합니다. 값이 없는 경우를 대비해 null 검사도 함께 처리합니다.
package com.example.myapplication;
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);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String value = bundle.getString("value");
TextView textView = findViewById(R.id.text_view);
textView.setText(value);
}
}
}
6단계 — AndroidManifest.xml에 액티비티 등록
새로 만든 SecondActivity는 매니페스트에 반드시 등록해야 합니다. 등록하지 않으면 해당 액티비티를 시작하는 순간 ActivityNotFoundException 오류가 발생합니다.
<?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(실행) 아이콘을 클릭하세요. 목록에서 본인의 모바일 기기를 선택하면 앱이 설치·실행되고, 아래와 같은 기본 화면이 나타납니다.

텍스트를 입력하고 Next 버튼을 누르면, 입력한 값이 인텐트를 통해 두 번째 화면으로 전달되어 화면에 표시되는 것을 확인할 수 있습니다.
