ruriruriya

[Android] 안드로이드 - 액티비티 간의 양방향 데이터 전달방법 본문

🤖Android

[Android] 안드로이드 - 액티비티 간의 양방향 데이터 전달방법

루리야ㅑ 2023. 12. 27. 10:28
반응형

안드로이드 앱 개발 시 데이터 전달은 단방향도 가능하지만 양방향도 가능하다.

첫 번째 Activity에서 두 번째 Activity로 데이터를 보낸 후 
두 번째 Activity에서 나이에 10을 더 해서 첫 번째 Activity로 보내보자.

 

1. 첫번 째 Activity -> 두 번째 Activity

첫 번째 Activity에서 이름과 나이를 받아온다.

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("name", name);
intent.putExtra("age", age);
launcher.launch(intent); // 양방향으로 보낼 때

 

2. 두 번째 Activity -> 첫 번째 Activity

두 번째 Activity에서 데이터를 받은 후
back 버튼을 누르면 나이에 +10을 한 뒤 다시 첫번 째 Activity로 보낸다.

		String name = getIntent().getStringExtra("name");
        age = getIntent().getIntExtra("age",0);

        txtName.setText(name);
        txtAge.setText(""+age);
        
                // Back 버튼 눌렀을 때 호출되는 함수

        getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                // 백버튼 눌렀을 때 하고 싶은 코드 작성.

                // 메인 Activity로, 나이 + 10한 수를 보내기.

                age = age+10;

                Intent intent = new Intent(); // 파라미터 안씀. 앞에 나와 있어서 back 버튼을 누르면 들어가기 때문.
                // 데이터만 담아서 보낼거임.
                intent.putExtra("age",age);
                setResult(100,intent);
                // RESULT_CANCELED, RSULT_OK... 안드로이드 제공 나머이 http 에러코드 참고.

                finish(); // Activity가 사라져야 한다.

            }
        });

 

3. 두번 째 Activity에서 받아 온 값 첫번 째 Activity에서 나타내기

내가 실행한 Activity로 부터 데이터를 다시 받아 10이 더해진 나이 값을 출력한다.

    ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult o) {
            if(o.getResultCode() == 100){
                int age = o.getData().getIntExtra("age",0);
                txtFuture.setText("10년 후의 나이는 : " + age);
            }
        }
    });
반응형