<?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 Álvaro Blanco Cabrero on Medium]]></title>
        <description><![CDATA[Stories by Álvaro Blanco Cabrero on Medium]]></description>
        <link>https://medium.com/@alvaro-blanco?source=rss-a38b2f4c9ec6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4_ATCZ6TxGvP1sXL4P-GWw.jpeg</url>
            <title>Stories by Álvaro Blanco Cabrero on Medium</title>
            <link>https://medium.com/@alvaro-blanco?source=rss-a38b2f4c9ec6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:48:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alvaro-blanco/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[Avoiding IllegalStateException for DialogFragments]]></title>
            <link>https://alvaro-blanco.medium.com/avoiding-illegalstateexception-for-dialogfragments-6a8f31c4ce73?source=rss-a38b2f4c9ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a8f31c4ce73</guid>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Álvaro Blanco Cabrero]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 22:49:46 GMT</pubDate>
            <atom:updated>2018-08-19T14:25:26.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3Q-atTk4pg4R5AaqmGUlQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/1td5Iq5IvNc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maximilian Weisbecker</a> on <a href="https://unsplash.com/search/photos/java?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Almost every single Android developer using DialogFragment has once faced this issue: you are waiting for a service call or some long time based task to complete in order to present the user a feedback dialog, then your app crash with the following exception:</p><pre>java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState<br>    at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)<br>    at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)<br>    at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)<br>    at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)</pre><p>I won’t enter into further explanations on why this exception occurs, this is greatly explained in this blog post:</p><p><a href="https://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html">Fragment Transactions &amp; Activity State Loss</a></p><p>TL;DR: Fragment transactions can not be committed after onSaveInstanceState has been called, so what to do in order to show DialogFragments inside asynchronous callbacks, without worrying about lifecycle and without resorting in commitAllowingStateLoss aka “I do not care if the DialogFragment is shown”?</p><p>Many solutions on StackOverflow had overcome this, i.e:</p><p><a href="https://stackoverflow.com/questions/16265733/failure-delivering-result-onactivityforresult">&quot;Failure Delivering Result &quot; - onActivityForResult</a></p><p>But would not be great to have a generic and simple solution to use across apps without forcing you to add too much boilerplate code to every component?</p><p>Let’s rely on Architecture Components to solve this problem, by simply creating a presenter class observing Activity’s lifecycle and controlling when transactions can be made or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/626c331fdedce675164a31048d97f8b2/href">https://medium.com/media/626c331fdedce675164a31048d97f8b2/href</a></iframe><p>Very simple: just create and instance of DialogFragmentPresenter in your Activity and delegate show method to it. No more exceptions won’t occur in we try to show the dialog on an illegal state.</p><p>But this approach do not cover DialogFragment presentation deferring, so lets update our code to allow it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f499768c1986ae1ec5eb98efb5fd39e/href">https://medium.com/media/3f499768c1986ae1ec5eb98efb5fd39e/href</a></iframe><p>Thats it, now our DialogFragments will remain stored until onResume is called again to show them. (Note that I declared a list of pending dialogs, although the most usual case is to only present once at a time, but lets do not be so restrictive and allow the possibility of spamming the user with multiple dialogs :D )</p><p>P.S: Although documentation warns not to play with Fragment transactions in onResume() (<a href="https://developer.android.com/reference/android/support/v4/app/FragmentActivity#onResume()),">https://developer.android.com/reference/android/support/v4/app/FragmentActivity#onResume()),</a> it is not very clear which is the real reason of this statement and looking across the source code of FragmentActivity does not unveil it: It appears to be safe making transactions after onResume() is called, and all our tests across different use cases and different API versions had work properly.</p><p>Thanks for reading this article. Be sure to like and recommend it if you found it helpful!</p><p>For more about Android development, you can <a href="https://medium.com/@alvaro.blanco">follow</a> me or connect with me through on <a href="https://github.com/imablanco">Github</a> and <a href="https://es.linkedin.com/in/%C3%A1lvaro-blanco-cabrero-59a024a3">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a8f31c4ce73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with Android Architecture Components + Retrofit — Part 1]]></title>
            <link>https://alvaro-blanco.medium.com/playing-with-android-architecture-components-retrofit-part-1-9994d651cf3c?source=rss-a38b2f4c9ec6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9994d651cf3c</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Álvaro Blanco Cabrero]]></dc:creator>
            <pubDate>Tue, 23 May 2017 21:53:32 GMT</pubDate>
            <atom:updated>2017-05-23T21:53:32.040Z</atom:updated>
            <content:encoded><![CDATA[<p>Google recently announced its new architecture based set of libraries at I/O 2017 under the name of Android Architecture Components. This libraries greatly simplify our lives when dealing with Android’s lifecycle, delegating its management to them.</p><p>To demonstrate how this new libraries can make our app more robust and maintainable I will write an example showing the core classes of a simple app I made to test this new components.</p><p>The app fetches a list of organizations from Github API using Retrofit as networking library, so we will start creating the data layer</p><h3><strong>Data Layer</strong></h3><p>First we start creating the interface to define Retrofit’s method call (<a href="https://api.github.com/organizations/44">https://api.github.com/organizations</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/471ed72928a1abdb9b4fb803f21cea2c/href">https://medium.com/media/471ed72928a1abdb9b4fb803f21cea2c/href</a></iframe><p>We need to define the organization model to. We will use a Kotlin data class to accomplish it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebd13a6c189aae8f43913fa2ba33b5e9/href">https://medium.com/media/ebd13a6c189aae8f43913fa2ba33b5e9/href</a></iframe><p>Also a class to call our defined Retrofit service</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1406584f85f9ef74f3e9c2cbfcc068fd/href">https://medium.com/media/1406584f85f9ef74f3e9c2cbfcc068fd/href</a></iframe><p>Now we are going to create our entry point to access Github service. It will be a singleton:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8c74840d9f9d36fba6ec48d0dd621a6/href">https://medium.com/media/e8c74840d9f9d36fba6ec48d0dd621a6/href</a></iframe><p>Now we can simply access our service and make the call to organizations API, but we are going to make our app a little bit smarter integrating Android Architecture Components.</p><p>You can add them from Google’s Maven</p><pre>repositories {<br>    maven { url &#39;https://maven.google.com&#39; }<br>}</pre><pre>compile &#39;android.arch.lifecycle:runtime:1.0.0-alpha1&#39;<br>compile &#39;android.arch.lifecycle:extensions:1.0.0-alpha1&#39;<br>annotationProcessor &quot;android.arch.lifecycle:compiler:1.0.0-alpha1&quot;</pre><p>Let’s take a look to one of them:</p><h3>LiveData</h3><p>From Android Developer page: <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html">LiveData</a> is a data holder class which keeps a value and allows this value to be observed. Unlike a regular observable, <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html">LiveData</a>respects the lifecycle of app components, such that the <a href="https://developer.android.com/reference/java/util/Observer.html">Observer</a> can specify a <a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.html">Lifecycle</a> in which it should observe.</p><p><a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html">LiveData</a> considers an <a href="https://developer.android.com/reference/java/util/Observer.html">Observer</a> to be in active state if the <a href="https://developer.android.com/reference/java/util/Observer.html">Observer</a>’s <a href="https://developer.android.com/reference/android/arch/lifecycle/Lifecycle.html">Lifecycle</a> is in STARTED or RESUMED state.</p><p>Using this class we can forget the lifecycle management by delegating to it and ensuring that our observer will only be called in an active state.</p><p>Let’s create an extension of this class to hold our data</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82432927c1d120c3b9ca5d99670ad2cc/href">https://medium.com/media/82432927c1d120c3b9ca5d99670ad2cc/href</a></iframe><blockquote>Network status exposure is omitted for the sake of clarity</blockquote><p><strong>onActive</strong> method is automatically called when the first observer is added (when observers change from 0 to 1), so this is the ideal method to start calling Github API.</p><p>LiveData also has an <strong>onInActive </strong>that is called when there are no remaining observers, but we are not going to implement it because we will rely on another class called <strong>ViewModel</strong> to do the proper cleaning/canceling.</p><p>Once we get the response, we set the <strong>value</strong> property (from getValue()/setValue in java) to let LiveData to notify our active observers.</p><p>Note that we are only executing the call when the first observer is added. This is because LiveData always calls a new observer with the last data it has, so subsequents observers will always receive the API response (also we could not reuse the same call object unless cloned :D ).</p><p>Also we will need to modify our <strong>OrganizationHandler</strong> class to return this new type of data</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a43cbec40f9ae8c19f2396f88dd6de7e/href">https://medium.com/media/a43cbec40f9ae8c19f2396f88dd6de7e/href</a></iframe><p>Now we can simply observe this LiveData to start calling and we will receive the response in a callback.</p><pre>DataHandler.INSTANCE.organizationHandler<br>        .getOrganizations()<br>        .observe(this, <em>Observer </em><strong>{ </strong>response <strong>-&gt; }</strong>)</pre><blockquote>Note: observe method from LiveData needs an instance of LifeCycleOwner, a class that have an Android lifecycle. Every class can implement this interface an provide the lifecycle, but we can use two already built classes: LifecycleActivity and LifecycleFragment</blockquote><p>This approach is totally ok, as we are getting automatically unsubscribed after <strong>onPause() </strong>callback and we are getting notified with the last value on subsequents subscribes during the LifeCycleOwner scope. But what happens if the user decides to rotate the device? Nothing good: Activity will be recreated and a new instance of our RetrofitLiveData with it, making the call again. One solution is to keep and static instance of our RetrofitLiveData out of the Activity scope and everything will be ok, because our observers will be automagically removed when the Activity is destroyed, avoiding memory leaks but there is no need to do this, because again Android Architecture Components are here to save our lives.</p><h3><strong>ViewModel</strong></h3><p>ViewModel is designed with the separation of concerns principle in mind. It’s a class that allows as to separate UI work from business logic. It is retained during configuration changes so it outlives the activity.</p><p>To gather an instance of a ViewModel for an Activity or Fragment, we should call</p><pre>ViewModelProviders.of(this).get(MyViewModel.class); </pre><p>If the activity is re-created, it receives the same MyViewModel instance that was created by the previous activity. When the owner activity is finished, the Framework calls <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel.html">ViewModel</a>’s <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel.html#onCleared()">onCleared()</a> method so that it can clean up resources.</p><p>Now let’s create our custom ViewModel:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e73d0abeab0fa838f1bd6bdf2d748500/href">https://medium.com/media/e73d0abeab0fa838f1bd6bdf2d748500/href</a></iframe><p>That’s all! Now in our Activity we simply need to access the ViewModel and make the call</p><pre>ViewModelProviders.of(this)<br>        .get(OrganizationListViewModel::class.<em>java</em>)<br>        .liveData.observe(this, <em>Observer </em><strong>{ </strong>response <strong>-&gt;}</strong>)</pre><p>The first time we observe the LiveData the call will be started and subsequent times we are only going to receive the cached result also surviving configuration changes and making the call once during the Activity lifecycle.</p><p>In <strong>Part 2 </strong>I will add persistence with Room, so stay tuned!(<a href="https://developer.android.com/topic/libraries/architecture/room.html">https://developer.android.com/topic/libraries/architecture/room.html</a>).</p><p><em>If you find this post useful, click the💚 below so other people can see it too!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9994d651cf3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>