메뉴 건너뛰기

?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

1. 액티비티 간에 데이터 전달방법

저번 포스팅에서 액티비티를 실행할 때 인텐트(Intent)를 생성하여 사용했습니다. 실행되는 액티비티에 데이터를 전달할 때도 마찬가지로 인텐트(Intent)를 사용하게 됩니다. 

 

 

 

 

▼ MainActivity에서 SubActivity를 실행하면서 데이터를 전달하는 대략적인 프로세스를 나타내는 그림입니다. MainActivity에서는 액티비티를 실행하기 위해서는 먼저 Intent 객체를 생성합니다. 

SubActivity에 데이터를 넘겨줄 때는 Intent 객체에 데이터를 담아 보내는데 해당 함수는 putExtra() 함수입니다. 인자 정보는 두 개로 하나는 데이터를 식별할 수 있는 키값이며 두 번째 인자는 데이터를 넘겨주게 됩니다.

 

SubActivity에서 전달받은 데이터를 가져오기 위해서는 먼저 자신을 호출한 액티비티에서 생성한 인텐트 객체를 getIntent() 함수를 통해 가져옵니다. 데이터를 가져오기 위해서는 getxxxExtra() 함수와 같이 Type에 맞는 함수를 호출하여 데이터를 가져올 수 있습니다. 

 

 

 

▼ putExtra() 함수는 두 번째 인자에 대해서 여러 Type으로 오버로딩 되어 있습니다. 

 

 

 

 


2. 액티비티 데이터 전달 예제

간단하게 MainActivity에서 SubActivity를 실행하면서 데이터를 전달하여 해당 데이터를 SubActivity에 표시하는 예제를 구현해보겠습니다. 

 

<MainActivity XML 레이아웃 리소스>

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="8dp">

        <Button
            android:id="@+id/button2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:onClick="OnClickHandler"
            android:text="Sub Activity 실행하기" />
    </LinearLayout>

<SubActivity XML 레이아웃 리소스>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />

        <TextView
            android:id="@+id/flowers"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="TextView" />
    </LinearLayout>

<MainActivity 자바 소스>

public class MainActivity extends AppCompatActivity{

    private String name;
    private ArrayList<String> flowerList;


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

        this.InitializeData();
    }

    public void InitializeData()
    {
        flowerList = new ArrayList<String>();

        flowerList.add("무궁화");
        flowerList.add("해바라기");

        this.name = "홍길동";
    }

    public void OnClickHandler(View view)
    {
        Intent intent = new Intent(this,SubActivity.class);

        intent.putExtra("name", "홍길동");
        intent.putExtra("flowers", flowerList);

        startActivity(intent);
    }
}

▼ Button 클릭에 대한 이벤트 처리를 하는 OnClickHandler() 함수내에서 액티비티 실행 및 데이터 전달을 위한 인텐트 객체를 생성하고 있습니다. 데이터 Type은 String과 ArrayList <String> 두 Type에 대한 데이터를 인텐트 객체에 담고 있습니다. 위에서 말했듯이 putExtra() 함수는 여러 Type에 대해 오버 라이딩이 되어 있기 때문에 가능한 구현 형태입니다. Intent 객체에 데이터도 담았으니 startActivity() 함수를 호출하여 액티비티를 호출합니다.

 

<SubActivity 자바 소스 코드>

public class SubActivity extends AppCompatActivity {

    private TextView textView_name;
    private TextView textView_flowers;

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

        Intent intent = getIntent();

        textView_name = (TextView)findViewById(R.id.name);
        textView_flowers = (TextView)findViewById(R.id.flowers);

        textView_name.setText(intent.getStringExtra("name"));

        ArrayList<String> flowers = intent.getStringArrayListExtra("flowers");

        textView_flowers.setText("");

        for(int i=0; i < flowers.size(); i++)
        {
            textView_flowers.setText(textView_flowers.getText() + flowers.get(i));
        }
    }

}

▼ getIntent() 함수를 호출하여 MainActivity에서 생성한 Intent 객체를 얻어옵니다. Intent 객체를 가져오게 되면 그 안에 담긴 데이터를 가져올 수 있습니다. Intent 객체는 getxxxExtra() 형태의 함수들을 제공하고 있기 때문에 데이터 Type에 따라 적절히 사용하면 됩니다. 예를 들어 String Type 데이터의 name 키값의 데이터를 가져오기 위해서는 getStringExtra("name") 같은 형태로 작성하면 됩니다.

 


List of Articles
번호 제목 날짜 조회 수
237 안드로이드 - RecyclerView 안에 RecyclerView 구현하기 file 2021.04.02 502
236 안드로이드 - Json 파싱하기 file 2021.04.02 828
235 안드로이드 - 타이머(Timer) 구현하기 2021.04.01 1368
234 안드로이드 - SQLiteDatabase 구현하기 file 2021.04.01 241
233 안드로이드 - 리사이클러 뷰(RecyclerView) 구현 file 2021.04.01 388
232 안드로이드 - 네비게이션 드로어(Navigation Drawer)를 활용하여 슬라이드 메뉴 구현하기 file 2021.04.01 1856
231 안드로이드 - 툴바(ToolBar)를 사용하여 앱바(App Bar) 구현하기 file 2021.04.01 454
230 안드로이드 - 프로그레스바(ProgressBar) 구현하기 file 2021.04.01 451
229 안드로이드 - AsyncTask 구현 예제 file 2021.04.01 280
228 안드로이드 - 액티비티(Activity)와 액티비티 생명 주기(Activity Life Cycle) file 2021.04.01 225
227 안드로이드 - 리스트뷰(ListView) 구현 file 2021.04.01 490
226 안드로이드 - 컨텍스트 메뉴(Context Menu) 사용 예제 file 2021.04.01 206
225 안드로이드 - 옵션 메뉴 (Option Menu) 구현 방법 file 2021.04.01 283
224 안드로이드 - 명시적 인텐트(Explicit Intent)와 암시적 인텐트 (Implicit Intent) file 2021.04.01 324
223 안드로이드 - 날짜 및 시간 정보 입력받기 (DatePickerDialog / TimePickerDialog) file 2021.04.01 1759
222 안드로이드 - setContentView()와 레이아웃 전개자(LayoutInflater) 2021.04.01 227
221 안드로이드 - AlertDialog 사용하여 알림창 띄우는 방법 총정리 file 2021.03.31 686
220 안드로이드 - SnackBar를 사용해 팝업창 띄우기 file 2021.03.31 281
219 안드로이드 - 토스트(Toast) 메시지 사용하기. file 2021.03.31 321
218 안드로이드 - 액티비티(Activity)로부터 결과 데이터 받아오기 file 2021.03.31 483
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 13 Next
/ 13

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved