How to replace startActivityForResult with Activity Result APIs?
Asked Answered
I

8

72

I have a main activity which serves as an entry point to call different activities, depending on condition. Among others, I use Firebase Auth to manage user sign in:

startActivityForResult(
            AuthUI.getInstance().createSignInIntentBuilder()
                    .setAvailableProviders(providers)
                    .build(),
            RC_SIGN_IN)

I overwrite onActivityResult() to distinguish the returned intent/data, for example:

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {

        REQUEST_CODE_1 -> {
          // update UI and stuff
        }

        RC_SIGN_IN -> {
          // check Firebase log in
        }
        // ...
    }
}

With the Activity Result APIs which is strongly recommended by the documentation, I get that I should make prepareCall() before ActivityResultLauncher and to make sure the activity is in created state when I launch, but I still don't understand how to handle multiple activity results gracefully (at least, in one place) like in onActivityResult().

Looking at this article, it seems I need to implement multiple child inner classes of ActivityResultContract type (therefore multiple prepareCall()'s?), because they are suppose to be different contracts, am I correct? Can someone please show me some skeleton example that mirrors the above onActivityResult() logic?

Indiscrete answered 27/4, 2020 at 9:12 Comment(0)
G
78

You can call as many Activities for result as you wish and have separate callback for each:

val startForResult = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        //  you will get result here in result.data
    }
}

startForResult.launch(Intent(activity, CameraCaptureActivity::class.java))

You just need to specify Activity class - CameraCaptureActivity::class.java

Update (as rafael mentioned):

The prepareCall() method has been renamed to registerForActivityResult() in Activity 1.2.0-alpha04 and Fragment 1.3.0-alpha04. And it should be startForResult.launch(...) in the last line

Glyptograph answered 3/5, 2020 at 11:23 Comment(3)
What about passing 'android.content.Intent intent, int requestCode' as parameters?Ease
But, in order to send back the result from Activity2, is the same as always?: setResult(Bundle)???Rainproof
it returns result.data as nullSessler
B
52

From now, startActivityForResult() has been deprecated so use new method instead of that.

Example

public void openActivityForResult() {
    
 //Instead of startActivityForResult use this one
        Intent intent = new Intent(this,OtherActivity.class);
        someActivityResultLauncher.launch(intent);
    }


//Instead of onActivityResult() method use this one

    ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // Here, no request code
                        Intent data = result.getData();
                        doSomeOperations();
                    }
                }
            });
Bedder answered 1/10, 2020 at 13:25 Comment(7)
Try this code with google signin onActivityForResult with no luck , any suggestions?Ekaterinburg
this code worked for me; had to translate to kotlin though. thanksLeacock
Thank you for not using "var" and lambdas :)Imogen
@Imogen You're welcome! I wrote without it because its easy to understand.Bedder
i forgot what function for make the someActivityResultLauncher have result ok , what trigger on activity to set result ok ?Illustrative
what about multiple intents, please see this post #72729619Ferland
Hi, @PembaTamang please check your post. I answered thatBedder
M
24

First, don’t forget to add this to your Gradle dependency

implementation 'androidx.activity:activity-ktx:1.2.0-alpha05'
implementation 'androidx.fragment:fragment-ktx:1.3.0-alpha05'

Second, create your result contract by extending an abstract class called ActivityResultContract<I, O>. I mean the type of input and O means the type of output. And then you only need to override 2 methods

class PostActivityContract : ActivityResultContract<Int, String?>() {

    override fun createIntent(context: Context, input: Int): Intent {
        return Intent(context, PostActivity::class.java).apply {
            putExtra(PostActivity.ID, postId)
        }
    }

    override fun parseResult(resultCode: Int, intent: Intent?): String? {
        val data = intent?.getStringExtra(PostActivity.TITLE)
        return if (resultCode == Activity.RESULT_OK && data != null) data
        else null
    }
}

And finally, the last step is registering the contract to Activity. You need to pass your custom contract and callback into registerForActivityResult.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
      
        start_activity_contract.setOnClickListener {
            openPostActivityCustom.launch(1)
        }
    }
  
    // Custom activity result contract
    private val openPostActivityCustom =
        registerForActivityResult(PostActivityContract()) { result ->
            // parseResult will return this as string?                                              
            if (result != null) toast("Result : $result")
            else toast("No Result")
        }
}

For More info check this Post

Methodist answered 8/2, 2021 at 5:29 Comment(3)
Was looking for the dependencies, Thanks for adding this. Get a upvote :)Flit
Good to hear that it helped you :)Methodist
A good approach to specify the requesting Intent! Thanks!Erato
P
5

In this case, what was returned by AuthUI was already an Intent, so, we use it like in the example below.

private val startForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            when(result.resultCode){
                RESULT_OK -> {
                    val intent = result.data
                    // Handle the Intent...
                    mUser = FirebaseAuth.getInstance().currentUser
                }
                RESULT_CANCELED -> {

                } else -> {
            } }
        }

start the activity from anywhere (for example on button click) using:

 AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers)
            .build().apply {
                startForResult.launch(this)
            }
Parietal answered 19/6, 2020 at 23:29 Comment(0)
C
1

If you start an activity from a fragment and return result to the fragment, do this.

In fragment:

private lateinit var activityResult: ActivityResultLauncher<Intent>

activityResult = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == RESULT_OK) {
        val data = result.data
        doSomeOperations(data)
    }
}

SomeActivity.showScreen(activityResult, requireContext())

In activity:

// activity?.setResult(Activity.RESULT_OK) doesn't change.

companion object {

    fun showScreen(activityResult: ActivityResultLauncher<Intent>, context: Context) {
        val intent = Intent(context, SomeActivity::class.java)
        activityResult.launch(intent)
    }
}
Chemotropism answered 12/1, 2021 at 13:14 Comment(3)
what is SomeActivity.showScreen(activityResult, requireContext()) i mean what is showScreen ??? can you more describe ?Illustrative
@YogiArifWidodo, fun showScreen(activityResult: ActivityResultLauncher<Intent>, context: Context) in the 2nd part of the answer. You can open an activity SomeActivity from a fragment, do some actions and return a result from that activity to the fragment.Chemotropism
@YogiArifWidodo, forgot to say that in Activity we should return a result with setResult(RESULT_OK, data) if I remember.Chemotropism
O
1
List<AuthUI.IdpConfig> providers = Arrays.asList(
                    new AuthUI.IdpConfig.EmailBuilder().build(),
                    new AuthUI.IdpConfig.GoogleBuilder().build());

            ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Log.v("LOGIN OK", "OK Result for Login");
                }
            });
            
            launcher.launch(AuthUI.getInstance()
                    .createSignInIntentBuilder()
                    .setIsSmartLockEnabled(false)
                    .setAvailableProviders(providers)
                    .build());

See this For More Details : https://githubmemory.com/repo/firebase/FirebaseUI-Android/issues?cursor=Y3Vyc29yOnYyOpK5MjAyMS0wMy0wNVQyMjoxNzozMyswODowMM4xEAQZ&pagination=next&page=2

Ouellette answered 1/6, 2021 at 19:27 Comment(0)
M
1

Use This for Firebase AuthUI;

final ActivityResultLauncher<Intent> launcher = registerForActivityResult(
            new FirebaseAuthUIActivityResultContract(), this::onSignInResult);

    binding.loginSignup.setOnClickListener(view -> {
        List<AuthUI.IdpConfig> provider = Arrays.asList(new AuthUI.IdpConfig.EmailBuilder().build(),
                new AuthUI.IdpConfig.GoogleBuilder().build(),
                new AuthUI.IdpConfig.PhoneBuilder().build());
        Intent intent = AuthUI.getInstance()
                .createSignInIntentBuilder()
                .setIsSmartLockEnabled(false)
                .setAlwaysShowSignInMethodScreen(true)
                .setAvailableProviders(provider)
                .build();
        launcher.launch(intent);
    });


private void onSignInResult(FirebaseAuthUIAuthenticationResult result) {

    if (result.getResultCode() == RESULT_OK) {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            if (user.getMetadata() != null) {
                if (user.getMetadata().getCreationTimestamp() != user.getMetadata().getLastSignInTimestamp()) {
                    Toast.makeText(this, "Welcome Back", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
                }
                startMainActivity();
            }
        }
    } else {
        IdpResponse response = result.getIdpResponse();
        if (response == null)
            Toast.makeText(this, "Canceled By You", Toast.LENGTH_SHORT).show();
        else Log.d(TAG, "onCreate: ActivityResult" + response.getError());
    }
}

private void startMainActivity() {
    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
    startActivity(intent);
    finish();
}

Like This.

Mccrary answered 1/8, 2021 at 4:21 Comment(0)
M
0
public void openSomeActivityForResult() {
    someActivityResultLauncher.launch(AuthUI.getInstance().createSignInIntentBuilder()
                .setAvailableProviders(providers)
                .build());
}

// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    // There are no request codes
                    Intent data = result.getData();
                    doSomeOperations();
                }
                else if(result.getResultCode() == Activity.RESULT_CANCELED) {
                    // code for cancelled result here
                }
            }
        });
Mcginty answered 20/2, 2023 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.