Read More
Read now

ActivityResultContract the new way

Save

As we already know the startActivityForResult method is now deprecated which was used for passing data and, getting responses between two activities. We previously got the response on the onActivityResult() method which we used always until now.

OntActivityResult() the old way

for example to get response on the activity we used the below logic:

To Start the Activity We used:

ActivityResultContract the New way

The new way to get the result back to your main activity or ask for permission with the help of the below example.

First, let’s create the POJO class we will use to pass our data to the main activity ContactDetail.kt:

Now we will add the layout design for our contact adding page at activity_contact.xml:

Now the Activity code for our ContactActivity.kt:

In above code, I have added a inner class to which is extendending the abstract ActivityResultContract class. In this, the two parameters are used 1st as Intent and, 2nd ContactDetail.

After the input and, output type is decided then, we have to override 2 methods:

To get the result on our main activity, MainResultActivity.kt:

The layout design activity_main_result.xml:

Our Handler class having all the operation Code MainActivityResultHandler.kt:

On the handler class I have created a instance for registering the Contact Activity class. You just have to pass your custom contract and, callback into register For Activity Result.

Now there is no nested code anymore and, you don’t have to add result code constant because, it will be maintained by Contact Activity class.

Requesting for Permission

Now we don’t have to code extra for asking the permission, it can also be maintained by the register For Activity Result method

Therefore, requesting permission will be easier than before. Request Permission method and, Request Multiple Permission method contract are now used to ask for permission request.

I have provided the example for the single permission on the above code to ask for multiple permission then you just have to make only 2 changes:


To ask for multiple permission then you just have to make only 2 changes:

The above example Result will be:

. . . . . . . . .

This is it on passing and getting the response between activities and permission. You can also check the official documentation provided by Google for more detail: Click Here.

That’s it from my side for today, thanks for reading it until now. You can check our other android blogs Click Here.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!

Deniel Kerr

Owner and Founder. Opencart

Talk to Sales
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home