티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to manage startActivityForResult on Android

Android에서 startActivityForResult를 관리하는 방법

 문제 내용 

In my activity, I'm calling a second activity from the main activity by startActivityForResult. In my second activity, there are some methods that finish this activity (maybe without a result), however, just one of them returns a result.

액티비티를 시작할 때 메인 액티비티에서 두 번째 액티비티를 호출합니다. 두 번째 액티비티에서는 이 액티비티를 완료하는 몇 가지 방법이 있지만(결과가 없을 수도 있음), 그 중 하나만 결과를 반환합니다.

 

For example, from the main activity, I call a second one. In this activity, I'm checking some features of a handset, such as does it have a camera. If it doesn't have then I'll close this activity. Also, during the preparation of MediaRecorder or MediaPlayer if a problem happens then I'll close this activity.

예를 들어, 메인 액티비티에서 저는 두 번째 액티비티를 부릅니다. 이 액티비티에서는 카메라가 장착되어 있는지 등 디바이스의 몇 가지 기능을 확인하고 있습니다. 그렇지 않으면 이 액티비티는 종료합니다. 또한 MediaRecorder 또는 MediaPlayer를 준비하는 동안 문제가 발생하면 이 액티비티를 종료합니다.

 

If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I'll send the result (address of the recorded video) back to the main activity.

디바이스에 카메라가 있고 녹화가 완료된 경우 동영상을 녹화한 후 완료 버튼을 클릭하면 결과(녹화된 동영상의 주소)를 메인 액티비티로 다시 전송합니다.

 

How do I check the result from the main activity?

메인 액티비티의 결과를 어떻게 확인합니까?

 

 

 

 높은 점수를 받은 Solution 

From your FirstActivity, call the SecondActivity using the startActivityForResult() method.

첫번째 액티비티에서 startActivityForResult() 메서드를 사용하여 두 번째 액티비티를 호출합니다.

 

For example:

예:
int LAUNCH_SECOND_ACTIVITY = 1
Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, LAUNCH_SECOND_ACTIVITY);

 

In your SecondActivity, set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

두 번째 액티비티에서 첫 번째 액티비티로 되돌리려는 데이터를 설정합니다. 돌아가고 싶지 않다면, 아무것도 설정하지 마세요.

 

For example: In SecondActivity if you want to send back data:

예: 두 번째 액티비티에서 데이터를 다시 전송하려면 다음을 수행합니다.
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

 

If you don't want to return data:

데이터를 반환하지 않으려면:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

 

Now in your FirstActivity class, write the following code for the onActivityResult() method.

이제 첫 번째 액티비티 클래스에서 onActivityResult() 메서드에 대해 다음 코드를 작성합니다.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == LAUNCH_SECOND_ACTIVITY) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            // Write your code if there's no result
        }
    }
} //onActivityResult

 

To implement passing data between two activities in a much better way in Kotlin, please go through 'A better way to pass data between Activities'.

Kotlin에서 두 액티비티 간에 데이터를 전달하는 훨씬 나은 방법으로 구현하려면 '액티비티 간에 데이터를 전달하는 더 나은 방법'을 참조하십시오.

 

 

 

 가장 최근 달린 Solution 

In Kotlin

코틀린의 경우

 

Suppose A & B are activities the navigation is from A -> B We need the result back from A <- B

A 및 B가 A -> B에서 실행되는 액티비티라고 가정합니다. 우리는 A <- B로부터 결과를 돌려받아야 합니다.

 

in A

A에서
    // calling the Activity B
    resultLauncher.launch(Intent(requireContext(), B::class.java))

    // we get data in here from B
    private var resultLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                result.data?.getStringExtra("VALUE")?.let {
                    // data received here
                }
            }
            Activity.RESULT_CANCELED -> {
                // cancel or failure
            }
        }
    }

 

In B

B에서
    // Sending result value back to A
    if (success) {
       setResult(RESULT_OK, Intent().putExtra("VALUE", value))
    } else {
       setResult(RESULT_CANCELED)
    }

 

 

출처 : https://stackoverflow.com/questions/10407159/how-to-manage-startactivityforresult-on-android

반응형
댓글
공지사항
최근에 올라온 글