<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Leonid Belyakov on Medium]]></title>
        <description><![CDATA[Stories by Leonid Belyakov on Medium]]></description>
        <link>https://medium.com/@lenyabelyakov?source=rss-da6fa65d21d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-OrEYGtreUKjDbHTSnM-NQ.png</url>
            <title>Stories by Leonid Belyakov on Medium</title>
            <link>https://medium.com/@lenyabelyakov?source=rss-da6fa65d21d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:54:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lenyabelyakov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The right way to get a result. Part 2. Fragment Result API]]></title>
            <link>https://medium.com/e-legion/getting-the-result-right-part-2-fragment-result-api-1a17f99490dc?source=rss-da6fa65d21d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a17f99490dc</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Leonid Belyakov]]></dc:creator>
            <pubDate>Mon, 31 May 2021 08:27:05 GMT</pubDate>
            <atom:updated>2021-05-31T13:01:07.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MX8AYVjiroArN6AouD-afg.png" /></figure><p>We continue the story about the Jetpack library’s latest updates that are designed to simplify data exchange between different parts of Android apps. <a href="https://medium.com/e-legion/the-right-way-to-get-a-result-part-i-activity-result-api-6efbcaa5600d">The first part</a> was about data transfer between Activities via the new Activity Result Api.</p><p>This time, we’ll cover the Fragment-based solution offered by Google. Due to the popularity of the Single Activity pattern, working with fragments is of great practical interest to many Android developers.</p><p>“How to transfer data between two Fragments?” — is a frequent job interview question. It can have various answers: creating a common ViewModel, implementing the interface in the Activity, using the targetFragment or some other methods.</p><p>As the Fragment Result Api was released, a simple way of transferring a small amount of information from one fragment to another has been added to this list. For example, returning the result of some user scenarios. We’ll describe how to bring the new Api to practice, but first, a bit of theory.</p><h3>Theory</h3><p>Since version 1.3.0-alpha04, FragmentManager implements the <em>FragmentResultOwner </em>interface. This means that FragmentManger is a dispatcher for the results sent by the fragments. Because of this, fragments can exchange information without direct lisnks to each other.</p><p>All the interaction occurs through the FragmentManager:</p><ul><li>If a fragment expects to receive some data from another fragment, it must register a listener in the FragmentManger using the <em>setFragmentResultListener()</em> method.</li><li>If a fragment needs to send a result to another fragment, it passes a Bundle object with the information to FragmentManger. The <em>setFragmentResult() </em>method is called to do this.</li><li>In order for FragmentManger to know how to relate the Bundle with the relevant listener, you must specify a string key when registering the listener and when transmitting the result.</li></ul><p>In a simplified way, the result-passing scheme can be represented like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*1mleK1VWhkUypej4UiAPYA.jpeg" /><figcaption><em>FragmentB sends data to FragmentA. FragmentManager acts as a dispatcher</em></figcaption></figure><p>New Api has one big advantage and it is its lifecycle-safety — the result is passed to the fragment only when it reaches the STARTED state, but not yet in the DESTROYED state.</p><p>Under the hood FragmentManger stores all registered listeners and all sent results in thread-safe Map implementations:</p><ul><li><em>Map&lt;String, Bundle&gt;</em> for the results sent by fragments</li><li><em>Map&lt;String, LifecycleAwareResultListener&gt;</em> for registered listeners</li></ul><p>When a fragment registers a FragmentResultListener, the FragmentManager adds it to the Map, and when the fragment is destroyed, the listener is removed from the Map. In order to consider the fragment’s lifecycle, the FragmentResultListener is wrapped in the LifecycleAwareResultListener.</p><p>When sending a result, the FragmentManager searches for a listener registered with the same key and passes the result to it. In case the listener is not found, the result is stored in the Map, expecting its further use.</p><p>Let’s check out how the new mechanism works in practice.</p><h3><strong>Practice</strong></h3><p>Take a look at the following example: ProductsFragment contains a list of products that can be sorted by various criteria, and SortFragment allows to specify the desired sorting criterion. The information about the selected sorting will be transmitted by the Fragment Result Api.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*XdRI1WhrpCg1oUPpj0HyQw.png" /><figcaption><em>his is how the final implementation looks like, it can be found by the </em><a href="https://github.com/BelyakovLeonid/FragmentResultSample"><em>link</em></a></figcaption></figure><h4><strong>Step 1</strong></h4><p>In the ProductsFragment, which expects to receive the result, we must register a listener with the FragmentManager. To do this, we will use the extension-function <strong><em>setFragmentResultListener</em></strong><em> </em>from fragment-ktx, which accepts a string key and a listener processing the result.</p><p>Registration of the listener can be done in the onCreate() callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a79e778a25d71fa33572de8921c20098/href">https://medium.com/media/a79e778a25d71fa33572de8921c20098/href</a></iframe><h4><strong>Step 2</strong></h4><p>When SortFragment is ready to send the result, the <strong><em>setFragmentResult</em></strong> method is called with the same string key and the filled Bundle object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c262322aa52c71699ca9ac375cc06a6/href">https://medium.com/media/6c262322aa52c71699ca9ac375cc06a6/href</a></iframe><p>That’s it. That’s all that was required to send a result using Fragment Result Api.</p><h3><strong>Important</strong></h3><p>Hot Api is quite simple, though it is crucial to understand certain nuances related to the correct choice of FragmentManager and the lifecycle.</p><h4><strong>FragmentManager choice</strong></h4><p>The FragmentManager does most of the work in passing the result from one fragment to another. But each fragment has several options to choose from: parentFragmentManager, childFragmentManager, and activity host FragmentManager. Let’s find out which cases presume the choice of one or another FragmentManager.</p><p>First, we get into the so-called master-detail configuration. The Activity contains two fragments, FragmentA and FragmentB, between which we want to pass some data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*M1VO5U4nddoNl8QREMbIzg.jpeg" /><figcaption><em>Activity is the host for FragmentA and FragmentB</em></figcaption></figure><p>In this case, the activity’s FragmentManager can transfer the result between fragments, because both fragments have access to it. You can get this FragmentManager by calling <strong><em>requireActivity().supportFragmentManager</em></strong> or <strong><em>parentFragmentManager</em></strong>.</p><p>Next situation is typical, for example, when opening a DialogFragment or when FragmentA places FragmentC within itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*2_I4-FWn_-zLJqYoX8uweA.jpeg" /><figcaption><em>FragmentA is a host to FragmentC</em></figcaption></figure><p>In this scenario, there are two ways to transfer the result from FragmentC to FragmentA:</p><ul><li>Through activity’s FragmentManager with <strong><em>requireActivity().supportFragmentManager</em></strong></li><li>Through the FragmentA’s child FragmentManager. To get a reference to it, FragmentA must refer to <strong><em>childFragmentManager </em></strong>and FragmentC to <strong><em>parentFragmentManager</em></strong>.</li></ul><h4><strong>Lifecycle nuances</strong></h4><p>As mentioned earlier, Fragment Result Api is lifecycle-safe— the result is delivered only if the fragment is on the screen. Let’s take a look at some examples.</p><p>Let’s introduce the standard case — the fragmentResultListener is set in the onCreate callback, then fragment reaches the STARTED state, and as soon as another fragment sends the result to the FragmentManager, the subscriber fragment receives it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*dbUN0lDDs37Ge9DHzXWb3w.jpeg" /><figcaption><em>Standard scenario</em></figcaption></figure><p>If before the fragment reached the STARTED state, the FragmentManager receivedseveral results, then the fragment will receive only the latest result (since the FragmentManager stores results in Map&lt;String, Bundle&gt;, each subsequent one overwrites the previous one).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*yF57X_NOKfP6dvzAWbv05Q.jpeg" /><figcaption><em>Only bundle3 will receive the fragment, since it was sent last</em></figcaption></figure><p>Now imagine a situation with the fragment being closed before sending the result to the FragmentManager. In this case the subscription will close when reaching the DESTROYED state and the FragmentManager will not send the result to the fragment. But it will internally save result to the map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*c1SflRm9IzjWMN0GOSi1LQ.jpeg" /><figcaption><em>The automatic fragment unsubscription occurs when the DESTROYED state</em></figcaption></figure><p>If we reopen the same fragment after closing, it will get the result that it “didn’t have time” to receive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*YWauV3GC1Fg-X-cvc9E2CA.jpeg" /><figcaption>Scenario when we reopen the fragment after closing. The result will be delivered</figcaption></figure><p>Scenario of the fragment not being finally closed, sitting in the back stack (which means it is in the CREATED state), the result will be delivered as soon as the user returns to this fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*CYnuRxn-T0KxAt2QN8ldxg.jpeg" /><figcaption>When yser returns to the fragment in the backstack, it recives the result if any</figcaption></figure><p>Scenario of the fragment not being finally closed, sitting in the back stack (which means it is in the CREATED state), the result will be delivered as soon as the user returns to this fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*2rf-RgI9PYY7zIE75auSFg.jpeg" /><figcaption><em>If you subscribe at the same time, only the last subscriber will get the result</em></figcaption></figure><h3><strong>Conclusion</strong></h3><p>To sum up, let’s note advantages of the new way of transferring the result between fragments:</p><ul><li>Fragment Result Api is stable, while the preceding targetFragment is deprecated.</li><li>The Api is easy to use and it doesn’t require to write a lot of code</li><li>It’s lifecycle-safe — when receiving a result, you can work with the fragment view</li><li>FragmentManager knows how save data about the passed results in Parcelable, which allows to survive configuration changes and even process death</li></ul><p>Yet, in my opinion there are some disadvantages:</p><ul><li>you need to keep string keys unique, and choose the correct place to store them</li><li>since the result is sent to a Bundle, there is no typization. If you make a mistake, you can get a ClassCastException.</li></ul><p>All in all, Fragment Result Api leaves a positive impression, so let’s try it out!</p><p>P.S. you can find a sample project in my <a href="https://github.com/BelyakovLeonid/FragmentResultSample">github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a17f99490dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/e-legion/getting-the-result-right-part-2-fragment-result-api-1a17f99490dc">The right way to get a result. Part 2. Fragment Result API</a> was originally published in <a href="https://medium.com/e-legion">e-Legion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The right way to get a result (Part I): Activity Result API]]></title>
            <link>https://medium.com/e-legion/the-right-way-to-get-a-result-part-i-activity-result-api-6efbcaa5600d?source=rss-da6fa65d21d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6efbcaa5600d</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android-sdk]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Leonid Belyakov]]></dc:creator>
            <pubDate>Wed, 17 Mar 2021 08:41:32 GMT</pubDate>
            <atom:updated>2021-03-17T09:03:49.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfiaK-Xwf720flLxg9cRjg.png" /></figure><p>Every Android developer has faced the need to transfer data from one Activity to another. This simple task often forces us to write not the most elegant code.</p><p>In 2020, Google finally introduced a solution to the old problem — the Activity Result API, a powerful tool for exchanging data between activities and requesting runtime permissions.</p><p>In this article, we’ll look at how to use the new API and highlight its benefits.</p><h3><strong>What’s wrong with onActivityResult()?</strong></h3><p>Robert Martin in his book “Clean Code” points out the importance of reusing the code or the Don’t repeat yourself principle (DRY) and encourages designing unambiguous functions that perform only a single operation.</p><p>The problem with <em>onActivityResult()</em> is that it becomes almost impossible when it is used following these recommendations. For example, let’s look at the simple screen that requests access to the camera, takes a photo, and opens a second screen — SecondActivity. Let’s suppose that we pass a string to SecondActivity and get an integer value back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5f8948580658aad50b91340324a219/href">https://medium.com/media/bb5f8948580658aad50b91340324a219/href</a></iframe><p>It’s obvious that the <em>onActivityResult()</em> method violates the single-responsibility principle because it is responsible for processing the photo result and for receiving data of the second Activity. Besides, this method looks confusing enough, even though we’ve considered a simple example with some details omitted.</p><p>Additionally, if another similar functionality screen appears in the app, we won’t be able to reuse our code and will have to duplicate it.</p><h3><strong>Using Activity Result API</strong></h3><p>The new API is available starting with AndroidX Activity 1.2.0-alpha02 and Fragment 1.3.0-alpha02, so let’s add the current versions of the corresponding dependencies to build.gradle:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da1144990a911c2fe980431f85f909bb/href">https://medium.com/media/da1144990a911c2fe980431f85f909bb/href</a></iframe><p>Applying an Activity Result consists of three steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jjOStRzu15JXTyxwRD9iwA.png" /></figure><h3><strong>Step 1. Creating a contract</strong></h3><p>Contract is a class that implements the <em>ActivityResultContract&lt;I,O&gt;</em> interface. Where I defines the type of input data necessary to start the Activity, and O defines the callback result type.</p><p>For typical tasks, you can use out-of-the-box implementations: PickContact, TakePicture, RequestPermission, and others. You will find a <a href="https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts">complete list here</a>.</p><p>When creating a contract, we should implement two of its methods:</p><ul><li><em>createIntent() </em>— accepts input data and creates an intent, which will be later launched by calling launch()</li><li><em>parseResult()</em> — is responsible for returning the result, handling resultCode, and parsing the data.</li></ul><p>Another method, <em>getSynchronousResult()</em>, can be overridden if necessary. It allows you to return the result immediately, without starting the Activity, for example, if the received input data is invalid. If this behavior is not required, the method returns null by default.</p><p>Below is an example of a contract that accepts a string and runs SecondActivity expecting an integer value from it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ec833167f0f053a11f9285b89804ecd/href">https://medium.com/media/1ec833167f0f053a11f9285b89804ecd/href</a></iframe><h3><strong>Step 2. Registering a contract</strong></h3><p>The next step is to register the contract in the activity or fragment by calling registerForActivityResult(). You need to pass ActivityResultContract and ActivityResultCallback as parameters. The callback will be invoked when the result is received.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1e1db918cff18f2f34b40331d2dacd4/href">https://medium.com/media/b1e1db918cff18f2f34b40331d2dacd4/href</a></iframe><p>Registering a contract won’t start a new Activity, but only returns a special ActivityResultLauncher object that is necessary for the following step.</p><h3><strong>Step 3. Launching a contract</strong></h3><p>To start the Activity, we only need to call launch() on the ActivityResultLauncher object that we have obtained in the previous step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d928d4d046da94bff6c427ef78ecae/href">https://medium.com/media/48d928d4d046da94bff6c427ef78ecae/href</a></iframe><h3><strong>Important!</strong></h3><p>Let’s highlight a few non-obvious points that must be taken into account:</p><ul><li>Contracts can be registered at any point of the activity or fragment lifecycle, but they cannot be launched before going to the CREATED state. A common approach is to register contracts as class fields.</li><li>It is not recommended to call <em>registerForActivityResult()</em> inside the <strong><em>if</em></strong> and <strong><em>when</em> </strong>statements. The reason is that while expecting the result, the application process can be destroyed by the system (for example, when launching a heavy camera app). And if we don’t re-register the contract when restoring the process, the result will be lost.</li><li>If we start an implicit Intent and the operating system is not able to find a suitable Activity, an exception ActivityNotFoundException: “No Activity found to handle Intent” will be thrown. To avoid this situation, you need to check <em>resolveActivity(</em>) with <em>PackageManage</em>r before calling <em>launch()</em> or in <em>getSynchronousResult()</em> method.</li></ul><h3><strong>Runtime permissions</strong></h3><p>Another handy Activity Result API usage is runtime permissions request. Instead of calling <em>checkSelfPermission(), requestPermissions()</em>, and <em>onRequestPermissionsResult(),</em>a concise and convenient solution is available now — <em>RequestPermission</em> and <em>RequestMultiplePermissions </em>contracts.</p><p>The first serves to request single permission, and the second to request several permissions at once. In the callback, RequestPermission returns <em>true</em> if access is granted, and <em>false</em> otherwise. RequestMultiplePermissions will return <em>Map&lt;String, Boolean&gt;</em>, where the key is the name of the permission requested and the value is the result of the request.</p><p>In real life, requesting permissions looks a bit more complicated. In <a href="https://developer.android.com/training/permissions/requesting">Google’s guidelines</a>, we’ll see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbjMlE5A4iDMNZZdsrq05Q.png" /><figcaption>Google guidelines of requesting permissions</figcaption></figure><p>Developers often forget about these nuances when dealing with runtime permissions:</p><ul><li>If the user has previously rejected our request, it is advisable to further explain why the application needs this permission (see 5a).</li><li>When rejecting a permission request (see 8b), we should limit the functionality of the application and consider the case when the user has checked the “Don’t ask again” option.</li></ul><p>This is where the <em>showRequestPermissionRationale()</em> method comes to our rescue. If the method returns <em>true</em> before requesting permission, we should tell the user how the application will use permission. If permission is not granted and <em>shouldShowRequestPermissionRationale()</em> returns <em>false</em>, it means that the “Don’t ask again” option was selected and we should ask the user to go into settings and grant permission manually.</p><p>With this in mind, let’s implement the device’s camera access request:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/917319fe2429b51093164fd1b632e723/href">https://medium.com/media/917319fe2429b51093164fd1b632e723/href</a></iframe><h3><strong>Conclusion</strong></h3><p>Now let’s bring our knowledge into practice and use it to rewrite the first screen example. As a result, we’ll get a quite neat, easy-to-read, and scalable code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e79045ee366d9046da44eb695925c4e/href">https://medium.com/media/4e79045ee366d9046da44eb695925c4e/href</a></iframe><p>Today we’ve seen the disadvantages of data exchange via onActivityResult(), learned how to connect Activity Result API to your project and how to use it in practice.</p><p>Also, note that the new API is totally stable, while the commonly used onRequestPermissionsResult(), onActivityResult() and startActivityForResult() are now Deprecated.</p><p>In my <a href="https://github.com/BelyakovLeonid/activity_result_api_sample">Github repository</a>, you will find a demo application with a variety of examples of using the Activity Result API including working with runtime permissions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6efbcaa5600d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/e-legion/the-right-way-to-get-a-result-part-i-activity-result-api-6efbcaa5600d">The right way to get a result (Part I): Activity Result API</a> was originally published in <a href="https://medium.com/e-legion">e-Legion</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>