<?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 T.Surkis on Medium]]></title>
        <description><![CDATA[Stories by T.Surkis on Medium]]></description>
        <link>https://medium.com/@t.surkiss?source=rss-331f2940e0d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YPqpIsD4P3AGulcBvA9VLg.jpeg</url>
            <title>Stories by T.Surkis on Medium</title>
            <link>https://medium.com/@t.surkiss?source=rss-331f2940e0d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:39:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@t.surkiss/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[Here’s how to build the MOST scalable Onboarding flow!]]></title>
            <link>https://medium.com/lumen-rnd/heres-how-to-build-the-most-scalable-onboarding-flow-e25ac5ad3371?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e25ac5ad3371</guid>
            <category><![CDATA[onboarding]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Thu, 08 Apr 2021 13:10:28 GMT</pubDate>
            <atom:updated>2021-04-08T13:11:21.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmn-ETplgQiIORUlZT5sdA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@dunc_in?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Duncan Meyer</a> on <a href="https://medium.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>At <a href="https://www.lumen.me/">Lumen</a>, we grow at a fast pace and constantly adjust and improve our onboarding experience, to provide the best personalized experience for our users. As a result, our onboarding flow became a tangle of spaghetti code of logic and UI scattered across multiple screens.</p><p>We will show you how we rebuilt our onboarding logic to allow for dynamic changes no matter how the app evolves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caabFIY_2Xy7ErG7BHzf-Q.png" /><figcaption>our onboarding flow overview at the time of publishing this article.</figcaption></figure><p>Onboarding flows are hard. They are easy to create but hard to maintain when our app evolves and changes with time. The nice flow you worked so hard to create becomes a convoluted mess of screens and logic scattered all around making it hard to introduce new changes. The solution will be to design it in a scalable way to grow with our application, but that’s easier said than done. Here’s how we did it:</p><h3>The old onboarding flow</h3><p>Applications are a series of screens, that interact with one another in a certain order. Therefore, pressing the sign-up button will lead you to the sign-up page. The sign-up page in turn will take you to the onboarding process. In this process, each page will lead to the next until you reach the end of the onboarding experience.</p><p>This is the most primitive implementation, and there is nothing wrong with it. In fact, many apps don’t require a lot of data, and their onboarding process is simple. But if your app needs a more complex onboarding experience and you feel like you could use a new and flexible way to do this, keep reading.</p><p>Once we recognized we needed more data on the user to allow for a more personalized experience, we knew our onboarding experience needed to grow. However, the way we built it didn’t allow for quick and precise actions, and we came across the following issues:</p><ul><li>Adding a new screen or series of screens forced us to update the previous and following screens. As a result, we had no clear image of the order of pages and each page was dependent on the other.</li><li>We implemented any complex routes that involved a route based on a decision (for example, go to page A or page B if a user does action C) in the page itself. This made the onboarding flow scattered across multiple pages without any clear indication of how it works and why.</li><li>To move pages around in the flow, we had to remember to move the complex parts which decided the next routes. As a result, bugs were very frequent due to “forgotten” logic in an already unrelated page.</li></ul><p>As a fast-moving startup constantly aiming to improve the user experience, this solution didn’t cut it. We needed a solution that de-coupled the logic from the pages and flows themselves, allowing us to easily and quickly move things around without damaging the flow itself. This will result in a testable, reliable and modular code, allowing us to experiment and iterate without major breaking changes.</p><h3>The new Onboarding experience</h3><p>To build a new system and a new mechanism, you first need to understand the different components and how they work together. Down to its core, an onboarding experience is made up of four components:</p><ul><li><strong>Route:</strong> The route contains the name of the screen and the parameters it requires. We use <a href="https://pub.dev/documentation/sailor/latest/">Sailor</a> as our navigational library and each screen name points to a method creating that said screen.</li><li><strong>Flow:</strong> The onboarding flow in Lumen consists of different flows, which allows us to break the experience into a more manageable specification. Each flow contains a collection of pages and represents a unified idea for a said collection of pages. For example, our setup flow is responsible for the initial setup of the user; his device pairing, and approving various permissions we required. As a result, these two screens belong to the setup flow.</li><li><strong>Manager of Flows: </strong>Just like a flow decides on which page to present, so does the manager of flows. For example, after the setup flow comes a flow dedicated to personal details, such as name, birth date, etc. Therefore, after the setup flow is complete, the manager takes us to the personal details flow.</li><li><strong>Router:</strong> This will be the base for all screens and contains the stack of pages from the currently presented flow. Each navigational command will be received here and routed to the correct screen.</li></ul><p>If your onboarding experience is relatively simple, you may have a single flow and ignore the manager of flows. However, I would recommend adding one if there is even a slight possibility of a future onboarding change.</p><p>To remove the dependency between pages, the manager of flows will decide the next screen. As a result, every page will communicate with the manager of flows when it needs to navigate. This creates onboarding pages that are not dependent on anything but the manager itself, which allows an easier way to arrange things around the onboarding process</p><p>Since we are using the <a href="https://pub.dev/packages/bloc">BLoC</a> architecture, our only way to communicate with the manager of flows is through an event. This event will be our <strong>NavigationEvent </strong>and will contain two parameters:</p><ul><li><strong>Direction:</strong> The user can always choose to continue in the flow or return to the previous page. The interpretation of this is an enum containing two values: Left \ Right. <em>In retrospect, a better name would be forward or backward to remove the dependency on the UI itself.</em></li><li><strong>Parameters:</strong> Some screens may want to pass information to the next screen; however, this remains null if it passes no parameters.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ca017915f5e90e0c159bf0805105d9b/href">https://medium.com/media/4ca017915f5e90e0c159bf0805105d9b/href</a></iframe><p>To see how all the parts work together, we first need to look at each one separately.</p><h4>Route</h4><p>A route represents the next screen; its name and the parameters it needs to receive.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9959f53a3cbe19674f1b504be71fff6/href">https://medium.com/media/e9959f53a3cbe19674f1b504be71fff6/href</a></iframe><h4>Flow</h4><p>A flow is a collection of pages all tied around a single feature. Because it represents a group of pages, a flow needs to be responsible for the logic and relationship between the pages. It should also provide the functionality to query what the next route is upon navigation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9cd1fba1f03b2c8dc39dbdc8046d194/href">https://medium.com/media/f9cd1fba1f03b2c8dc39dbdc8046d194/href</a></iframe><p>Each flow will have the ability to navigate forward or backward in the flow. The navigation will be entirely logical and would represent an update of the<em> </em>currentRoute<em> </em>parameter.</p><p>The purpose of the didFinish param is for the manager of flows to know if this flow is complete. If the flow isn’t complete, then the manager of flows needs to query the current route after applying the next or previous methods. However, if the flow has finished, then the manager of flows will query the next flow in the line. If no more flows exist down the line, then the onboarding process is complete. More on that will be in the manager of flows section down below.</p><p>Since most of the onboarding process is linear, meaning it has a set number of pages that do not change along the way, we can construct a custom class that would do the heavy lifting for all of our flows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b82e346169b0985b7be77ee45371bee4/href">https://medium.com/media/b82e346169b0985b7be77ee45371bee4/href</a></iframe><p>The linear flow holds a list of objects (<em>screenRoutes</em>) representing the screens. The order of this flow is also the chronological order in which the screens are displayed, hence why a data structure of the list is used. To move from one screen to the next or back, we update the <em>currentPosition</em> index.</p><p>The query as to whether we finished the flow or not depends on the index value compared to the number of screens. If the index has passed that number, it means we have completed the flow.</p><p>To create a new flow, all we have to do is to create a new class extending the <em>LinearRouteFlowGroup</em> class and declare in its constructor, the screens that belong to that flow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdd4770f4186b38e8106ab54913e2d1d/href">https://medium.com/media/fdd4770f4186b38e8106ab54913e2d1d/href</a></iframe><p>As a side note, the class will be a bit more complex, checking if the data exists before deciding if a screen enters the list or not. This depends on the logic of your application and works similarly to the way we add different screens depending on the operating system.</p><h4><strong>Manager of Flows</strong></h4><p>This class will be the manager of flows and the highest logical component in your onboarding process. Due to the complexity of the class, I will break it down into a few parts. Before we begin, there are two important things to note here:</p><p>The manager of flows will be a class implementing a BLoC and following the BLoC architecture. Therefore, let’s start with the state of the BLoC, which represents the current route and flow direction. The router will read the state to decide what page or flow to present.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32519acb6d3d1cbb3914ffb4d9a3c10e/href">https://medium.com/media/32519acb6d3d1cbb3914ffb4d9a3c10e/href</a></iframe><p>The initial state will have to come after the data is ready for us to query it. The manager will instantiate each flow in a dedicated list, representing the order of flows. Each flow will be created as presented earlier and, depending on the data, some flows might be already complete. This can occur if a user has started the onboarding process and closed the application or uninstalled it and returned to it later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5c0f7845e63422fb887ca790332cd19/href">https://medium.com/media/e5c0f7845e63422fb887ca790332cd19/href</a></iframe><p>Each flow would hold a getter named <em>isEmpty</em> to represent whether the list of flows inside it is empty. If all the data is available for that particular flow, then it should have an empty list.</p><p>Iterating over the list would lead us to the flow that was not completed yet, thus receiving its current position in the collection of flows (<em>_flows</em>). That position, <em>_currentPosition</em>, represents the currently active flow.</p><p>During the actual onboarding process, a user will move between pages, be it forward or backward. Each movement will be an event processed by the manager BLoC. It will activate the current flow and then query it on whether it is complete or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f13b233612dbf379a9ccb5fff67c20a5/href">https://medium.com/media/f13b233612dbf379a9ccb5fff67c20a5/href</a></iframe><p>If the flow did not finish, we will move to the next page. Since the flow has already advanced, as we have seen in the previous section, all we have to do is create a state out of its <em>currentRoute</em> value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9a0b3632ee1f5f54ceb1ef351b32f4/href">https://medium.com/media/5b9a0b3632ee1f5f54ceb1ef351b32f4/href</a></iframe><p>If the flow is already complete, we will advance to the next flow by incrementing the <em>_currentPosition</em> value. Afterward, we will have three options.</p><ul><li>This was the last flow. As a result, the entire flow list is complete, and the onboarding process is over. The state that would return to the router will signal it to move to the steps following a successful onboarding process.</li><li>The current flow that <em>_currentPosition</em> points to is empty. From the previous sections, an empty flow is a complete one. As a result, we will need to advance to the next flow. Therefore, we would call the <em>_onFlowFinished</em> method again to initiate the process of moving a flow all over again.</li><li>The new flow is not an empty one and contains a screen that was not yet filled by the user. Therefore, the user continues to the current page of the flow, calling the <em>_onFlowContinue</em> method we have seen earlier.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d799af229221c53b8ef59158be7303a/href">https://medium.com/media/2d799af229221c53b8ef59158be7303a/href</a></iframe><h4>Router</h4><p>Each application in Flutter has a navigation class. This navigation is a stack of pages being put on top of one another, depending on the logic. To separate the onboarding process from the main navigation of the application, we created the onboarding as its own navigator, independent of the main application navigation, but nested inside of it.</p><p>This means, that each navigation occurs inside the onboarding navigator. Upon a successful onboarding, the navigator is discarded and move to the regular application navigation.</p><p>It provides full control of the entire onboarding process without potentially breaking anything in the application navigation itself. I would recommend separating big feature-rich screens the same way if possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMhwM3cJNJo1x02BZzdnKA.jpeg" /></figure><p>The <strong>OnboardingFlow</strong> is the widget that gets loaded from the application navigation, be it the next page after sign up.</p><p>The <strong>OnboardingRouterWidget</strong> is the one that receives the different navigational states from the BLoC we’ve seen earlier. It decides upon receiving a state — whether to navigate towards a specific screen or pop the current one.</p><p>The screens and flows themselves live inside the <strong>Onboarding Navigator</strong> which is just the Navigator widget nested inside the <strong>OnboardingRouterWidget</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94fea167364ccc985dfde881c5c64acf/href">https://medium.com/media/94fea167364ccc985dfde881c5c64acf/href</a></iframe><p>The root screen is a simple empty container that is presented for a short period of time until the onboarding BLoC decides on the first flow that will be displayed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32116b04bee74762a99fbe39791f24df/href">https://medium.com/media/32116b04bee74762a99fbe39791f24df/href</a></iframe><p>The onBlocStateChange method will vary between different applications, but at its core, it will have four options:</p><ul><li><strong>Navigate to a new flow:</strong> The old flow, since it was complete, has its screens popped from the navigation stack. In their place is inserted the first screen of the flow.</li><li><strong>Navigate to a new page:</strong> Navigating to a new page will be done by adding it to the current navigational stack. As a result, a user could seamlessly scroll forward and backward between all the pages of that given flow.</li><li><strong>Navigate back:</strong> Navigating back is executed by a simple pop to the stack. The user will face each page again if he or she chooses to navigate forward.</li><li><strong>Navigate out of onboarding:</strong> When all the flows are complete, the user has finished the onboarding process. Therefore, we will navigate outside of the onboarding flow by calling the application navigator, discarding the OnboardingFlow widget.</li></ul><h3>Summary</h3><p>Although seemingly more difficult at first, the new onboarding process allows us to move fast and change things easily. Since each widget is de-coupled from its previous or following widget, all we have to do to change the order is to update the flow classes.</p><p>The logic allows us abstraction and control with the given benefit of tests, all while not comprising of the quality that we provide for our users.</p><p>I would recommend that anyone, given a complex onboarding process, or one that might grow one day, invest a lot of thought into how you build it today. This will allow your company to move fast and be nimble without compromising the experience of the user.</p><p>In what ways are you implementing your onboarding flows?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e25ac5ad3371" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lumen-rnd/heres-how-to-build-the-most-scalable-onboarding-flow-e25ac5ad3371">Here’s how to build the MOST scalable Onboarding flow!</a> was originally published in <a href="https://medium.com/lumen-rnd">Lumen R&amp;D</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Architecture Components & MVP \ MVVM]]></title>
            <link>https://medium.com/android-news/architecture-components-mvp-mvvm-237eaa831096?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/237eaa831096</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-architecture]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Thu, 18 Oct 2018 02:50:44 GMT</pubDate>
            <atom:updated>2018-11-12T04:59:03.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iypX-t97yxcFL9Zp-vR1fw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@randomlies">Ashim D’Silva</a>: <a href="https://unsplash.com/photos/3Ijt7UkSBYE">https://unsplash.com/photos/3Ijt7UkSBYE</a></figcaption></figure><p>We all heard of the architecture components library. However, if our app is built with an MVP architecture or MVVM architecture, there are specific barriers to using it.</p><p>How can we cross these barriers?</p><p>Please note that architecture, in general, is abstract, and apart from some ground rules, it can be applied in different ways. Therefore, read this article as a means of new ideas or approaches rather than a single way to do things.</p><h3>History</h3><p>In the beginning, there was no architecture. Making applications were the name of the game back then.</p><p>However, as time passed, there came an understanding that the code base needs to be maintainable. As an application grows, so does its complexity. Using god activities made everything very coupled and hard to maintain. Sometimes even the smallest feature could break the entire system.</p><p>A skyscraper cannot be built without blueprints and planning. There needs to be a definitive plan for each step of the way — from the infrastructure all the way to the antenna up top.</p><p>Applications are no different. Applications need a blueprint as well, and that blueprint is known as architecture.</p><p>The first architecture that gained popularity in the Android world was MVP. There was a clear separation between a view, its business logic, and its data. Every component had its way and its purpose.</p><p>Later on, Google saw the change in the Android world, and it has provided us with its own set of tools to ease our lives. It introduced to us the architecture components libraries.</p><h3>Today</h3><p>MVP matured well and is still being used in the industry. Architecture components did not introduce a superior architecture. MVVM is more of a rival than a supreme ruler, and it should be treated as such.</p><p>However, Architecture components did introduce new tools that seemingly work better with MVVM. Is it the case?</p><p>As I mentioned earlier, architecture has different implementations and interpretations. Therefore, some would prefer to stay with MVP, and some would migrate to MVVM.</p><p>I will tackle both ways.</p><h3>MVP Route</h3><p>This route will be picked when most of the application is already written with MVP in mind, or when MVP is the clear architectural choice.</p><p>Architecture components are a great tool, but we don’t want to change our architecture. We want to have the best of both worlds.</p><p>In this article, I will use a classic application. The application will display a list of opinionated quotes that are retrieved by a remote API.</p><p>Each architecture has its flow of data, and the MVP data flow is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3guTkDg_7DgFiq5l3-GqPw.png" /></figure><p>The data resides in a data controller or repository class. According to the business logic, the presenter requests data with a callback. Once the data is ready, the presenter is notified and according to its business logic activates the view to display the data.</p><p>At the end of the data flow chain in our application, there is an adapter. Few are the applications that exist in the market that don’t have at least one screen showing a list of data. Therefore, we can assume that most applications will have at least one adapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ueSIWYeWsz5Mi-0X3Muhxg.png" /></figure><p>Adapters are a weird kind. Instead of the presenter, giving orders to the view, the adapter asks for orders. This weird flow was accepted as an anomaly in MVP because of the way adapters work. Consequently, the presenter will implement the following methods:</p><ul><li>onDataReceived(data: List&lt;Object&gt;) \ onDataChanged(data: Object) \ onDataDeleted(data: Objecsubmit list)…</li><li>getDataCollectionSize(): Int</li><li>getItem(position: Int): Object</li></ul><p>With version 27 of the support libraries, a new kind of adapter was introduced to save us from writing all of this boilerplate code. This adapter is called <a href="https://developer.android.com/reference/android/support/v7/recyclerview/extensions/ListAdapter">ListAdapter</a>, not to confuse with the API 1 ListAdapter.</p><p>The way ListAdapter works is by passing it a class that implements the DiffUtil.ItemCallback&lt;T&gt; interface and declaring the data and view-holder object types. Each time our data has changed, we call a dedicated method to submit the data collection anew. Behind the scenes, the adapter uses the class that implements the DiffUtil.ItemCallback&lt;T&gt; interface to analyze the data and to act upon only what has changed. As a result, we don’t need to worry about all the boilerplate code that we once had.</p><p>However, our presenter is still left with one single method:</p><ul><li>onDataReceived(data: List&lt;Object&gt;)</li></ul><p>It might not seem like a big deal, but remember we are talking about a simple application in this example. Rare are the cases where such a solution is sufficient. Most complex applications have multiple streams of data, and it adds up to more unnecessary boilerplate code.</p><p>How can we use architecture components to our advantage?</p><h4>LiveData</h4><p>LiveData is observable data. Instead of actively waiting for a data response, we subscribe to it to be notified of any data change. There are two ways to subscribe to data, and the names are self-explanatory:</p><ul><li>Forever</li><li>Lifecycle aware</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jfjsJYUTPnX3KvBBb1N8Zg.png" /></figure><p>I will focus on the second subscription type since it is better tied to this article.</p><p>To subscribe to LiveData, the obvious thing we need to pass on is a callback class. However, the second part is quite peculiar — we need to pass on our activity or fragment.</p><p>Why do we need the view class? Why can’t we subscribe to LiveData from our DataController class and notify the presenter of each data change?</p><p>The answer lies in the subscription type name — Lifecycle.</p><p>With the architecture components library, under the hood changes were introduced to Android. These changes are what allows the new architecture components to function.</p><p>How do these changes tie in with LiveData?</p><p>The changes to work with LiveData were introduced to two particular classes:</p><ul><li>FragmentActivity, from which AppCompatActivity inherits from</li><li>Fragment, from the support libraries</li></ul><p>These classes implement an interface called LifecycleOwner. When we subscribe to LiveData observation, the method expects to receive a class that implements that interface alongside our callback. It constructs a map entry of our observer callback as a key pointing to a wrapper class.</p><p>There are two types of wrapper classes:</p><ul><li>AlwaysActiveObserver</li><li>LifecycleBoundObserver</li></ul><p>The wrapper is created according to the observation choice. In our case, a lifecycle observation is followed by the creation of an instance of LifecycleBoundObserver. The class holds two member classes:</p><ul><li>LifecycleOwner</li><li>Observer</li></ul><p>Afterward, the wrapper class is being saved in an instance of a class named LifecycleRegistry which is extracted by calling the single LifecycleOwner method, getLifecycle(), which is part of our screen class. It constructs a map entry that resides in the LifecycleRegistry instance class. The entry is built from our previous wrapper class, LifecycleBoundObserver to a wrapper class that has two values:</p><ul><li>LifecycleObserver — our LifecycleBoundObserver instance</li><li>State — the current lifecycle state of our Activity \ Fragment</li></ul><p>Each time a change occurs in the lifecycle of our screen, the LifecycleRegistry is the one that receives the changes. Each time our screen is destroyed but retained, the LifecycleRegistry instance is saved by being passed in a bundle and read in the onCreate method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lY1kqi01-fu2TJDufYjs4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tc2AkkCEwRiQc2Iw7mbM_g.png" /></figure><p>Now that we understand how LiveData is built under the hood, what would we need to implement it in our presenter?</p><p>In our opinionated quotes application, we have one single source of data, coming from a remote API. Thus, we will only need one instance of LiveData. Two components will be necessary, as we’ve seen in the explanation above:</p><ul><li>LifecycleOwner — our screen</li><li>Observer — the callback of the data</li></ul><p>The architecture in hand is MVP, so no data binding in the screen class is allowed since it needs to be passive. Furthermore, it cannot be in the presenter itself, since it is not supposed to be familiar with Android components nor deal with data.</p><p>Our ideal class is our data controller. The data controller class only needs to know about a class implementing the LifecycleOwner interface and a callback class or method. Therefore, it will hold a single method that would receive two parameters:</p><ul><li>LifecycleOwner instance</li><li>Callback class or method instance</li></ul><p>To retrieve the LifecycleOwner instance of our screen, we can create a method in a unique interface from which all screens implementing the view portion of the contract will inherit. Each class will be responsible for retrieving itself as a LifecycleOwner instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f2e88ff5cf8333b202153a42a857e45/href">https://medium.com/media/0f2e88ff5cf8333b202153a42a857e45/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f98568289d830525fee888d4be614dc/href">https://medium.com/media/2f98568289d830525fee888d4be614dc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21cedc1b827eb1b614ea7edce2fdb122/href">https://medium.com/media/21cedc1b827eb1b614ea7edce2fdb122/href</a></iframe><p>At the appropriate time of initialization, the presenter will call a dedicated bind method in the data controller. The callback class will be received from the screen, and the LifecycleOwner will be extracted from the view by the presenter.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdc8d9573651afe557a49d79098d1c1e/href">https://medium.com/media/fdc8d9573651afe557a49d79098d1c1e/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0558b95bb56f26812212f29556a6a717/href">https://medium.com/media/0558b95bb56f26812212f29556a6a717/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/703359e4b2808caa79aa28898005655b/href">https://medium.com/media/703359e4b2808caa79aa28898005655b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/263ed59c0e5aaef4b62a246c22dedaa6/href">https://medium.com/media/263ed59c0e5aaef4b62a246c22dedaa6/href</a></iframe><p>As a result, the adapter is bound directly to the data, and no redundant code exists in the presenter. The presenter was cut from the data flow, and the data flow depends on the presenter only for the initial binding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hB_zr6TZQP2XxZFM8sf6UQ.png" /></figure><p>Our adapter will now be updated of any changes and act upon them, not relying on the presenter but on the data itself.</p><p>However, the data is lifecycle aware, but our presenter is not. Once the screen is flipped, the presenter is recreated, and all the previous information we have is lost.</p><h4>Lifecycle</h4><p>Lifecycle handling used to be a synonym with boilerplate and a lot of headaches. It is imminent when we look at the current top applications in the market, most of which are locked to portrait mode.</p><p>How does the architecture components library alleviate lifecycle handling?</p><p>It provides us with a class named ViewModel.</p><p>The ViewModel class has a broader lifecycle than our screen. It survives orientation changes and thus, saves us from weird data transfers during the occasion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI0FrBgogHWiBpZwAq0Mfw.png" /></figure><p>Consequently, our screen cannot be the one who initializes a ViewModel, since it has a narrower lifecycle. Thus, a factory class exists to create or fetch from the cache the requested ViewModel instance. Even with the default configuration, in which no factory is mentioned, a default one is used behind the scenes.</p><p>Therefore, our presenter class will have a similar lifecycle to a ViewModel class. However, unlike a ViewModel class, the presenter holds a direct reference to our screen, which could result in a memory leak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0oEoIfiBG7uAQ7oAB0m0g.png" /></figure><p>As a result, the presenter could communicate with different instances of the same screen, depending on how many times the screen is destroyed and recreated. Additionally, the presenter will not be directly instantiated by the screen but by a factory, to allow for a broader lifecycle. Therefore, the screen will be removed as a constructor argument and added in setter method.</p><p>Also, the screen instance cannot be preserved in the presenter when the activity or fragment is destroyed since that would lead to a memory leak. The simplest solution is the one that requires less code and would save us from clearing the instance each time the screen is destroyed is WeakReference.</p><p>The screen will be wrapped in a WeakReference class when it would be attached. Once it is destroyed, the garbage collector will clear it for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22a79435abaa9dab23987144c92d67d7/href">https://medium.com/media/22a79435abaa9dab23987144c92d67d7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d82d351ec379e6342743b23f5caad09/href">https://medium.com/media/7d82d351ec379e6342743b23f5caad09/href</a></iframe><p>Now that our presenter is ready to have a broader lifecycle, how do we apply it?</p><p>In our application written in the MVVM path, the ViewModel is extracted in a certain way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ca51438a527959d734be38b6b8c27e6/href">https://medium.com/media/6ca51438a527959d734be38b6b8c27e6/href</a></iframe><p>After a neat, readable line, we will have a ViewModel instance. It looks like magic until we understand what happens under the hood.</p><p>For us to understand it we need to separate it into two parts:</p><ul><li><strong>ViewModelProviders.of(screen ,factory)</strong></li><li><strong>.get(ViewModel class)</strong></li></ul><p>Why is our screen necessary for the ViewModel call? Under the hood, changes were introduced to allow the feature to work. The changes, similarly to the LiveData changes, were introduced into two classes:</p><ul><li>FragmentActivity, from which AppCompatActivity inherits from</li><li>Fragment, from the support libraries</li></ul><p>What is that change? Our screen holds a reference to a new class that is responsible for storing our ViewModel classes — ViewModelStore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ySZ-bnMyTmq3bZxcCAH8gA.png" /></figure><p>Once our screen is rotated, the ViewModelStore instance survives rotation by the usual way of saving it in the onSaveInstance and retrieving it in the onCreate method. Also, if the screen is destroyed, ViewModelStore instance is destroyed along with it.</p><p>The ViewModelStore class is a simple container class that holds a map of String keys to ViewModel instances.</p><p>The screen implements an interface named ViewModelStoreOwner which has a getter method that retrieves our ViewModelStore instance. Thus, the first argument of the first part requires a class that implements a ViewModelStoreOwner interface, namely the mentioned fragment and activity up top.</p><p>The factory instance is necessary for the second part, which creates a wrapper class. The wrapper class is named ViewModelProvider, and it holds:</p><ul><li>ViewModelStore</li><li>Factory</li></ul><p>The get method inside the ViewModelProvider class retrieves a ViewModel from the ViewModelStore or creates one anew if it does not exist yet. To create a ViewModel class it calls the factory class, and once the ViewModel is created, it is stored in the ViewModelStore class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6y3f3htwuFRsUjbEDTfPqQ.png" /></figure><p>The default factory initializes a ViewModel class through reflection. As a result, if a ViewModel class has at least one argument in its constructor, the factory cannot instantiate it through reflection. Thus, in most cases, we will need a custom factory for our ViewModel classes.</p><p>I recommend using Dagger2 for the custom factory creation since it would allow different presenter classes have different argument constructors all working with a single custom factory. The way it works is the same as with ViewModel, and there are plenty of guides out there. The only difference is the naming convention which calls everything a presenter. The repositories I have created, which are linked at the bottom of the article, show how it can be done.</p><p>Now that we understand how it works behind the scenes and we have our custom factory ready, all our presenter has to do is have its base class extend ViewModel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66991d85e8eb2c5bf5d90684acf69707/href">https://medium.com/media/66991d85e8eb2c5bf5d90684acf69707/href</a></iframe><p>An additional method we gained is the onCleared method that is called each time the screen is destroyed, which could be great for clearing resources.</p><h4>MVP Route Conclusion</h4><p>Thanks to the hard work Google has put into adding under the hood changes and creating the architecture components library, we can save ourselves from the usual hassle of boilerplate code without a lot of headaches. MVP can work very nicely with architecture components, and at first glance, no one would even notice you are using them.</p><p>The example project for this part has a few different branches, all of which display a specific step in the modification of an MVP project to an MVP Architecture Components project.</p><p><a href="https://github.com/TSurkis/AppinionMVP">TSurkis/AppinionMVP</a></p><h3>MVVM route</h3><p>Why does this section exist? The architecture components library works with MVVM like a charm.</p><p>It does, on paper. However, when you first start implementing the architecture, you can’t help but notice that something is missing.</p><p>The ViewModel is de-coupled from the screen class. However, once a screen requests data, the ViewModel class cannot call the screen to display the data. If the ViewModel is aware of the screen, then we are implementing an MVP architecture.</p><p>How can our screen with its list of quotes display the quotes once the ViewModel process the response? How can the ViewModel communicate with the screen without knowing it at all?</p><p>Just as we looked at architecture components with MVVM as our example to implement it in MVP, so we can take a look at MVP in this section to implement MVVM.</p><p>How is it done in an MVP architecture?</p><p>The presenter does not know the screen directly, but by an interface it implements. However, the ViewModel cannot know the screen even by an interface since it would be an MVP architecture all over again. The answer lies in the most underestimated feature of MVP — the contract.</p><p>The beauty of MVP is that the entire screen logic is understood by reading the contract. We could design all of the screens features just by writing the contract. As a result, the contract defines our screen and its various states. Consequently, our ViewModel needs a class to describe the screen state.</p><p>To understand the screen state class, we need to ask a big question. In all architectures exists a single M letter nobody gives a second thought about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9U8yifecpyIRrmelDngzA.png" /></figure><p>A lot of people reading this article will probably say that it is the data that represents the screen or the data controller class that process the data. However, when a thought is put into it a lot of questions appear:</p><p>What if we have more than one source of data or more than one data controller? Does the M represent each one of the sources or does it represent the data or data controllers as a whole? What about screens that have no data at all?</p><p>To clarify, we are discussing architecture in this article. As a result, there is no definitive answer to any architecture but different interpretations of the same idea.</p><p>After I read an interesting article by Hannes Dorfmann in which he questions the purpose of the M word, I understood how to implement MVVM with a flavor of MVP.</p><p><a href="http://hannesdorfmann.com/android/mosby3-mvi-1">Reactive Apps with Model-View-Intent - Part1 - Model</a></p><p>What if the M in each architecture, namely in MVVM, is the screen state? To put it differently, if we take the view part of our MVP contract and convert it to a data class, we would create a screen state class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCL7OJwOfrD5c3KiTQrmgQ.png" /></figure><p>To keep the de-coupling of the screen from the ViewModel, we can leverage our knowledge of LiveData and wrap it around our screen state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c5c3e501b0f6d7d1c0c0c6daf212ce/href">https://medium.com/media/09c5c3e501b0f6d7d1c0c0c6daf212ce/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1086172a9d4ffb5519eb793e786033bd/href">https://medium.com/media/1086172a9d4ffb5519eb793e786033bd/href</a></iframe><p>Our ViewModel will have a mutable class to change each time the screen business logic dictates a change. On the other hand, the screen would have an immutable class to observe and act upon on each change. Of course, applications are more complicated than that, but generally, this idea can be grown into different screen states for different screen parts.</p><p>Moreover, it would allow us to easily test our screen or our ViewModel since one does not require the other.</p><p>Also, we would need to differentiate data from screen state data. In our application, the data of the quotes is separate from the data of the screen state. The two are not supposed to be related since they display different data types. The adapter acts upon the quotes data changes separately from the screen acting upon screen business logic.</p><p>As a result, migrating an MVP architecture to MVVM wouldn’t be that difficult in theory. The contract will be translated into a state class, and the data would be separated from the states. Consequently, the presenter will be de-coupled resulting in an MVVM architecture.</p><p>The example project of this section exists in GitHub and has similar functionality to the MVP project but with an MVVM architecture in mind:</p><p><a href="https://github.com/TSurkis/AppinionMVVM">TSurkis/AppinionMVVM</a></p><h3>General Conclusion</h3><p>The architecture components library and the changes that were introduced for it to work are a blessing for us developers. Whether you are using MVP or MVVM or even other architectures, adapting the architecture to work with architecture components is very much achievable.</p><p>So have no fear, architecture components are here (for everyone).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=237eaa831096" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/architecture-components-mvp-mvvm-237eaa831096">Architecture Components &amp; MVP \ MVVM</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SDKs & Permissions]]></title>
            <link>https://medium.com/android-news/sdks-permissions-3aa6172cdb30?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aa6172cdb30</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Mon, 11 Jun 2018 06:00:48 GMT</pubDate>
            <atom:updated>2018-06-11T06:00:48.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OEPODIXnpD-xY4zEXwhJw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/_we0BQQewBo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Masaaki Komori</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Android has many SDKs for various usages, from remote API handling to animations. Adding an SDK to your application, such as Retrofit 2.0, is a no-brainer and is even a recommendation. What about less familiar SDKs? What power can an unfamiliar SDK have over your application? Can an SDK add permissions to your application without you knowing about it?</p><p>Having a successful application suddenly displaying permission not related at all to the app, can be disastrous and result in users abandoning it.</p><p>Can any SDK insert permission stealthily into our application?</p><h4>Manifest Permissions</h4><p>I am using location permission in this article, but any other permission is relatable to this article.</p><p>I have created an application and inside it a library module. All the library module contains is a manifest with location permission.</p><p>Assembling the APK and analyzing it reveals to us that our application indeed has a location permission, thanks to our innocent SDK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*WVKg53wsi_lP476BR8VOag.png" /></figure><p>How did our application receive new permission?</p><p>When an APK file is generated, it merges all the manifest files of all the modules and libraries with the application manifest into a single big manifest file.</p><p>Our library’s manifest, containing location permission, and our application manifest merged into a single manifest file that contains the data of both.</p><p>The solution is quite simple. We can add a single line to our application manifest that states: do not merge this permission to the assembled manifest.</p><pre>&lt;uses-permission android:name=&quot;ANY_PERMISSION&quot; tools:node=&quot;remove&quot;/&gt;</pre><h4>Runtime Permissions</h4><p>Android has further complications when the application is running on an API 23+ device, and the permission is of the dangerous kind.</p><p>How can the SDK ask for runtime permissions?</p><pre>ActivityCompat.<em>requestPermissions</em>(<br>        activity,<br>        new String[]{Manifest.permission.<em>ACCESS_FINE_LOCATION</em>},<br>        <em>REQUEST_CODE</em>);</pre><p>It’s evident from the documentation that an Activity instance is required to activate runtime permissions.</p><p>Can an SDK activate a runtime-permission if it does not have an activity instance? It actually can, by asking for an application instance. All it has to do is have a class that implements <a href="https://developer.android.com/reference/android/app/Application.ActivityLifecycleCallbacks">Application.ActivityLifecycleCallbacks</a> and register to the callbacks. On each event in which the activity is visible, it can request permission.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9501db04b4d82f13a9f475debfaccde/href">https://medium.com/media/e9501db04b4d82f13a9f475debfaccde/href</a></iframe><p>Knowing all this and implementing the line of code in the previous section, if the SDK asks for a runtime-permission, the behavior is unknown due to the fragmentation issues of Android. I had an application crash on one device, and nothing happened on another.</p><h4>Conclusion</h4><p>SDKs have the power to add permissions. However, with some caution, such as checking an app manifest (via the analyze tool or the Merged Manifest tab), you can prevent unnecessary complications. So, the next time you add a suspicious SDK, be aware that it can add an unwanted secret passenger to your manifest.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aa6172cdb30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/sdks-permissions-3aa6172cdb30">SDKs &amp; Permissions</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Become an Android Painter]]></title>
            <link>https://medium.com/android-news/become-an-android-painter-aadf91cec9d4?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/aadf91cec9d4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[custom-views]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 08:22:24 GMT</pubDate>
            <atom:updated>2018-10-28T10:59:55.187Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bsw3o0HGoH3e3Pgglb0hHA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/K5gBXHSvtkc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Denise Johnson</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>For every Android developer comes a day where the Android built-in views are not enough. One day your designer or project-manager or client or even you need a unique feature. That single feature embodies a particular view that does not exist naturally in the Android world.</p><p>The first and correct instinct is to search for a library that does the trick. However, there comes a time where no library meets our standards, and even if one does, it is not exactly what we need.<br>Eventually, you will be forced to modify an existing library, assuming it is open source, or create something entirely new.</p><p>In this article, I will introduce you to the world of custom views and hopefully shed some of the ambiguity of this world that makes it look so daunting.</p><p>During the article, we will create our custom view step by step. The result will be a ViewPager page indicator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*LA-2cRTR30vcR9x-3rQslQ.gif" /></figure><h3>View lifecycle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*3LvbgrwpJAlX87rypy-h7w.png" /></figure><p>I will cover all the necessary lifecycle methods in this article separately step by step. Please note that this is not the full lifecycle. The complete list of methods is irrelevant since we can only access the ones I mentioned here. Some methods that are not mentioned can be accessed but do not seem to be built for that purpose, and therefore they are not discussed here either.</p><h3>Constructors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*-3MB755wMdjVRMRX82o9tw.png" /></figure><p>This part is self-explanatory. We will override all the constructors and create a single method to receive the attributes. We will get back to that method later on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6d50fb60f482009c44eca087ad221a8/href">https://medium.com/media/b6d50fb60f482009c44eca087ad221a8/href</a></iframe><p>There are a total of four constructors because there are four ways for our view to be created:</p><ul><li>Inflated programmatically in code.</li></ul><pre>Indicator(Context context)</pre><ul><li>Created when inflating a view from an XML.</li></ul><pre>Indicator(Context context, AttributeSet attrs)</pre><ul><li>Created when inflating a view from an XML and applying a class-specific base style from a theme attribute.</li></ul><pre>Indicator(Context context, AttributeSet attrs, int defStyleAttr)</pre><ul><li>Created when inflating a view from an XML and applying a class-specific base style from a theme attribute or a style resource. This constructor is from API 21.</li></ul><pre>Indicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)</pre><h3>Measurements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*C0-cYzne2QCsmJxGM5j4tg.png" /></figure><h4>Measurements — Rules</h4><p>Measurements are the most crucial step in creating a custom view. It is similar to marking with a pencil each circle location, right before drawing it there. And just as we don’t want to recalculate each time we draw, so does the Android operating system.</p><p>There are three essential things to know before starting this step:</p><ul><li><strong>Axes:</strong> The x,y axes are starting from the topmost left corner. If you haven’t guessed already, the heavy lifting of creating a custom view is creating an algorithm to map the coordinates of each component. Of course, the complexity differs from each custom view.<br>The values of the X-axis increase as you go right on the axes. However, unlike we were taught at school, the values of Y are increasing as we go from top to bottom. That is very important and will save you a lot of headaches.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*04Hu9WWieMWqoZln6G9a9Q.png" /></figure><ul><li><strong>Screen Sizes:</strong> Android screen sizes come in different sizes. Therefore, each value needs to be treated in its DP or SP form when initialized. During calculation, these values must be translated to pixels.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d3b055f7963bffb3b6afee15852e4bb/href">https://medium.com/media/6d3b055f7963bffb3b6afee15852e4bb/href</a></iframe><ul><li><strong>System Parameters:</strong> Unless you are the sole user of the custom views, you must not forget about padding and width\height. Would it not be weird if you added “match_parent” in the width section but the view would not stretch to the edges of the screen?<br>On a side note: from API 17 a user can define a paddingStart, paddingEnd XML attribute. The methods getRightPadding(), getLeftPadding() are sufficient since they factor in these attributes.</li></ul><p>Having the three crucial steps in our mind, we can begin.</p><h4>Measurements — Theory</h4><p>Each view has an <strong>onMeasure</strong> method. This method is called each time the view is measured. The two parameters that are received are the stats of our width and height, and they contain the information written in our layout_width and layout_height in the layout XML where our view resides.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/696bc1817373ba6ff1d97ca1c598ae68/href">https://medium.com/media/696bc1817373ba6ff1d97ca1c598ae68/href</a></iframe><p>Each value represents the specSize and specMode.</p><pre>int specMode = MeasureSpec.<em>getMode</em>(measureSpec);<br>int specSize = MeasureSpec.<em>getSize</em>(measureSpec);</pre><p><strong>specMode </strong>has three possible values:</p><ul><li><strong>MeasureSpec.EXACTLY</strong>: Represents a ‘match_parent’ value or a hard-coded value such as ‘50dp’. It means that the user or the container of the view expect the view to stretch to the given measurements without any consideration of our calculations.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac7cd46f66cbf338939b6c7b7cce06d/href">https://medium.com/media/bac7cd46f66cbf338939b6c7b7cce06d/href</a></iframe><ul><li><strong>MeasureSpec.AT_MOST</strong>: Represents a ‘wrap_content’ value. It means that the user or the container of the view allow us to decide what the width and height will be.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8a61a28ed5ddd0b0e75d205f5ed8f48/href">https://medium.com/media/a8a61a28ed5ddd0b0e75d205f5ed8f48/href</a></iframe><ul><li><strong>MeasureSpec.UNSPECIFIED</strong>: Represents a view that is in a ScrollView which means that the user or container has no idea what width and height to adjust for our view. It is very similar to MeasureSpec.AT_MOST and therefore I treat both the same.</li></ul><p><strong>specSize</strong> represents the requested size of the view by the user or by the view container in pixels and should usually be used with MeasureSpec.EXACTLY since this is the exact width\height the container or the user asks for.</p><h4>Measurements — Practice</h4><p>In most cases, to measure the width and height of a custom view, we first need to measure its components and find the components x and y coordinates. These measurements, in turn, would provide to us the height and width of our custom view.<br>Once the calculations are complete, we pass our width and height values to the setMeasuredDimension method. This method will give our view the calculated width and height.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3a9abe2445c42f60fb79ef06ea8bf0c/href">https://medium.com/media/c3a9abe2445c42f60fb79ef06ea8bf0c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a4659c56f9843fed8dfc4c2875b9de7/href">https://medium.com/media/0a4659c56f9843fed8dfc4c2875b9de7/href</a></iframe><p>Each custom view has different calculations. Therefore I did not include this part in the code example. I will say that our calculation method creates an array of positions of the circles. Each position is represented by a different x coordinate. Also, there is a single y coordinate that is common to all since they are all parallel to each other. These x and y coordinates pinpoint the exact center of each of our indicator circles.</p><p>If you want to take a look at the calculations, I have linked at the end of the article the GitHub repository of this articles code example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lw2xYGka11MrFIMqMIygsw.png" /><figcaption>Each dot represents the center of each indicator circle.</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21d09d08cc8676d94161d81e50e25ca1/href">https://medium.com/media/21d09d08cc8676d94161d81e50e25ca1/href</a></iframe><h3>Child Views — onLayout()</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*pKkwQ6bv_a0hP68gyklnSw.png" /></figure><p>If our view contains child views, this is where we measure them. In our case, we don’t have any child views, so this step is not relevant to us. However, in theory, we could create each circle as a child view and calculate them at this step.</p><h3>Drawing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*WzuuI25V87FmG5RU4UTyNA.png" /></figure><h4>Drawing — Rules</h4><p>There is a single very important rule to draw. The specific method that is called when we need to form our components, <strong>onDraw()</strong>, can be called a lot of times. Every little change in our view will result in this method call. Therefore, we must not do any memory allocations or calculations. This process needs to be fast and efficient.</p><h4>Drawing — Theory &amp; Practice</h4><p>Just like a professional painter, we have Canvas and Paint objects to draw our components. The canvas is received as a parameter in the overridden method <strong>onDraw()</strong>, and the paint objects need to be created by us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bb4f5a7333a292185609cf4b24c27f6/href">https://medium.com/media/2bb4f5a7333a292185609cf4b24c27f6/href</a></iframe><p>The Paint object is like a bucket of color. The Paint object constructor receives a flag that describes how the Paint object will be drawn when it is used. Different flags exist for different views; some are adjusted to text, some to geometry and some for both.<br>Each Paint object expects a particular style when its color is being used.<br>Both of these are out of the scope of this article since <a href="https://developer.android.com/reference/android/graphics/Paint.html">Google’s documentation</a> explains them very well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b63e576fe5a0dd63e5d2898e87c206b/href">https://medium.com/media/6b63e576fe5a0dd63e5d2898e87c206b/href</a></iframe><p><a href="https://developer.android.com/reference/android/graphics/Canvas.html">Canvas</a> is a whole world by itself. With the correct parameters, it can do anything from drawing a circle to drawing text. Each view has its complexity and required components, and the usage of the Canvas object differs according to that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a8911e3d312e03cc69829aec13e561f/href">https://medium.com/media/2a8911e3d312e03cc69829aec13e561f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ShjT54MyT50VpwAzXDMwg.png" /></figure><h3>Lifecycle control</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*g5I6OXM6x4xKdAmrP0_g6A.png" /></figure><p>This step differs from custom view to custom view. Some custom views such as our Indicator need to change and adapt to different parameters and events and some might not even need it.</p><p>Two methods can send us to a certain point in the lifecycle event of a view:</p><ul><li><strong>invalidate()</strong>: Calls the drawing process to happen again. Therefore, this method should be used when the state of the view has changed, but not its size.<br>In our case, whenever the page is changed we must update the indicator, and we do so by calling the invalidate() method.</li><li><strong>requestLayout()</strong>: Calls the entire lifecycle events to occur again. Therefore, this method should be used when the size or dimensions of our custom views change in a way that forces us to remeasure it.<br>For example, if our view contains child views, and one of the child measurements pushes it out of the view in the onLayout() method, we will call requestLayout() to recalculate the width and height of the view all over.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJcDH4rTwnyTpaJxN-ql0A.png" /></figure><h3>Attributes — Custom Parameters</h3><p>Congratulations! We have a drawn an indicator view. However, the values we entered so far were hard-coded, and as a result, our view is not reusable. To allow the user to choose the values in the XML declaring the view, we must use attributes.</p><p>How do we create a custom attribute for our view? All we need to do is create a file named attr.xml and place it in the values folder. This XML file is the home of all the custom views parameters. Therefore, if the file exists we just add the view tags.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/391af79379df06b50fadafd58da19e70/href">https://medium.com/media/391af79379df06b50fadafd58da19e70/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7d9d9062045216f0d6976f29125753d/href">https://medium.com/media/b7d9d9062045216f0d6976f29125753d/href</a></iframe><p>There is a variety of parameter types to choose from: boolean, color, dimension, enum, flag, float, fraction, integer, reference, and string. Most of the time only a select few of the parameters are relevant for us. The indicator custom view we are creating will need the next parameters:</p><ul><li>radius of the circle</li><li>distance between each circle</li><li>number of circles</li><li>color of the chosen circle</li><li>color of the default circle</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83e62a4e71f33385be56315743659a8f/href">https://medium.com/media/83e62a4e71f33385be56315743659a8f/href</a></iframe><p>If your custom view has attributes that represent a value that is vital for calculations, like our radius or distance between each circle parameters, I recommend to accept it as a dimension value. A dimension value forces the user of the view to enter a value that is in SP or DP.<br>The rest of the attributes parameter types are self-explanatory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967d6d63b8564c5ca8556a7c7190d634/href">https://medium.com/media/967d6d63b8564c5ca8556a7c7190d634/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3d26e8841217c1788aa9cfb2f98ff4a/href">https://medium.com/media/b3d26e8841217c1788aa9cfb2f98ff4a/href</a></iframe><p>An important thing to note is that the dimension type parameter that is received as a DP or SP value in the XML layout file is automatically converted to pixels when extracted from the attribute data collection.</p><h3>Conclusion</h3><p>Custom views may seem intimidating at first, but as you dive in and analyze them, they are quite simple to master. So next time you are considering a custom view don’t be afraid — it is doable.</p><p>All the code can be found in:</p><p><a href="https://github.com/TSurkis/Timdicator">TSurkis/Timdicator</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aadf91cec9d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/become-an-android-painter-aadf91cec9d4">Become an Android Painter</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where is Android Wear?]]></title>
            <link>https://medium.com/android-news/where-is-android-wear-472ed3e81432?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/472ed3e81432</guid>
            <category><![CDATA[pixel]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[wearables]]></category>
            <category><![CDATA[smartwatch]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Thu, 05 Oct 2017 08:16:14 GMT</pubDate>
            <atom:updated>2017-10-12T14:09:08.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbIORObewwk0eK_giSeKNw.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/UIUgYu9bENU">https://unsplash.com/photos/UIUgYu9bENU</a></figcaption></figure><p>On October 4th, 2017 Google has released the new line of Pixel devices. The headphone jack is dead in the eyes of Google (WHY?!), Google assistant is everywhere, and soon even your fridge will talk to you.</p><p>However, something was missing.</p><p>Apple released its stunning iPhone X but I was impressed by something else — the Apple watch series 3. Apple introduced a watch with cellular capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*41eK4qM_yZpXFpqyKXGj8A.jpeg" /></figure><p>Wait a minute; Google has already done that, right? If a tree falls in a forest and no one is around to hear it, does it make a sound?</p><p>Google stated that it would be working with big manufacturers to release more watches running Android Wear. However, where are they? If they are making ones, they sure aren’t marketing them.</p><p>The lack of marketing is apparent when looking at the global smartwatch distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*f52U9AX_nEk5NzGXjbIEvg.png" /><figcaption>Published by: <a href="https://9to5mac.com/2017/05/11/samsung-tizen-overtake-android-wear-apple-50-percent/">https://9to5mac.com/2017/05/11/samsung-tizen-overtake-android-wear-apple-50-percent/</a></figcaption></figure><p>Samsung, one of the prominent Android manufacturers, is a contender in the smartwatch industry, running Tizen. But even its market share pales in comparison to Apple — controlling over 50% of the market.</p><p>Furthermore, a year after Google stepped into the smartphone market with their Pixel phone line, there is no Pixel watch to be seen. A company with a watch operating system and a hardware division not focusing on that operating system does not paint a bright future.</p><p>Google started the Pixel line because the current market of smartphones was not how they visioned Android. Their relatively new position in the market shows their belief in Android and their hardware division. Consequently, they marketed the hell out of the Pixel which was unlike Google at the time.</p><p>All of these facts show that Google cares about the smartphone industry. Thus, does the absence of a Pixel smartwatch proves the opposite?</p><p>Google, you are the only ones that can truly compete with Apple in the smartwatch industry. Please, don’t abandon the market — remember your real fans!</p><h4>Conclusion</h4><p>It is apparent that currently, the smartwatch industry is not in the full interest of Google. Could it be that with the new <a href="http://www.businessinsider.com/why-google-paid-11-billion-for-htc-pixel-team-2017-9">HTC deal</a> Google might step up their game and introduce to the world the Pixel smartwatch? Instead, could Apple be the dark knight to push the smartwatch industry forward, hopefully waking Google up?</p><p>Clap to let me know if you enjoyed the article and follow me on Medium and Twitter ;)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=472ed3e81432" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/where-is-android-wear-472ed3e81432">Where is Android Wear?</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean your API calls!]]></title>
            <link>https://medium.com/android-news/clean-your-api-calls-79d67098d258?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/79d67098d258</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Sat, 16 Sep 2017 10:38:30 GMT</pubDate>
            <atom:updated>2017-09-18T07:54:51.025Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMuMnR3gViUP6y-ySm_-6g.jpeg" /><figcaption>Credits belong to: <a href="https://www.instagram.com/cinamon357">https://www.instagram.com/cinamon357</a></figcaption></figure><p>You need to add a new API call. Because the server error and API error handling code is usually similar to all the API calls, you just copy paste another call and change its parsing code. We have all done it at one point or another in our Android career. <br>We have all been bothered by the long never ending list of similarly looking API calls</p><p>If you’re looking for a faster to write, cleaner and less bug prone code — tag along.</p><p><em>I will be using Retrofit 2.0. Even if you are not familiar with Retrofit or don’t want to be, I recommend reading on as this article is more of a blueprint.</em></p><p><em>I will be referring in this article to the asynchronous way to do an API call using Retrofit, but the logic can be applied to a synchronous call as well.</em></p><p><em>I will also use generics so if you are not familiar or feeling rusty regarding the subject you can check out an article I wrote regarding that subject:</em></p><p><a href="https://android.jlelse.eu/generics-in-java-have-no-fear-generics-is-here-8eabe6f5d541">Generics in Java — Have no fear, Generics is here</a></p><h3>Typical Call</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d06f8ba88cfbd5baa75c29a3dbbd8a5c/href">https://medium.com/media/d06f8ba88cfbd5baa75c29a3dbbd8a5c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/870f718e243b04288dc5d233f2aa7b8e/href">https://medium.com/media/870f718e243b04288dc5d233f2aa7b8e/href</a></iframe><p>Each asynchronous Retrofit call expects a Callback&lt;T&gt; object. The T represents the object that is supposed to be received from the API call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74694946b1117bc0576cc1731f2f6b84/href">https://medium.com/media/74694946b1117bc0576cc1731f2f6b84/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d81b4e89f9e1fad70bb2fbd9b4465b7/href">https://medium.com/media/8d81b4e89f9e1fad70bb2fbd9b4465b7/href</a></iframe><p>As seen in the code, the class Callback&lt;T&gt; is an interface that is expected to be passed in for each API call.</p><h3>Generalizing the failure response</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac5115d8a7c48e0f2700803923a4e589/href">https://medium.com/media/ac5115d8a7c48e0f2700803923a4e589/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53e81bc8368d34622626d721a758bddd/href">https://medium.com/media/53e81bc8368d34622626d721a758bddd/href</a></iframe><p>In Object Oriented Programming, if class A inherits or implements from class B it can be treated as B. Therefore, if we create a class implementing the Callback&lt;T&gt; interface we can pass it instead.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ef9ecb2e0af06b6de85bf81f74bc608/href">https://medium.com/media/3ef9ecb2e0af06b6de85bf81f74bc608/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98a79bd2cfbf365c518e7289e595004e/href">https://medium.com/media/98a79bd2cfbf365c518e7289e595004e/href</a></iframe><p>The class is deliberately abstract to allow us to implement any method. The method that we will override will be the server error method.</p><p>Server errors generally have the same handling across all the API calls of the app. If a particular case of processing is needed, the method can be easily overridden.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34b6bf6ad781bd22caa6573a32783357/href">https://medium.com/media/34b6bf6ad781bd22caa6573a32783357/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7b47467faac17e8a2cf4e999c984b34/href">https://medium.com/media/d7b47467faac17e8a2cf4e999c984b34/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7d2401fe185d37515bb240239fc6cd1/href">https://medium.com/media/e7d2401fe185d37515bb240239fc6cd1/href</a></iframe><h3>Generalizing the parsing process</h3><p>The Retrofit response object holds the parsed data in the variable body that is retrieved through the body() method. Therefore, we can retrieve the object for any API call from the body() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d85a18f5318ce59d28e166ff783e60/href">https://medium.com/media/b5d85a18f5318ce59d28e166ff783e60/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/174431cbeda75432c72d484d34ee837f/href">https://medium.com/media/174431cbeda75432c72d484d34ee837f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44904d277a00654f601de6c5ef9003ab/href">https://medium.com/media/44904d277a00654f601de6c5ef9003ab/href</a></iframe><p>Our API call has gotten a hell lot shorter. However, something is missing. How do we notify the listener of the response?</p><h3>Delivering the response</h3><p>Since our class handles all the responses from Retrofit, the only way to provide the response to the listener is by passing it to the constructor and save it as a member class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baf0687c7c859fdac3d0f4ef5c557594/href">https://medium.com/media/baf0687c7c859fdac3d0f4ef5c557594/href</a></iframe><p>The final result is a just a single line:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e8790ee1c86657e06f6f4ef712981b/href">https://medium.com/media/c9e8790ee1c86657e06f6f4ef712981b/href</a></iframe><p>Each new API call would only require us to create a new POJO class to hold the parsed data and a single line to retrieve the result to the listener.<br>How great is that? ;)</p><h3>Summary</h3><p>This article is more of a blueprint than a single way to handle API calls. I hope I have inspired some of you to create a cleaner and more maintainable approach to API calls.</p><p>The code example of this article can be found in:</p><p><a href="https://github.com/TSurkis/Clean-API-Calls">TSurkis/Clean-API-Calls</a></p><p>👏 to let me know if you enjoyed the article and follow me on Medium and Twitter ;)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79d67098d258" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/clean-your-api-calls-79d67098d258">Clean your API calls!</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Developers — This Is Why You Need To Be Wary With Kotlin]]></title>
            <link>https://medium.com/android-news/android-developers-this-is-why-you-need-to-be-wary-with-kotlin-745e139db74e?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/745e139db74e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Mon, 07 Aug 2017 08:44:19 GMT</pubDate>
            <atom:updated>2017-08-07T08:44:19.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Developers — This Is Why You Need To Be Wary With Kotlin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BnAeduZFmtWSyoEvEB7SEA.png" /><figcaption>Just as one will pay attention when entering a road after seeing the sign, so should you when using a new language. Credits belong to <a href="https://www.instagram.com/cinamon357"><strong>https://www.instagram.com/cinamon357</strong></a>.</figcaption></figure><h4>History</h4><p>The Java language was built to <a href="https://en.wikipedia.org/wiki/Write_once,_run_anywhere">write once run anywhere</a>. Instead of compiling directly to machine code it compiles to bytecode, and afterward, the <a href="https://en.wikipedia.org/wiki/Java_virtual_machine">JVM</a> translates the language to machine code. This approach allows the hardware to become an abstract layer, freeing the developer from keeping it in mind when developing programs.</p><p>When the Android operating system was open for development back in 2009, the programming language to build Android applications was Java.</p><p>Fast forward to 2011, <a href="https://blog.jetbrains.com/kotlin/2011/07/hello-world-2/">JetBrains unveils the Kotlin programming language</a>. Even though it took JetBrains to <a href="https://blog.jetbrains.com/kotlin/2016/02/kotlin-1-0-released-pragmatic-language-for-jvm-and-android/">release the 1.0 stable version of Kotlin</a> 5 years, it caught the Android development world’s attention with its approach to solve the verbosity and problems of the Java programming language.</p><p><a href="https://www.youtube.com/watch?v=d8ALcQiuPWs">Followed by hysterical applauds from the crowd</a>, in 2017 <a href="https://android-developers.googleblog.com/2017/05/android-announces-support-for-kotlin.html">Google declared the Kotlin language as a first class language for Android</a>. Even though many would argue that Kotlin was ready for companies to use in their production code since version 1.0, it was the announcement of Google that made it an official companion\alternative programming language for Java.</p><h4>Why did Kotlin succeed?</h4><p>The language was aimed to be a JVM language. As a result, it could communicate with Java and vice versa. Combined with the great syntax to save us from writing the same code in a million lines of Java, it was ready to use in Android development from day one.</p><p>It would take some time for companies to make the switch and until then it is our responsibility as Android developers to study the language.</p><h4>Beware of Kotlin</h4><p>With the said above, Kotlin needs to be treated carefully. As I mentioned earlier, Kotlin is a JVM Language. As a result, the bytecode can be reverse engineered to Java code. That means that the beautiful syntax of the Kotlin class you write becomes a plain Java class.</p><p>Therefore, it is our responsibility to be careful and aware as to what our Kotlin code creates. We mustn’t rush to write a great looking Kotlin classes and marvel at their sugary syntax. We must be aware, in every step of development of what our code looks like behind the scenes. Because, as we all know it — a poorly written Java class can cause problems and issues, if not now then later down the road.</p><p>I highly recommend the following articles that explore the hidden costs of Kotlin:</p><ul><li><a href="https://medium.com/@BladeCoder/exploring-kotlins-hidden-costs-part-1-fbb9935d9b62">Exploring Kotlin’s hidden costs — Part 1</a></li><li><a href="https://medium.com/@BladeCoder/exploring-kotlins-hidden-costs-part-2-324a4a50b70">Exploring Kotlin’s hidden costs — Part 2</a></li><li><a href="https://medium.com/@BladeCoder/exploring-kotlins-hidden-costs-part-3-3bf6e0dbf0a4">Exploring Kotlin’s hidden costs — Part 3</a></li></ul><h4>Conclusion</h4><p>I encourage everybody to embrace Kotlin but be careful when doing so. Let’s keep writing great code, even in new unexplored lands.</p><h4>Personal Thoughts</h4><p>I am only now starting to study Kotlin myself, but I see the potential of it. I believe the day is not far when most of Android applications would contain at least some Kotlin code (if not 100%). <br>Maybe one day when Google will release <a href="https://en.wikipedia.org/wiki/Google_Fuchsia">Fuchsia</a>, given its <a href="https://en.wikipedia.org/wiki/Oracle_America,_Inc._v._Google,_Inc.">history with Oracle</a> and the development of <a href="https://blog.jetbrains.com/kotlin/2017/06/kotlinnative-v0-3-is-out/">Kotlin native</a>, we will see an operating system not dependent on Java (one can dream, right?).</p><p><em>Click the ❤ button to let me know if you enjoyed the article and follow me on Medium and Twitter.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=745e139db74e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/android-developers-this-is-why-you-need-to-be-wary-with-kotlin-745e139db74e">Android Developers — This Is Why You Need To Be Wary With Kotlin</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What type of Android developer are you?]]></title>
            <link>https://medium.com/android-news/what-type-of-android-developer-are-you-4d92a5eb7c9e?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d92a5eb7c9e</guid>
            <category><![CDATA[adapter]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Mon, 10 Jul 2017 06:01:01 GMT</pubDate>
            <atom:updated>2017-07-10T06:01:01.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>What type of Android developer are you?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C0gtN47UraEPQt2y5_zM1Q.png" /><figcaption>We can spot a few different ViewHolders in this real life RecyclerView grid. Credits belong to: <a href="https://www.instagram.com/cinamon357">https://www.instagram.com/cinamon357</a></figcaption></figure><p>At one point or another, we have all written an application that displays data in a list form. Whether you were around when ListView was the way to show information in a list or started developing when RecyclerView became the standard for that, you are familiar with RecyclerView and the ViewHolder design pattern.</p><p>At this point, you belong to roughly one of two groups when it comes to writing an implementation of an Adapter and ViewHolders.</p><h4>ViewHolder view class members access from the adapter</h4><p>Through public access of your ViewHolder view class members, the adapter puts the relevant data inside them during the onBindViewHolder method.</p><pre>class Adapter {</pre><pre>  ...</pre><pre>  public void onBindViewHolder(...) {  <br>    viewHolder.textOne.setText(...);<br>    viewHolder.myImageView.setImageResource(...);<br>  }</pre><pre>  ...</pre><pre>  ViewHolder {<br>    public TextView textOne;<br>    public ImageView myImageView;</pre><pre>    ...</pre><pre>  }<br>}</pre><h4>ViewHolder view class members are private</h4><p>The ViewHolder view class members are private. Therefore, for the Adapter to pass the relevant data to the ViewHolder, a unique method is created inside the ViewHolder to receive it. Then the method puts the data inside the private view class members.</p><pre>class Adapter {</pre><pre>  ...</pre><pre>  public void onBindViewHolder(...) {<br>    viewHolder.setDataInViews(...);<br>  }</pre><pre>  ...</pre><pre>  ViewHolder extends RecyclerView.ViewHolder {<br>    private TextView textOne;<br>    private ImageView myImageView;<br>  <br>    ...<br>  <br>    public void setDataInViews(...) {<br>      textOne.setText(...);<br>      myImageView.setImageResource(...);<br>    }<br>  }<br>}</pre><h4>Why does it even matter?</h4><p>If you are of the first type, your code ignores some of the most important Object Oriented Programming principles. If you are of the second category, tag along to find out how to enhance your code.</p><p>How does the first way of writing an Adapter ignore some of the most important Object Oriented Programming principles?</p><h4><a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)">Encapsulation</a></h4><blockquote>Encapsulation is bundling of data with the methods that operate on that data. It is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties’ direct access to them.</blockquote><p>It is uncommon to come across a list of items of a different kind. The elements are represented as different type ViewHolders. For each type of a ViewHolder exists different data. Using the first method will result in something of the sort:</p><pre>void onBindViewHolder(...) {<br>  switch(viewHolder.getItemViewType()){<br>    case HEADER: {<br>      ((HeaderViewHolder) viewHolder).headerTitle.setText(...);<br>      break;<br>    }<br>    case POST_ITEM: {<br>      ((RegularViewHolder) viewHolder).postTitle.setText(...);<br>      ((RegularViewHolder) viewHolder).postImage.setImage(...);<br>      break;<br>    }<br>    case Ad: {<br>      ...<br>    } <br>    ...<br>  }<br>}</pre><p>Adding an item might seem simple, just add some code into the onCreateViewHolder and onBindViewHolder methods. Consequently, more lines of code are added to our Adapter — the more ViewHolders we have, the less usable it becomes. Having even three simple ViewHolders will inflate the Adapter.</p><p>Why don’t we just create a separate class for each ViewHolder? Creating a class for each ViewHolder will leave us with classes that have public member fields. At first, it doesn’t sound too much of a bad idea. However, when we look deeper, it breaks an Object Oriented Programming principle. Where a POJO with immutable public fields will be okay, since the data is immutable anyways, a ViewHolder with public class members will pose a problem. Why? The ViewHolder fields are mutable, and that ignores one of the pillars of Object Oriented Programming: encapsulation. Furthermore, a deeper look reveals to us that the original code is also ignoring the encapsulation principle in the same manner.</p><h4><a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)">Inheritance</a></h4><blockquote>A class is based on another class, using the same implementation or specifying a new implementation to maintain the same behavior.</blockquote><p>Of course, having ViewHolders with identical class members is not uncommon as well. Using inheritance might seem the optimal solution to save us from two identical code pieces.</p><pre>onBindViewHolder(...) {<br>  switch(viewHolder.getItemViewType()){<br>    ...<br>    case AD: {<br>      ((AdViewHolder) viewHolder).adView.setAd(...)<br>      break;<br>    }<br>    case SPECIAL_AD: {<br>      ((SpecialAdViewHolder) ViewHolder).adView.setAd(...)<br>      break;<br>    }<br>    ...<br>  }<br>}</pre><pre>AdViewHolder extends RecyclerView.ViewHolder {<br>  public AdView adView;<br>  ...<br>  public AdViewHolder(View itemView) {<br>    super(itemView)<br>    adView = (AdView) itemView.findViewById(R.id.ad);<br>    ...<br>  }<br>}</pre><pre>SpecialAdViewHolder extends AdViewHolder {<br>  ...<br>  public SpecialAdViewHolder(View itemView) {<br>    super(itemView);<br>  }<br>}</pre><p><em>In the example above AdView is a custom view that could exist in a project.</em></p><p>However, when accessing the Adapter ViewHolder views in the onBindViewHolder, we are accessing each view of a ViewHolder separately since each one needs a different data in most cases. The full power of inheritance only saves us a few lines of instantiation code, missing the mark by a long shot — yet another pillar of Object Oriented crumbles. <br>Given that, using the first way to write an Adapter with inheritance seems like a waste.</p><h4><a href="https://en.wikipedia.org/wiki/Abstraction_(software_engineering)">Abstraction</a></h4><blockquote>Involves the facility to define objects that represent abstract “actors” that can perform work, report on and change their state, and “communicate” with other objects in the system.</blockquote><p>Correspondingly, not using inheritance forces us to communicate with each ViewHolder as it is since there is no general base upon which all are structured. Summing it up, each ViewHolder is unique. Therefore, the abstraction principle of Object Oriented cannot be applied in this situation.</p><h4><a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)">Polymorphism</a></h4><blockquote>The provision of a single interface to entities of different types. A polymorphic type is one whose operations can also be applied to values of some other type, or types.</blockquote><p>This principle just gathers dust in your tool belt since it has become unusable by ignoring three of the Object Oriented Programming principles mentioned above.</p><h4>OOP is broken, so what?</h4><p>Breaking Object Oriented Programming will result in a less extensible, maintainable and modular code. Your code will become your enemy.</p><p>How bad can it be?</p><h4><a href="https://en.wikipedia.org/wiki/Extensibility">Extensibility</a></h4><p>In reality, most of the adapters written in the first scheme look way messier. Frequently, more steps are involved in the onBindViewHolder method and often than not, some views depend on other views.</p><p>Additionally, the add \ update \ remove methods of your Adapter might include more logic dependent on your previous ViewHolders.</p><p>Moreover, adding even a single view to a ViewHolder will require us to create the field, instantiate it and then update its data in the Adapter onBindViewHolder method. Changing the view to a different type will compel us to change its type all across the previously mentioned areas. Having a reliable refactoring tool in Android Studio is helpful, but changing a field in one class consequently requiring us to change it in another, is bad practice and bug prone.</p><p>Before you know it, extending the class is nearly impossible without breaking something.</p><h4><a href="https://en.wikipedia.org/wiki/Software_maintenance">Maintainability</a></h4><p>Expanding on the previous section, if you have just a few simple ViewHolders then maintaining their code will not pose a problem. However, your Adapter probably has a lot of code in it, requiring you to sometimes ‘minimize’ methods in Android Studio to get to the important parts. Additionally, having a bug in a ViewHolder will most likely result in fixing both the ViewHolder and the Adapter since they are so tightly coupled. And, if that ViewHolder inherits from another ViewHolder or is inherited from, the class dependent on it needs to be updated as well.</p><p>Even if your Adapter has a single ViewHolder — don’t you find it weird that for a single ViewHolder to be fixed or updated, you have to go through the entire Adapter code?</p><p>All of a sudden, maintaining your adapter is nearly impossible.</p><h4><a href="https://en.wikipedia.org/wiki/Modular_programming">Modularity</a></h4><p>What if we have a ViewHolder we want to use in another Adapter? Seeing as it is so tightly coupled to the Adapter, we will need to copy paste it.<br>I hope you cringed reading that sentence just as I did writing it. Why? Two existing copies of our ViewHolder will double the maintenance — fixing or modifying one code piece will force us to update the second.</p><p>What about removing a ViewHolder? We will have to search for the ViewHolder usage areas across the Adapter and delete them. Yes, Android Studio has a useful refactoring tool. However, if one or more copies of our ViewHolder exist, we might completely forget about them.</p><p>That small code-change-one-hour task you had to make in your adapter turns into a day’s or more worth job.</p><h4>How to fix it?</h4><p>If ignoring the important Object Oriented principles led us here, shouldn’t we utilize them for our benefit?</p><h4>Encapsulation Utilization</h4><p>Following this principle, the member classes of a ViewHolder become private. Now that the fields are private, we can create a unique method that receives the data from the Adapter. Internally the data is allocated across the ViewHolder fields. As a result, the ViewHolder is responsible for its member classes — Seems logical, doesn’t it?</p><pre>onBindViewHolder(...) {<br>  switch(viewHolder.getItemViewType()) {<br>    case HEADER:{<br>      ((HeaderViewHolder) viewHolder).setHeaderData(...);<br>      break;<br>    }<br>    case AD: {<br>      ((AdViewHolder) viewHolder).setAdData(...);<br>      break;<br>    }<br>    case SPECIAL_AD: {<br>      ((SpecialAdViewHolder) viewHolder).setSpecialAdData(...);<br>      break;<br>    }<br>    ...<br>  }<br>}</pre><pre>HeaderViewHolder extends RecyclerView.ViewHolder {<br>  ...<br>  setHeaderData(...) {<br>    headerTitle.setText(...);<br>  }<br>}</pre><pre>AdViewHolder extends RecyclerView.ViewHolder {<br>  ...<br>  setAdData(...) {<br>    adView.setAd(...);<br>  }<br>}</pre><pre>SpecialAdViewHolder extends RecyclerView.ViewHolder {<br>  ...<br>  setSpecialAdData(...)}<br>    specialAdView.setAd(...);<br>  }<br>}</pre><h4>Inheritance Utilization</h4><p>Looking at the example code above, the AdViewHolder and SpecialAdViewHolder have the same view used. This time, the full power of inheritance can be utilized.</p><pre>onBindViewHolder(...) {<br>  switch(viewHolder.getItemViewType()) {<br>    case HEADER:{<br>      ((HeaderViewHolder) viewHolder).setHeaderData(...);<br>      break;<br>    }<br>    case AD: <br>    case SPECIAL_AD: {<br>      ((AdViewHolder) viewHolder).setAdData(...);<br>      break;<br>    }<br>    ...<br>  }<br>}</pre><pre>HeaderViewHolder extends RecyclerView.ViewHolder {<br>  ...<br>  setHeaderData(...) {<br>    headerTitle.setText(...);<br>  }<br>}</pre><pre>AdViewHolder extends RecyclerView.ViewHolder {<br>  ...<br>  setAdData(...) {<br>    adView.setAd(...);<br>  }<br>}</pre><pre>SpecialAdViewHolder extends AdViewHolder {<br>  ...<br>}</pre><p>The solution looks great, but what about the rest of the ViewHolders? This solution does not cure us yet of the horrors of the switch-case code.</p><h4>Abstraction and Polymorphism Utilization</h4><p>Studying the new approach regarding ViewHolders, it is easily noticeable that all the ViewHolders have a single method of data entry. That allows us to create a general base for all the ViewHolders, treating them as the same one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4c117df402f13b434f5c18cdf86e1ce/href">https://medium.com/media/a4c117df402f13b434f5c18cdf86e1ce/href</a></iframe><pre>onBindViewHolder(...) {  <br>  int viewType = viewHolder.getItemViewType();<br>  Object data = getData(viewType, position);<br>  viewHolder.setDataInViews(data);<br>}</pre><pre>public Object getData(int viewType, int position) {<br>  Object data = null;<br>  switch (viewType) {<br>    case HEADER: {<br>      ...<br>      data = ...<br>  }<br>    case AD:<br>    case SPECIAL_AD: {<br>      data = ...<br>  }<br>  return data;<br>}</pre><pre>HeaderViewHolder extends BaseDataViewHolder&lt;String&gt; {<br>  ...<br>  setHeaderData(String title) {<br>    headerTitle.setText(title);<br>  }<br>}</pre><pre>AdViewHolder extends BaseDataViewHolder&lt;Ad&gt; {<br>  ...<br>  setAdData(Ad ad) {<br>    adView.setAd(ad);<br>  }<br>}</pre><pre>SpecialAdViewHolder extends AdViewHolder {<br>  ...<br>}</pre><p><em>Uncertain about generics? Check out my in-depth article:</em></p><p><a href="https://android.jlelse.eu/generics-in-java-have-no-fear-generics-is-here-8eabe6f5d541">Generics in Java — Have no fear, Generics is here</a></p><p>It might seem as if we are done, but in reality, we moved the problem elsewhere since the switch-case still exist. Of course, we are far from over — we need a better solution.</p><h4>MVP to the rescue</h4><p>If unfamiliar or uncertain about MVP this is a great article explaining it:</p><p><a href="https://medium.com/@cervonefrancesco/model-view-presenter-android-guidelines-94970b430ddf">Model-View-Presenter: Android guidelines</a></p><p>Why MVP? In this architecture, the view is “dumb” and asks the presenter what to do. Therefore, the presenter will hold getter methods — one getter method per data.</p><pre>class Presenter {</pre><pre>  ...</pre><pre>  String getHeaderTitle() {<br>    ...<br>  }<br>  <br>  Ad getAd(int position) {<br>    ...<br>  }<br>  <br>  PostItem getPostItem(int position) {<br>    ...<br>  }<br>}</pre><p>The Adapter will pass the presenter instance to each ViewHolder in the onBindViewHolder method.</p><pre>class Adapter {<br>  <br>  ...</pre><pre>  onBindViewHolder(...) {<br>    viewHolder.setDataInViews(presenter);<br>  }<br>}</pre><p>And each ViewHolder will ask a corresponding getter method for data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39c9e4869e5bb6f2cd1c20b1eff71d8c/href">https://medium.com/media/39c9e4869e5bb6f2cd1c20b1eff71d8c/href</a></iframe><pre>HeaderViewHolder extends BaseViewHolder {<br>  ...<br>  setDataInViews(Presenter presenter) {<br>    String title = presenter.getHeaderTitle();<br>    headerTitle.setText(title);<br>  }<br>}</pre><pre>AdViewHolder extends BaseViewHolder {<br>  ...<br>  setDataInViews(Presenter presenter) {<br>    Ad ad = presenter.getAd(getAdapterPosition());<br>    getAdadView.setAd(ad);<br>  }<br>}</pre><pre>SpecialAdViewHolder extends AdViewHolder {<br>  ...<br>}</pre><pre>PostItemViewHolder extends BaseViewHolder {<br>  ...<br>  setDataInViews(Presenter presenter) {<br>    PostItem post = presenter.getPostItem(getAdapterPosition());<br>    ...<br>  }<br>}</pre><p>Thus, all the above mentioned Object Oriented Programming principles apply. If you look close enough, you will realize that we achieved the second method of writing an Adapter — welcome to the other side!</p><h4>How is the data handled?</h4><p>Instead of allocating the data when the ViewHolder requests it, it is mapped before the adapter initialization.</p><p>The Presenter analyzes the data and constructs two data collections:</p><ul><li>A map of views. Each item is an integer that represents the view type; the index is its location in the list.</li><li>A map of data locations. Each item is an integer that represents the location of the data in the data collection; the index is its location in the list.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*nMAGuKGj3fEsjvX_kP-Zew.png" /></figure><p>When the getItemViewType method of the adapter is called, the map of view types is queried to retrieve the view type in the requested position.<br>Correspondingly, in the onBindViewHolder when data is requested the mapped UI index points to the relevant data collection.</p><p>I have created an example project on GitHub. The project represents all the examples in the article and ranges from the most modular to the least modular solution.</p><p><a href="https://github.com/TSurkis/MVP-Adapter">TSurkis/MVP-Adapter</a></p><h4>Conclusion</h4><p>I reached each conclusion laid out in this article over the course of my Android development career, and it is a representation of the various Adapter ways I have tried over the years.<br>The code written in my GitHub repository has three various code examples in achieving all that I have written above and should be seen as a blueprint more than a single way to write an Adapter.<br>The beauty of Android is its versatility, and there is no right way for everything but a few good ways.<br>If you have suggestions or questions, feel free to write them in the comment section below.</p><p><em>Click the ❤ button to let me know if you enjoyed the article and follow me on Medium and Twitter.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d92a5eb7c9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/what-type-of-android-developer-are-you-4d92a5eb7c9e">What type of Android developer are you?</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generics in Java — Have no fear, Generics is here]]></title>
            <link>https://medium.com/android-news/generics-in-java-have-no-fear-generics-is-here-8eabe6f5d541?source=rss-331f2940e0d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eabe6f5d541</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[T.Surkis]]></dc:creator>
            <pubDate>Tue, 16 May 2017 09:58:48 GMT</pubDate>
            <atom:updated>2017-05-28T18:36:04.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*OkG5AXrk_eafkgQ5jwCjLQ.jpeg" /><figcaption><a href="http://www.clipartbest.com/clipart-RcGG5agpi">http://www.clipartbest.com/clipart-RcGG5agpi</a></figcaption></figure><p>Generics is one of the best tools you could have in your tool belt. Whether you used generics before or were too afraid to, I welcome you to this generic overview (pun intended).</p><h3><strong>Methods</strong></h3><p>We will assume that <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])">Arrays.toString()</a> does not exist and we need an integer array printing method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa08763af6ca4b211136aada48bcbc56/href">https://medium.com/media/fa08763af6ca4b211136aada48bcbc56/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d11ec848baabb757991518d934a76582/href">https://medium.com/media/d11ec848baabb757991518d934a76582/href</a></iframe><p>If a double array printing method is required, a simple copy paste action (mastery of software developers) followed by variable type name changes will result in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2aef7f07f63ee4d5193b767b67093233/href">https://medium.com/media/2aef7f07f63ee4d5193b767b67093233/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1725bfceb9089cf716764f809227138/href">https://medium.com/media/e1725bfceb9089cf716764f809227138/href</a></iframe><p>Similarly, if a new printing method for string arrays is needed, we could copy-paste and change the variable name types. However, a close look at both methods reveals similarities. The only difference between the two are the places in which we declare the variables.</p><pre><strong>public void printArray(</strong>int <strong>[] array) {</strong></pre><pre><strong>public void printArray(</strong>double <strong>[] array) {</strong></pre><pre><strong>for(</strong>Integer <strong>printObject : array) {</strong></pre><pre><strong>for(</strong>Double <strong>printObject : array) {</strong></pre><p>In these cases, generic method types roll up their sleeves. Using a generic method type we can create a general method that can accept any variable type during usage.</p><pre><strong>public void printArray(</strong>ArrayType <strong>[] array) {</strong></pre><pre><strong>for(</strong>ArrayType <strong>printObject : array) {</strong></pre><p>Similar to a regular method, a generic method has a special place to declare the variable types it will receive. The declaration will take place before the return type and will appear with an opening ‘&lt;’ sign followed by a closing ‘&gt;’ sign. Therefore, the correct way to write the method is as followed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6885d06ec70b355b1e5ec32d84c7b5d4/href">https://medium.com/media/6885d06ec70b355b1e5ec32d84c7b5d4/href</a></iframe><p>The explicit way to use a generic method is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdf245ba80304fab95b61ca11d3116b3/href">https://medium.com/media/bdf245ba80304fab95b61ca11d3116b3/href</a></iframe><p>Luckily for us, the variable type recognition is being done by recognizing the variable type passed inside. Consequently, the common way to use a generic method is in an implicit form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c401890ffab4543df3ec4918aaf5d511/href">https://medium.com/media/c401890ffab4543df3ec4918aaf5d511/href</a></iframe><p>Due to generics API restrictions, only variable types that extend object types can be used as variable types. Therefore, primitives we used before will now be used in their class form.</p><p>Of course, generic methods are not restricted to a single variable type.<br>Just like a method, we can add as many variable types as we want, separated by a comma.</p><p>For example, we can create a dual array printing method. For simplicity sake, let’s assume that the received arrays are not null and are the same size.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca242cf22022fe8754484a13d98ce5d9/href">https://medium.com/media/ca242cf22022fe8754484a13d98ce5d9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3c939f60b219b6b5599f00bce840712/href">https://medium.com/media/b3c939f60b219b6b5599f00bce840712/href</a></iframe><h3><strong>Classes</strong></h3><p>What if we wanted that class to hold a generic class member?</p><pre>public class ArrayWrapper {<br>  private ArrayType [] array;</pre><pre>  public &lt;ArrayType&gt; void printAnyArray() {<br>    ...<br>  }<br>}</pre><p>Just as a generic method has its place for variable types, so does a class. The declaration will be after the class name and will appear with an opening ‘&lt;’ sign followed by a closing ‘&gt;’ sign.<br>In the next example, we wrap an array with a generic class and provide a printing method. Since the array used in the method is the same type as the variable type declared in the class, we can drop the generic declaration from the method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37d3f46ab4e5e0665485b698ec090f60/href">https://medium.com/media/37d3f46ab4e5e0665485b698ec090f60/href</a></iframe><p>Using a generic class resembles the generic method usage in that it has two ways — the explicit way and the implicit way.</p><p>The explicit way is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3693ed2f68e24cfc2e8395135930507/href">https://medium.com/media/d3693ed2f68e24cfc2e8395135930507/href</a></iframe><p>The implicit way is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a20ae7bb36dc881afec316f7cb80ca15/href">https://medium.com/media/a20ae7bb36dc881afec316f7cb80ca15/href</a></iframe><p><strong>Unlike generic methods, when using classes, I strongly advise using the explicit way.</strong></p><p>Why?</p><p>Take a look at the next example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/210f6267c1d50e29cd34403a071f3605/href">https://medium.com/media/210f6267c1d50e29cd34403a071f3605/href</a></iframe><p>The default constructor is employed. Therefore, the variable type of the class is only decided when the setter method is used in runtime.</p><p>What would happen if the class setter method is used far from its instantiation? Looking at the creation alone would not provide an answer since the variable type is not declared there. We would need to track the first usage of the setter method. Whereas, if the explicit way were used, a look at the instantiation would be enough.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79aecb35effcd013b2bc3ca4d5bf58a0/href">https://medium.com/media/79aecb35effcd013b2bc3ca4d5bf58a0/href</a></iframe><p>Of course, all the previous rules apply when we add a generic method with a different variable type than our classes variable type. In the next example, our class has a generic method that receives an array and prints it alongside the array of the class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b567ceb4b20915e3f492945b7fb69524/href">https://medium.com/media/b567ceb4b20915e3f492945b7fb69524/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7613d0c21ab99649b26ba45bf7dca1db/href">https://medium.com/media/7613d0c21ab99649b26ba45bf7dca1db/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91f70b814098641bcbed136b79d8f191/href">https://medium.com/media/91f70b814098641bcbed136b79d8f191/href</a></iframe><h3>Inheritance &amp; Implementation</h3><p>I am an Android developer, and for my personal project, I was in need of a database. Not keen to write the implementation myself, my research has brought me up to <a href="http://greenrobot.org/greendao/">GreenDAO</a>.</p><p>One of my POJO classes has an ArrayList of Integer types as a class member. However, GreenDAO, just like other database solutions, offers only a limited set of types — ArrayList is not one of them.<br>The answer comes in the form of a generic interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f9af641c8be0a6c4c55ab1ee1be8604/href">https://medium.com/media/3f9af641c8be0a6c4c55ab1ee1be8604/href</a></iframe><p>This code was copied from the GreenDAO official GitHub Repository:</p><p><a href="https://github.com/greenrobot/greenDAO/blob/master/greendao-api/src/main/java/org/greenrobot/greendao/converter/PropertyConverter.java">greenrobot/greenDAO</a></p><p>P represents a value in the POJO class.<br>D represents the POJO value in its database form.<br>The implementing class has to create a conversion in both directions.</p><p>I have decided save my ArrayList of Integer types in the database as a String. I chose String because of its simplicity. The code itself will explain the conversion, but it is not the purpose of this article.</p><p>How do we apply our Generics API knowledge?<br>Our POJO member class value is an ArrayList of Integer types. Therefore it will be placed instead of the P.<br>The ArrayList of Integer types will be translated to a String. Therefore it will be placed instead of the D.</p><pre>... implements PropertyConverter&lt;<strong>ArrayList&lt;Integer&gt;</strong>, <strong>String</strong>&gt;</pre><p>Wait, what? A generic inception? Exactly!<br>The Generics API allows us to insert generic types as generic types (it can go even further depending on how crazy you are).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cb38a43b10bcc7ce7b701c2f50a83ac/href">https://medium.com/media/7cb38a43b10bcc7ce7b701c2f50a83ac/href</a></iframe><p>Let’s take it a step further.</p><p>Before the class can be used, it needs to be tested (using JUnit 4). <br>The testing algorithm is pretty basic and is not part of this article, but this is the gist of it:</p><pre>testEntityConversion(entityValue, converter) {<br>  databaseValue = converter.convertToDatabaseValue(entityValue)</pre><pre>  newEntityValue = converter.convertToEntityValue(databaseValue)</pre><pre>  assertEquals(entityValue, newEntityValue)<br>}</pre><pre>testDatabaseConversion(databaseValue, converter) {<br>  entityValue = converter.convertToEntityValue(databaseValue)</pre><pre>  newDatabaseValue = converter.convertToDatabaseValue(entityValue)</pre><pre>  assertEquals(databaseValue, newDatabaseValue)<br>}</pre><p>The inserted value is converted to its other value and back. Only when the result equals the inserted value, the test has passed and the conversion works flawlessly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5edaf0ada0ef0f7cf9578f355ffce7d/href">https://medium.com/media/d5edaf0ada0ef0f7cf9578f355ffce7d/href</a></iframe><p>Just after I wrote the code in my project, I have created another converter class. As a result, another test class was needed. However, I detected a pattern.<br>Sounds familiar? You might have already noticed that the written algorithm is very general. <br>You have guessed correctly, we can create a generic converter test class.</p><p>How do we start?</p><p>Before a single line of code is even written, we need to analyze the components:</p><ul><li>Entity value.</li><li>Database value.</li><li>Converter.</li></ul><p>Each of the components can be replaced with a general one without breaking the written above algorithm. The converter test class general structure will be as followed:</p><pre>public class GeneralConverterTest&lt;EntityType, DatabaseType, ConverterType&gt;</pre><p>It might seem as if we are done. But, if we do the modifications, we will run into a problem.</p><pre>converter.<strong>convertToEntityValue(</strong>...<strong>)</strong></pre><pre>converter.<strong>convertToDatabaseValue(</strong>...<strong>)</strong></pre><p>The ConverterType we added is expected to extend the Object class. However, the Object class does not have these methods.<br>In some way, we need to declare in the generic class that a class type implementing PropertyConverter&lt;P, D&gt; is the only class type we can pass.</p><p>How?</p><p>Generics API allows us to add the ‘extends’ keyword inside the declaration. Oddly enough, it applies to classes that implement an interface or extend a class.</p><pre>...&lt;..., ..., ConverterType extends PropertyConverter&gt;</pre><p>We can now use the ConverterType methods. However, we did not declare the variable types the converter methods receive.<br>Just as we extended the PropertyConverter&lt;P, D&gt; class and passed down the variable types we add the variable types to the PropertyConverter&lt;P, D&gt;.</p><pre>...&lt;...,...,ConverterType extends PropertyConverter&lt;EntityType, DatabaseType&gt;&gt;</pre><p>The full declaration means that the EntityType, DatabaseType and a ConverterType that implements an interface with EntityType and DatabaseType as variable types are expected as variable types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d4400279b99218b8ee3974db16b48b/href">https://medium.com/media/52d4400279b99218b8ee3974db16b48b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2c57abe41569bcdf418b07f0ba9300/href">https://medium.com/media/cd2c57abe41569bcdf418b07f0ba9300/href</a></iframe><h3>Conclusion</h3><p>Generic API is quite flexible and can be adapted to various scenarios. If you are detecting a repeating pattern or feel like you are copy-pasting don’t forget about generics — it may come in handy!</p><p>All the examples in this article can be found in here:</p><p><a href="https://github.com/TSurkis/Medium-Article-Generics-in-Java-Examples">TSurkis/Medium-Article-Generics-in-Java-Examples</a></p><p><em>Click the ❤ button to let me know if you enjoyed the article and follow me on Medium.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2F3e491f%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2F3e491f%2F&amp;image=http%3A%2F%2Fapi.screenshotlayer.com%2Fapi%2Fcapture%3Faccess_key%3Dfe59908dad3baab69ffab249a2224b03%26viewport%3D1024x612%26width%3D1000%26url%3Dhttps%253A%252F%252Fupscri.be%252F3e491f%253Fscreenshot&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href">https://medium.com/media/fedb9f91e907af2468a937c944ed32ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eabe6f5d541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/generics-in-java-have-no-fear-generics-is-here-8eabe6f5d541">Generics in Java — Have no fear, Generics is here</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>