<?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 David Guerrero on Medium]]></title>
        <description><![CDATA[Stories by David Guerrero on Medium]]></description>
        <link>https://medium.com/@davidguerrerod?source=rss-2f152e258d5a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lmQOpWU0eVg_38R5Xi7xmw.png</url>
            <title>Stories by David Guerrero on Medium</title>
            <link>https://medium.com/@davidguerrerod?source=rss-2f152e258d5a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:47:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidguerrerod/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[Compose Multiplatform: A ready-made Template for your next App]]></title>
            <link>https://davidguerrerod.medium.com/compose-multiplatform-a-ready-made-template-for-your-next-app-7c76cb746041?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c76cb746041</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[compose-multiplatform]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 20:27:43 GMT</pubDate>
            <atom:updated>2025-01-01T20:27:43.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYB_L5sqh8xqdBHC-IJ9Rg.jpeg" /></figure><p>Setting up a Compose Multiplatform project can be time-consuming and sometimes a non-trivial task, especially when ensuring all components work seamlessly across iOS and Android. Compose Multiplatform simplifies this process by sharing not only the business and data logic but also the views, enabling developers to write consistent, reusable UI code. To make this even easier, I’ve created a <strong>Compose Multiplatform Template</strong>, now available on GitHub: <a href="https://github.com/DGuerrero/compose-multiplatform-template">DGuerrero/compose-multiplatform-template</a>.</p><p>This template is designed to get you up and running quickly with a solid foundation for building cross-platform apps. It includes the dependencies to most common libraries and is implemented with a basic clean architecture structure, using shared view models and database.</p><h3>Project Highlights</h3><p>The Compose Multiplatform Template has following features:</p><h4>1. Bottom Bar Navigation</h4><p>The app includes a bottom bar navigation pattern with three screens. <strong>Screen1 </strong>displays a list with example “lorem ipsum” data and images fetched via a REST API. <strong>Screen2 and Screen3 </strong>are empty and ready for you to add any content.</p><p>The navigation between screens is performed via Compose Navigation and again shared between both platforms.</p><h4>2. Clean Architecture</h4><ul><li><strong>Views:</strong> Built with Jetpack Compose, ensuring a modern declarative UI for both platforms.</li><li><strong>View Model:</strong> Shared between both platforms and implemented with Android Jetpack.</li><li><strong>Repository:</strong> Combines a REST API and local repository for data management.</li><li><strong>Local Cache:</strong> Powered by <strong>SqlDelight</strong>, enabling a robust and platform-agnostic local database solution.</li></ul><h3>Key Libraries</h3><ul><li><strong>Koin:</strong> Manages dependency injection to keep the codebase modular and testable.</li><li><strong>Ktor:</strong> Handles remote network requests.</li><li><strong>SqlDelight:</strong> Provides a multi-platform database for local caching, with type-safe queries and shared schemas.</li><li><strong>Coil:</strong> Loads and caches images efficiently, ensuring smooth and performant image rendering across platforms.</li></ul><h3>Future Roadmap</h3><p>This template is a work in progress, here’s what’s next on my agenda:</p><ul><li><strong>Unit and UI Tests:</strong> No surprises here, UI test using Espresso and JUnit for Unit Testing,</li><li><strong>Platform-Specific Features:</strong> Add examples of handling iOS and Android-specific features within the shared codebase.</li><li><strong>iOS look &amp; feel: </strong>Experiment with <a href="https://github.com/alexzhirkevich/compose-cupertino">Compose Cupertino</a> (or similar) to get a more Apple platform specific UI.</li></ul><h3>How to Get Started</h3><ol><li>Clone the repository from GitHub: <a href="https://github.com/DGuerrero/compose-multiplatform-template">compose-multiplatform-template</a>.</li><li>Open the project in Android Studio, select the compose App configuration and run the Android app.</li><li>When the Android finishes, select the iOSApp configuration and run as well.</li><li>Modify the project naming for your specific project and start adding features!</li></ol><h3>Summary</h3><p>This Compose Multiplatform Template is designed to save you time and streamline your development workflow, making it an ideal starting point for your next project. Whether you’re working on a prototype or a production app, this template has you covered.</p><p>Check out the <a href="https://github.com/DGuerrero/compose-multiplatform-template">GitHub repository</a>, and I’d love to hear your thoughts and contributions!</p><p>If you find this project helpful, don’t forget to star the repo and share it with your network. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c76cb746041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An effective testing strategy for Android (Part 2) – Unit Testing]]></title>
            <link>https://proandroiddev.com/an-effective-testing-strategy-for-android-part-2-unit-testing-86edaf83d348?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/86edaf83d348</guid>
            <category><![CDATA[android-development]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Mon, 26 Aug 2024 21:56:34 GMT</pubDate>
            <atom:updated>2024-08-28T15:18:55.824Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xgVkMfA5q0zWmqn44BH14w.jpeg" /></figure><p>In the <a href="https://medium.com/proandroiddev/an-effective-testing-strategy-for-android-i-4a269d134acf">first part</a> of this series we described the elements that define a good testing strategy and the different types of tests we should implement. In this second part, we focus on unit testing — what they are, how, and when to implement them.</p><h3>Definition of Unit Test</h3><p>In a nutshell, a unit test is an automated piece of software that verifies the correctness of a small part of the codebase, does it quickly, and in isolation from the rest of the system. Let’s see an example:</p><pre>@Test<br>fun `calculateStops returns correct number of stops for a given line ID`() {<br><br>  val repository = LinesRepository()<br>  val route = BusRoute(repository, &quot;Line123&quot;)<br>    <br>  val numberOfStops = route.calculateStops()<br><br>  assertEquals(3, numberOfStops)<br>}</pre><p>As we can see we have a class named “BusRoute” that calculates the number of stops for a specific bus line ID. In this test, we check that the function works properly and returns the expected number of stops for that bus line.</p><h3>The two Unit Testing schools of Thought</h3><p>The software engineering community generally agrees on the key characteristics of a unit test, but opinions differ when it comes to the best approach for isolation. When we talk about testing a small piece of code, what exactly does that mean? Is it just a single function, or does it refer to an entire class? Could it be a component that includes other classes as collaborators? Should these dependencies be tested as well, or is it acceptable to replace them with substitutes like mocks or stubs? Let’s explore these questions in more detail.</p><h4>The Classical or Detroit School</h4><p>The basic idea here is that we have to test the unit of code using real dependencies, ensuring that the functionality works as expected with real objects interacting with each other. This guarantees usage close to real-world scenarios, reducing the risk of false positives.</p><p>In this approach, isolation doesn’t mean completely detaching the code under test from the rest of the system, including collaborators and dependencies. We only want to isolate this particular functionality from any other logic not related to the Subject Under Test (SUT from now on). The dependencies need to be the same as in the production code. However, to keep the tests fast, reliable, and to avoid flakiness, we must avoid adding real instances of “out-of-process” dependencies like databases, network requests, etc.</p><p>In the above example, when we instantiate the SUT, BusRoute, we pass a real instance (not a mock) of the LinesRepository.</p><p>The main criticism of this school of thought is that the dependency graph of a single component can get really complicated, and providing real objects for every single component can be arduous or even impossible in some cases. Still, it is worth aiming for this approach because of the advantages mentioned earlier, and we should define clear boundaries for when to use mocks instead of real objects.</p><h4>The Mockist or London School</h4><p>Proponents of this approach suggest that the SUT must be completely isolated, with any dependency mocked and replaced to provide the bare minimum functionality needed to exercise the correctness of the test unit. The idea is to exclusively test the SUT and nothing else, assuming that every collaborator will be tested on its own. Let’s see the above example now with the Mockist approach:</p><pre>@Test<br>fun `calculateStops returns correct number of stops for a given line ID using a mocked service`() {<br>    <br>    val busStopService = mock(BusStopService::class.java)<br>    `when`(busStopService.getStops(&quot;Line123&quot;)).thenReturn(listOf(&quot;Station A&quot;, &quot;Station B&quot;, &quot;Station C&quot;))<br>    <br>    val route = BusRoute(busStopService)<br>    val numberOfStops = route.calculateStops(lineId)<br><br>    assertEquals(3, numberOfStops)<br>}</pre><p>In this example, the SUT is the BusRoute class, and the dependencies have been mocked to provide the expected behavior. This is valuable because the focus is 100% on the functionality of this class and nothing else. If a regression is introduced and the test fails, we can be completely certain that the bug is in this element and only here. This granularity provides an efficient and fast process for finding issues in our code.</p><h3>What should a Unit Test cover?</h3><p>When discussing testing, one of the main challenges is defining the different types of tests: what should we validate, what is the scope of the code under test, and what components or parts should be part of our strategy. So, what are we supposed to test in a unit test?</p><h4>Behaviour Over Implementation</h4><p>Test the outcomes and results of the unit’s behavior, not the implementation details or internal functionality. In the examples above, even if we change how we calculate the number of stops, the outcome should be the same. Therefore, the test should always validate the outcome and not how we accomplish that.</p><h4>Single Responsibility</h4><p>The tests should verify one single unit of behavior so it’s easy to understand and maintain, and so that we have a clear and single source of the issue. For example, in the bus route example, we should test only the number of stops and not try to also validate, say, the names of the stops (which might be returned by a different function).</p><h4>Edge Cases</h4><p>Your tests should cover edge cases like null inputs, empty values, error cases, and so on — not only the typical happy paths. In the example above, we should also test what happens when we pass an invalid bus line ID, or what happens if the repository call fails, etc.</p><h3>Anatomy of a Unit Test</h3><p>The Arrange — Act — Assert (AAA) pattern has been widely accepted in the software industry as it provides a methodical and clear approach for writing and maintaining tests. The idea is to divide the test in three parts:</p><h4>Arrange</h4><p>We set up the initial conditions required for the test, such as initialising objects and configuring mock behaviour.</p><h4>Act</h4><p>This is where we execute the functionality we want to validate.</p><h4>Assert</h4><p>Finally, we verify the outcome of the functionality under test and check that it matches the expected result.</p><p>Here’s how this looks in practice:</p><pre>@Test<br>fun `calculateStops returns correct number of stops for a given line ID`() {<br>    <br>  // Arrange<br>  val repository = LinesRepository()         // Set up the real or mock repository<br>  val route = BusRoute(repository, &quot;Line123&quot;)// Create the BusRoute instance with the given line ID<br><br>  // Act<br>  val numberOfStops = route.calculateStops() // Call the method under test<br><br>  // Assert<br>  assertEquals(3, numberOfStops)             // Verify that the result matches the expected number of stops<br>}</pre><h3>Test Doubles</h3><p>In the London or Mockist School of testing, we often refer to all objects used to replace dependencies of the SUT as “mocks.” However, in reality, there are several distinct types of test doubles, each serving a specific purpose in unit testing.</p><h4>Dummy</h4><p>A dummy is an object that is passed as a dependency but is never actually used in the test. It is included only to satisfy the method or class parameters.</p><p><strong>When to Use:</strong> Use a dummy when the SUT requires an object that is irrelevant to the test, such as a Context in a test where the context is not directly utilized.</p><p><strong>Example:</strong> Passing a dummy Context when testing a method that doesn&#39;t interact with the Android framework.</p><p><strong>Library/Framework:</strong> No specific library is needed for dummies, as they can simply be placeholders or null objects.</p><pre>@Test<br>fun `calculateStops returns correct number of stops using a dummy Context`() {<br>    // Arrange<br>    val dummyContext = mock(Context::class.java)<br>    val route = BusRoute(dummyContext, &quot;Line123&quot;)<br><br>    // Act<br>    val numberOfStops = route.calculateStops()<br><br>    // Assert<br>    assertEquals(3, numberOfStops)<br>}</pre><h4>Fake</h4><p>A fake is a working implementation of a dependency with simplified logic. It provides just enough functionality to support the SUT during the test.</p><p><strong>When to Use:</strong> Use a fake when you need a lightweight, functional version of a component, such as an in-memory database, which is faster and easier to manage during testing.</p><p><strong>Example:</strong> An in-memory implementation of SharedPreferences or a fake network service that returns predefined responses.</p><p><strong>Library/Framework:</strong></p><ul><li><strong>Room:</strong> Use an in-memory database configuration to fake the persistence layer.</li><li><strong>Faker:</strong> Use libraries like <a href="https://github.com/square/okhttp/tree/master/mockwebserver">MockWebServer</a> to fake network responses.</li></ul><pre>class FakeBusStopService : BusStopService {<br>    override fun getStops(lineId: String): List&lt;String&gt; {<br>        return listOf(&quot;Station A&quot;, &quot;Station B&quot;, &quot;Station C&quot;)<br>    }<br>}<br><br>@Test<br>fun `calculateStops returns correct number of stops using a FakeBusStopService`() {<br>    // Arrange<br>    val fakeService = FakeBusStopService()<br>    val route = BusRoute(fakeService, &quot;Line123&quot;)<br><br>    // Act<br>    val numberOfStops = route.calculateStops()<br><br>    // Assert<br>    assertEquals(3, numberOfStops)<br>}</pre><h4>Stub</h4><p>A stub is a test double that provides specific, predetermined responses to method calls. This allows the SUT to proceed with its logic without relying on the full implementation of the dependency.</p><p><strong>When to Use:</strong> Use stubs when you need to control the output of a dependency to test specific scenarios within the SUT.</p><p><strong>Example:</strong> Stubbing a method in a repository to return a specific value when testing a ViewModel.</p><p><strong>Library/Framework:</strong></p><ul><li><strong>Mockito:</strong> Use the when().thenReturn() construct to create stubs.</li><li><strong>Kotlin:</strong> Use <a href="https://mockk.io/">MockK</a> for more idiomatic Kotlin stubbing.</li></ul><pre>@Test<br>fun `calculateStops returns correct number of stops using a stubbed BusStopService`() {<br>    // Arrange<br>    val busStopService = mock(BusStopService::class.java)<br>    `when`(busStopService.getStops(&quot;Line123&quot;)).thenReturn(listOf(&quot;Station A&quot;, &quot;Station B&quot;, &quot;Station C&quot;))<br>    val route = BusRoute(busStopService, &quot;Line123&quot;)<br><br>    // Act<br>    val numberOfStops = route.calculateStops()<br><br>    // Assert<br>    assertEquals(3, numberOfStops)<br>}</pre><h4>Mock</h4><p>A mock is a test double that not only provides responses like a stub but also records interactions, allowing you to verify that specific methods were called with the expected parameters.</p><p><strong>When to Use:</strong> Use mocks when you need to verify interactions between the SUT and its dependencies, such as ensuring a certain method is called only once.</p><p><strong>Example:</strong> Verifying that a method to save data in a repository is called when a form is submitted.</p><p><strong>Library/Framework:</strong></p><ul><li><a href="https://site.mockito.org/"><strong>Mockito</strong></a><strong>:</strong> The most widely used library for creating mocks and verifying interactions.</li><li><a href="https://mockk.io/"><strong>MockK</strong></a><strong>:</strong> A powerful alternative for Kotlin projects.</li></ul><pre>@Test<br>fun `calculateStops calls getStops on BusStopService`() {<br>    // Arrange<br>    val busStopService = mock(BusStopService::class.java)<br>    val route = BusRoute(busStopService, &quot;Line123&quot;)<br><br>    // Act<br>    route.calculateStops()<br><br>    // Assert<br>    verify(busStopService).getStops(&quot;Line123&quot;)<br>}</pre><h4>Spy</h4><p>A spy wraps a real object, allowing you to call its actual methods while still monitoring and verifying interactions with it. This is useful when you want to partially mock an object while keeping some of its real behavior.</p><p><strong>When to Use:</strong> Use spies when you need to track method calls but still want to use the actual implementation for other methods.</p><p><strong>Example:</strong> Spying on a ViewModel to ensure certain lifecycle methods are invoked while still executing the real ViewModel logic.</p><p><strong>Library/Framework:</strong></p><ul><li><strong>Mockito:</strong> Use spy() to create a spy around a real object.</li><li><strong>MockK:</strong> Provides support for spies as well, allowing for more flexible testing scenarios in Kotlin.</li></ul><h3>A solid Unit Testing strategy</h3><p>A good unit test is not just about ensuring that the code works as expected; it also serves as a long-term safeguard for the stability and maintainability of your application. Here are the key characteristics:</p><h4>Protection Against Regressions and Refactoring</h4><p>One of the primary purposes of a unit test is to prevent regressions — unintended changes in behavior when new code is added or existing code is modified. A well-written test detects breaking changes in functionality by focusing on testing outcomes and behavior rather than implementation details.</p><h4>Maintainability</h4><p>Unit tests should be easy to maintain, understand, and modify when necessary. A red flag is an overly complicated “Arrange” section or difficulty in providing dependencies, which can make the test harder to work with in the long term.</p><h4>Fast Feedback</h4><p>Unit tests should execute quickly, providing fast feedback to developers. This encourages frequent test runs and a straightforward process for identifying and fixing bugs when tests fail. Quick execution is essential for maintaining a productive development workflow, especially in continuous integration environments.</p><h3>Unit Testing in Android</h3><p>Now that we have a good understanding about unit testing, what parts and components of our Android app we should unit test?</p><p><strong><em>(Note: </em></strong><em>In the examples below I’m using mocks for simplicity but ideally we should prefer fakes and real implementations when possible</em><strong><em>)</em></strong></p><h4>Business Logic</h4><ul><li><strong>ViewModel</strong>: They are going to contain most of the UI logic and in many cases also business logic (depending on our architecture and separation of concern level). Here we should be testing things like the different model states after some user interaction, data responses from a repository, etc.</li></ul><pre>class BusRouteViewModelTest {<br><br>    private lateinit var viewModel: BusRouteViewModel<br>    private val repository = mock(LinesRepository::class.java)<br><br>    @Before<br>    fun setUp() {<br>        viewModel = BusRouteViewModel(repository)<br>    }<br><br>    @Test<br>    fun `fetchStops sets stops LiveData correctly`() {<br>        // Arrange<br>        val expectedStops = listOf(&quot;Station A&quot;, &quot;Station B&quot;, &quot;Station C&quot;)<br>        `when`(repository.getStops(&quot;Line123&quot;)).thenReturn(expectedStops)<br><br>        // Act<br>        viewModel.fetchStops(&quot;Line123&quot;)<br><br>        // Assert<br>        assertEquals(expectedStops, viewModel.stops.getOrAwaitValue())<br>    }<br>}</pre><ul><li><strong>Use Cases or Interactors</strong>: If we are using this component in our Clean Architecture implementation, they will contain business logic that must be unit tested.</li></ul><h4>Utility Classes, Helpers, Mappers</h4><p>Any function, class, helper, mappers, etc that perform calculations, data formatting and similar logic should be tested.</p><pre>//  Assuming this utility class:<br>object BusRouteUtils {<br>    fun formatStops(stops: List&lt;String&gt;): String {<br>        return stops.joinToString(separator = &quot; -&gt; &quot;)<br>    }<br>}<br><br>//  This could be a test case:<br>class BusRouteUtilsTest {<br>    @Test<br>    fun `formatStops returns correctly formatted string`() {<br>        // Arrange<br>        val stops = listOf(&quot;Station A&quot;, &quot;Station B&quot;, &quot;Station C&quot;)<br>        val expectedFormat = &quot;Station A -&gt; Station B -&gt; Station C&quot;<br><br>        // Act<br>        val result = BusRouteUtils.formatStops(stops)<br><br>        // Assert<br>        assertEquals(expectedFormat, result)<br>    }<br>}</pre><h4>Data Layer</h4><ul><li><strong>Repositories</strong>: Test that the repository fetch, store, cache and process the data correctly. Specially important if this component has actually repository functionalities like fetching data from different sources, mapping or similar.</li><li><strong>Data mappers</strong>: If we are converting data models to lets say domain models, this are the perfect candidate for unit testing as well.</li></ul><pre>class BusRouteRepositoryTest {<br><br>    private lateinit var repository: BusRouteRepository<br>    private val localDataSource = mock(BusStopDataSource::class.java)<br>    private val remoteDataSource = mock(BusStopDataSource::class.java)<br><br>    @Before<br>    fun setUp() {<br>        repository = BusRouteRepository(localDataSource, remoteDataSource)<br>    }<br><br>    @Test<br>    fun `getStops returns local data when available`() {<br>        // Arrange<br>        val expectedStops = listOf(&quot;Station A&quot;, &quot;Station B&quot;)<br>        `when`(localDataSource.getStops(&quot;Line123&quot;)).thenReturn(expectedStops)<br><br>        // Act<br>        val result = repository.getStops(&quot;Line123&quot;)<br><br>        // Assert<br>        assertEquals(expectedStops, result)<br>        verify(remoteDataSource, never()).getStops(anyString())<br>    }<br><br>    @Test<br>    fun `getStops fetches from remote and saves locally when local data is empty`() {<br>        // Arrange<br>        val expectedStops = listOf(&quot;Station A&quot;, &quot;Station B&quot;)<br>        `when`(localDataSource.getStops(&quot;Line123&quot;)).thenReturn(emptyList())<br>        `when`(remoteDataSource.getStops(&quot;Line123&quot;)).thenReturn(expectedStops)<br><br>        // Act<br>        val result = repository.getStops(&quot;Line123&quot;)<br><br>        // Assert<br>        assertEquals(expectedStops, result)<br>        verify(localDataSource).saveStops(&quot;Line123&quot;, expectedStops)<br>    }<br>}</pre><h3>Conclusion</h3><p>In this article, we explored the essential elements of unit testing in Android development. We started by defining what unit tests are and their importance in preventing regressions, maintaining code quality, and providing fast feedback. We discussed the different types of test doubles, such as dummies, fakes, stubs, mocks, and spies, and how they can be effectively used in Android projects. We also covered what should be unit tested in an Android project, including ViewModels, utility classes, and repositories, along with best practices for writing maintainable and efficient tests.</p><p>While this article provided a comprehensive overview of unit testing, topics like Test-Driven Development (TDD) and integrating tests into Continuous Integration (CI) pipelines are crucial aspects that will be covered in future articles. For those interested in deepening their understanding of unit testing principles, I highly recommend the book <a href="https://a.co/d/1lCOoZ4"><em>Unit Testing: Principles, Practices, and Patterns</em></a> by Vladimir Khorikov, which served as a valuable reference for this post.</p><p>Thank you for reading, and I hope this guide helps you write better tests and build more robust Android applications!</p><p><strong><em>Disclaimer:</em></strong><em> The views and opinions expressed in this blog post are solely my own and do not reflect the official policy or position of my employer. The approaches and strategies discussed here are based on my personal experience and understanding of unit testing in Android development.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86edaf83d348" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/an-effective-testing-strategy-for-android-part-2-unit-testing-86edaf83d348">An effective testing strategy for Android (Part 2) – Unit Testing</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An  effective testing strategy for Android (Part 1)]]></title>
            <link>https://proandroiddev.com/an-effective-testing-strategy-for-android-i-4a269d134acf?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a269d134acf</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Tue, 22 Jun 2021 21:54:59 GMT</pubDate>
            <atom:updated>2024-08-27T22:10:23.663Z</atom:updated>
            <content:encoded><![CDATA[<h3>An effective testing strategy for Android (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5mOLESSLfoDbpGuK" /><figcaption>Photo by <a href="https://unsplash.com/@florianolv?utm_source=medium&amp;utm_medium=referral">Florian Olivo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some time ago, in the early days of Android development, the testing strategy was often the great forgotten in the projects for this platform.</p><p>I think there were a few fundamental reasons for this. For a start, we didn’t have clear design or architecture patterns to follow that facilitate the task of implementing testable code, this is code separated by responsibilities and isolated from implementation details and the Android Framework. Nowadays this is not so common but as we know we are all guilty at some point of our career as Android developer of placing all data, business and view logic in the same place, usually a big bloated Activity making the testing of this functionality pretty much impossible.</p><p>On the other hand, the Android SDK wasn’t facilitating this task as we didn’t have good testing framework and libraries, aside from basic JUnit tests and some automation features. It was difficult to set up and run, the primitive IDE didn’t help either (remember Eclipse?), documentation almost didn’t exist and Google itself didn’t provide proper guidelines and examples on this matter.</p><p>On top of that, maybe what I consider even the worst of the problems, we developers quite often didn’t consider a good testing strategy as a first class citizen but instead, more as overhead and an amount of work and time we couldn’t afford to spend (this still happen in some cases now days, but that is a different story for a different post).</p><p>Thankfully this now days has changed and most teams have in place some kind of testing approach. The Android framework has evolved a lot and it provides an extensive set of tools and a good framework for a different type of tests. The Android community has embraced several types of architecture and design patterns that facilitates the tests implementation for the different layers and components of the applications and we developers are more conscious about the critical role of a good test approach.</p><p>But despite all these improvements I believe that quite often we still struggle to implement an effective automated test strategy, able to guarantee as much as possible the correctness of all the different functionalities of our apps with a good return of investment from our time and effort.</p><p>What should I unit test and which is the scope of them? Do I need UI tests and how can I make them as fast and reliable as possible? What about integration tests, do I need them and what for? What about end to end tests or manual quality assurance? Should I favour any kind of tests over the others?</p><p>The purpose of this first article is to propose and describe an approach which I consider is an effective testing strategy that maximise the time and effort we spend providing the best return in terms of correctness, quality assurance and stability of our products. I will describe what I believe is the best way to distribute and use the different type of tests and tools we have in Android. In following posts I will be extending the information about different particular topics when they need a more in deep description and level of detail.</p><h3>Why do I need a good testing strategy?</h3><p>The main goals when we implement our test strategy are:</p><ul><li>Allow the organic and sustainable growth of the code base maintaining the quality, robustness and stability.</li><li>Avoid slowing down and stalling of the development work.</li><li>Facilitate the ability to continuously improve, change and expand the functionalities of the product.</li></ul><p>So we can’t deny the benefits of well rounded testing implementation, but to achieve this sweet spot we need to design carefully how are we going to invest our precious time. Tests implementation and running can be expensive and time consuming, and in many cases we might fall in the trap of creating test cases for the sake of tick the coverage boxes without getting any real value from them.</p><h3>Requisites for a solid testing strategy</h3><p>So what are the requirements to consider our approach effective and solid?</p><ul><li><strong>Priority to the important and critical parts of the code. </strong>The domain layer, classes and components that implements business logic, algorithms, etc. In here is where we need to put all our attention and efforts. This is the code that provides more value so it’s the code we need to protect the most with a good test safety net. Outside this area, we have mostly external services, database, network, infrastructure, etc.</li><li><strong>Integrated in the development cycle. </strong>Test suites must be integrated in the workflow of the development team, they have to be part of the Continuous Integration flow and run every time we intend to merge new changes.</li><li><strong>Reasonable development and maintenance cost with a good return of investment ratio</strong>. This means that our tests must provide high value and a good safety net but without penalising excessively the time and efforts to implement, run and maintain that make the task of implement this tests not worth it for the returned value.</li></ul><p>In order to achieve this sweet spot of the highest value at lowest cost possible, we need to design carefully the test strategy: What type of test are the most adequate for this class, component or feature? Should I use Unit or Integration Test? Shall I follow strictly the usually recommended test pyramid?</p><p>We might think that a straightforward solution would be implement mostly UI tests using Espresso. At the end of the day we are a front end system and we are interested in testing that what the user see and the visual experience is correct and everything work as expected. If I can test that a whole user flow is working properly by emulating the same behaviour and checking the result, we can consider that the implementation is correct and defect free.</p><p>But UI tests are expensive to implement and slow to run. In some cases we need to set up complex application state that might include login, accessing remote and local data, maybe even access to device capabilities like camera, Bluetooth, etc. Or we have to go through a long user flow, and things get even worse when if the application has a considerable size and we have tons of screens and flow. If we need to run a whole tests suit of this type in a big application after every commit in the main branch, as we should, development cycles can get extremely long and cause a bottleneck in our Continuous Integration pipeline and in the general development flow.</p><p>In some projects things can get even worse when on top of the UI tests, and because we didn’t managed to create a good safety net and confidence in the quality achieved by our automated tests, we decide to also have in place and run a lot of manual tests. We end up with one of the common anti patterns in testing strategy, the testing cupcake, as described in this <a href="https://www.thoughtworks.com/insights/blog/introducing-software-testing-cupcake-anti-pattern">article</a> by ThoughtWorks. On top of long UI automated test sessions we have to perform long cycles of manual tests.</p><p>To avoid these issues let’s take a look to a more heterogeneous approach that can help to keep test suites faster to run and less costly to maintain and develop while keeping a high level of confident in the correctness of the code.</p><h3>The Strategy</h3><p>The first requisite to be able to implement our strategy is that the application must be designed with an architecture that facilitate separation of concerns and modular design. Clean Architecture is a good example that is widely adopted in the Android community, but any other pattern would be perfectly valid. Apart from the obvious benefits of having in place a good architecture, like scalability, flexibility, adaptability, and so on, a well designed code base will make possible the testability of classes of modules with minimum friction and effort. A class that contains too many dependencies, with some of them belonging to the Android framework or other third party component will make the testing process really difficult if not impossible in many cases.</p><p>In order to guarantee the correctness of a feature as much as possible in the most effective and cost efficient way, we will be using a variety of type of test at a different levels of the code structure to maximise coverage. For this we are going to implement a combination of <strong>Unit, Integration</strong>, <strong>End to End</strong>, <strong>UI and Manual tests</strong>.</p><p>We need to prioritise automated over manual tests. Manual tests take long time to run, are prone to human error and more expensive in resources. We can launch the suite of automated tests for the whole project as many times as we want, but we can’t ask a human to test again and again the whole system every time we need it.</p><p>Having the majority of tests automated means we need to be able to run them as fast as possible. If we can guarantee and maximise the correctness validation of our application quick and automatically, this is going to allow us to develop, deploy and release much faster and frequently making our agile and train release process a well greased and efficient machine.</p><p>And this is what makes so important to choose a good combination of tests. If most of our tests are UI based end to end tests, running the whole test suite is going to be painfully slow and in many cases a flakey process. We need to provide the same level of confidence of correctness with faster and reliable combination of tests.</p><p>So to summarise all this, and because the reader quite probably will be familiar with the classic test pyramid defined by Mike Cohn, below we can see a variation of that as a graphical representation of all this strategy defined so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*C2lvt7xrqV14tyBg_vmgDQ.png" /><figcaption>The proposed new test strategy pyramid</figcaption></figure><p>So now let&#39;s take a look now at a high level the different type of tests that we need to implement and the purpose of each one. In the next blog posts we will dig into more detail about all of them, tools and libraries to use, examples and recommendations.</p><h4>Unit Tests</h4><p>These should be implemented in critical parts of the code base, usually domain classes containing business rules, algorithms, etc.</p><p>What is an Unit Test and how to approach the implementation and the different techniques will be the topic of the part II of this series of articles. The There is a lot of debate and different philosophies to approach unit tests implementation, but to summarise the key concepts, they must be focused in a single unit of behaviour, not necessarily a single class and we should try to use real dependencies as much as possible, trying to minimise the use of mocks and fakes to only when really necessary. Is also important that we test <strong><em>what</em></strong> this component does, but not <strong><em>how</em></strong> they do it.</p><h4>Integration Tests</h4><p>These are test where we are going to validate that different components of our system are working together correctly. For example we could be testing how a repository, an Interactor and a ViewModel are working together and if based on a data state in the repository the view model is receiving the expected data in the correct type and format after a request via the Interactor. These tests run in the JVM and not in a emulator or a real device, making them fast and reliable.</p><p>Once again here we can see how important is to implement a good architecture in our application, so we can define the different responsibilities and scope of the tests. Something to take into account here is that in some cases we will might be unit testing one class or component and also we will be testing how this component work together with other components to achieve certain task.</p><p>As we can see in the pyramid, is in these type of tests where we should spending much of our time because is where we are going to receive more value for this investment. These tests are fast to execute as they don’t depend on a mobile phone or emulator.</p><h4>UI Tests</h4><p>In here what we are going to test is that the screen is representing a state of the app correctly, with the right data, position of the component, user interactions, etc. These run in a real device or an emulator, which mean they are expensive and slow. If we are using the MVVM pattern, the way to go is just to define and set up states and the models with different data depending on the test scenario and validate the UI with the Espresso assertions. The key here is that we are just testing the UI in isolation of the rest of the application, this tests should be relatively fast to run. As we will see in next articles here the Android class <em>FragmentScenario</em> is our friend.</p><h4>End to End Tests</h4><p>These are the most expensive to implement and slow to run of all the tes types, for this reason we will be implementing as fewer as possible, prioritising those critical user flows and core functionalities of our app. These are blackbox tests so we are testing the scenarios in the same way a user would be using the application. This provides a strong assertion about the correctness of the features in our app as we are testing the whole implementation, and if we have staging or other kind of development environment we can actually be including the network requests and any other external process.</p><h4>Manual Tests</h4><p>Finally we have the tests performed by humans. If we have implemented a full suite of tests off all types described above, these should be the smaller section of all the process. In here the QA team (if we have one, if not the developers) should be just running some smoke tests and any edge cases that couldn’t be asserted with all the automated tests implemented so far. Basically we should avoid to test again anything that has been already tested by the automated suites. And this apply to any other kind of tests implemented before.</p><h3>Designing the tests suite</h3><p>So based in all the concepts and theory described above, how do we select what type of test apply to the different components of the app? What should be the scope of the integration tests? Let’s see with a practical example what could be an effective design.</p><p>Below we can see a classic Clean Architecture approach to implement a common use case in an application, this is we fetch some data from a remote or local data source and then display on the screen some kind of information based on this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*7cbqWlDsMzG-obkeggCAbg.png" /><figcaption>A common Clean Architecture approach with data flow directions</figcaption></figure><p>So, let&#39;s start with the Unit Tests. As mentioned before we want to test the unit of behaviour of a specific component. In this example as we can see in the diagram below, we want to test the Use Case (also known as Interactor) and the Repository. These components might contains logic that we need to test. In the case of the Repository it could be the logic to select between source of data, or some data model transformation, etc. Same thing with the use case, we might have some business logic or any other domain operation that needs to be tested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAlCvQHz4EnASHbGbXc6Hg.png" /></figure><p>Now that we have implemented the unit tests for the Use Case and the Repository and we can confirm the correct behaviour and correctness the functionality that they provide individually, is time to validate how these components work together. For this purpose we start with the Integration Test. The idea is to make them as bigger in scope as possible including as many components involved in a feature or data flow as possible. For our example we decide that we are going to test from the repository up to the ViewModel. So providing a fake version of the data that the repository fetch from the backend or database, we will assert that the ViewModel is creating the right states, view data models, etc. This way we are testing all the contracts of all classes involved, the mapping to different models to cross boundaries, the exception management, etc, etc.</p><p>In important to note that we are leaving out of the test the components that we don’t control, the out of process elements like the backend and database. We want to run this tests in the JVM and do not depend on a emulator or real device. We want to avoid brittle and flaky tests, and if we depend on a real database or a backend that is going to be almost impossible. If the network fails the test will result in a false negative. If we need to populate the database or wait for a request in a real device, they will be slow and difficult to set up. Below we can see a diagram representing this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vF421okU2884ieyuLY3_4w.png" /></figure><p>Now is turn for the UI test, which are the only ones we want to run in an emulator of real device. For this reason we want to make then small and focused on pure UI assertions. So as represented in the diagram, we are going to inject in our ViewModel the data models that represent a state of the application. We will be using FragmentScenario to launch in isolation that screen and then using Espresso we will assert that the view is actually representing the state defined by the ViewModel. We will be checking that we are displaying the right components with the right copies, is any of them must be visible or not, enabled or not, the events dispatched by the View to the View Model, etc. As we can see here there is no full users journeys and full features tests, just pure UI testing of a single view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FtWsnDyuYlyTCviN2Nihfw.png" /></figure><p>And finally is time for the End to End test where again we are going to use real devices or emulators but in this cases we will be launching the whole app and performing complete users flows and feature testing as described in the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UrICFfHXJBAtE-r57gsoPw.png" /></figure><h3>Summary</h3><p>So this is it. In this first part about implementing a good test strategy for our Android projects I have tried to define and explain an approach that I considered balanced and effective. The main goal is to maximise the time and dedication spent in testing while getting the most return of investment and minimising the human testing efforts.</p><p>In the following articles we will focus on the details of the different type of tests, recommendations, best practices and implementation details for a good automated test.</p><p>I would love to hear your feedback, ideas or different approach about this topic and the content of the article. Please feel free to drop any comments and thanks for reading!</p><p><strong><em>Disclaimer:</em></strong><em> The views and opinions expressed in this blog post are solely my own and do not reflect the official policy or position of my employer. The approaches and strategies discussed here are based on my personal experience and understanding of unit testing in Android development.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a269d134acf" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/an-effective-testing-strategy-for-android-i-4a269d134acf">An  effective testing strategy for Android (Part 1)</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security matters: A quick introduction and some tips for Android developers]]></title>
            <link>https://davidguerrerod.medium.com/security-matters-a-quick-introduction-and-some-tips-for-android-developers-11fac2d2c76d?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/11fac2d2c76d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Sun, 27 Aug 2017 19:06:05 GMT</pubDate>
            <atom:updated>2017-08-28T14:16:53.331Z</atom:updated>
            <content:encoded><![CDATA[<p>Quite often the security aspect of our apps is not taken in consideration when we are working in our projects. Generally speaking the mobile ecosystems are perceived as very secure due the particular architecture and design of the main platforms (Android and iOS) compared to other platforms like, let’s say the Windows PC operating systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*vgTpwU-ODvPan1oH." /></figure><p>From a user point of view there is also this relaxed perception about the security of our devices. As we are going to see in this post we should take much more seriously the security of our platform, as developers and also as users, taking into account the massive amount of personal information that we carry in our devices. And here we as developers have a big responsibility.</p><h3>The evolution</h3><p>The malware and cybersecurity threats as we know it’s not something new. Hackers are being around for a while and their practices have been evolving with the progress and evolution of the computer systems.</p><p>In the early days malware were usually more kind of a joke, experiments and bit of fun with normally no much harm done in the attacked system. We remember virus like the ping-pong, bars, etc that were just an annoying joke in most cases.</p><p>Later on, massive infections of more disrupting malware started to spread mainly in the Windows platform, we remember viruses like Melissa, Conficker or Sasser that infected millions of computers around the world in a few hours, and in some cases leaving the systems unusable.</p><p>Pretty soon hackers realised that there was an opportunity to make money exploiting systems and vulnerabilities so this was the next logic step in the malware evolution. For example, very well known in these days are the <a href="http://www.bbc.com/news/technology-39901382">ransomware cases</a> where the attacker request an amount of money in order to unlock and decrypt the user machine.</p><p>And last but not least we can’t forget the special interest and effort of almost all governments around the world and how they are investing fortunes in spying, attacking and influence to internal or external targets for political and strategic interests.</p><p>With the popularisation of the portable devices it was a matter of time that they become the target of the bad guys who would try to access the massive amount of information collected by these powerful tools, not only personal information like bank accounts or emails but also access to critical sensors, location, microphone, camera, etc.</p><h3>Threats in the mobile platforms</h3><p>Based on <a href="https://securelist.com/it-threat-evolution-q1-2017-statistics/78475/">Kaspersky report for Q1 of 2017</a>, the mobile products of the security company detected 1,333,605 malicious installation packages, 32,038 mobile banking Trojans and 218,625 mobile ransomware Trojans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*O5yt0xjtSIMXo06k." /></figure><p>Distribution of mobile malware by type © Kaspersky Lab 2017</p><p>One of the most common malware types identified were Trojans capable of gain super user rights. This is doable by exploiting well known vulnerabilities in older versions of Android. Unfortunately is quite common in the Android ecosystem that many devices never receive the latest updates of the OS to fix these vulnerabilities.</p><p>As we can imagine, once these malicious programs has gained super user rights, the possibilities and ways to control the device are massive. Read and alter text messages, modify URLs, steal login credentials, key logging, encrypt data, etc. just to name some of them.</p><p>These malware samples are not only distributed in dodgy stores, but also Google Play has been used to spread these malicious apps despite the improvements and effort from Google to increase the security and analysis of all the apps published in the market.</p><p>One example as reported by Kaspersky Lab was a Trojan app that was supposed to be a <a href="https://wordpress.com/post/davidguerrerodiaz.wordpress.com/2243">Pokemon Guide</a>. But underneath, the application contained malicious code that downloaded rooting malware and installed unsolicited apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*AfZOAMbVnhZCWcdY." /></figure><p>Source: Kaspersky Labs</p><p>This application was downloaded more than 500,000 times and managed to perform at least 6,000 infections.</p><p>Another example was the false OS cleaning app Wiperius, that in reality was a Ransomware tool able to encrypt the device disk and afterward demanded a ransom to unblock the phone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*7McbySSYs9_ncuKq." /></figure><p>Source: Kaspersky Labs</p><p>As we can see the mobile platforms are not so secure as most of users might think, compared to other traditionally more affected platforms like Windows.</p><p>So from a developer point of view, what can we do to make our apps more secure? How can we avoid hackers trying to break into our systems? How can we keep the personal data of our users safe and sound?</p><h3>OWASP Mobile Security Project</h3><p><a href="https://www.owasp.org/index.php/About_The_Open_Web_Application_Security_Project">OWASP</a> is a non profit organisation and an open community dedicated to help organisations to develop, maintain and operate Software that can be trusted.</p><p>As part of the organisation there is the <a href="https://www.owasp.org/index.php/OWASP_Mobile_Security_Project">OWASP Mobile Security Project</a> with the goal of classify mobile security risk and provide resources to mitigate the risk and impact of any possible threat, with the focus on the developers and at application level where we can make a difference in our apps.</p><p>They provide a few really helpful tools and frameworks like the <a href="https://www.owasp.org/index.php/OWASP_Mobile_Security_Testing_Guide#tab=Main">Mobile Security Check List and Testing Guide</a>, a <a href="https://www.owasp.org/index.php/OWASP_Mobile_Security_Project#tab=M-Tools">list of tools</a> and one particularly interesting for us as developers which we are going to focus our attention now, <a href="https://www.owasp.org/index.php/Mobile_Top_10_2016-Top_10">The Top 10 Mobile Risks</a>.</p><p>Let’s take a look to the list and see how we can make a difference as developers to make our platform a safer system:</p><h4>M1 — Improper Platform Usage</h4><p>Misuse of a platform feature or failure to use the OS security controls, like Intents in Android, permissions, misuse of Touch ID, etc.</p><p>For example asking for too many or risky permissions can provoke misuse of them and increase the risk of an attack. Or using implicit Intents to run a Service, because you don’t know which service will respond to the Intent.</p><p>We can find <a href="https://developer.android.com/training/articles/security-tips.html">here</a> the official Android documentation about security tips and good practices.</p><h4>M2 — Insecure Data Storage</h4><p>Insecure data storage includes things like SQL Databases, Log files, binary data, resource files, etc.</p><p>For example, an app that is logging publicly critical or sensitive information of a user, or a “hidden” url of our backend services. Or an app that is storing sensitive non encrypted data in shared preferences or the database. If an attacker gain access to our device would be quite easy to get lot of personal information or critical for our business.</p><p>Follow the guidelines for <a href="https://developer.android.com/training/articles/security-tips.html#StoringData">storing data</a> of the official documentation.</p><h4>M3 — Insecure communication</h4><p>Exploit any vulnerability to intercept sensitive data while travelling across the wire. This includes communication using Bluetooth, Wifi, NFC, GSM, etc. As sensitive data we understand things like session tokens, account details, metadata, passwords, etc.</p><p>As an example of attack scenarios we have seen apps sending personal information via non secure channels instead of SSL, or applications accepting connections even though certificates handshake fails.</p><p>Some recommendations to mitigate this threats would be using SSL/TLS, strong cypher suites, certificates signed by CA provider, do not send sensitive information via SMS or notifications, etc. Once again for a more complete list of recommendations check the <a href="https://developer.android.com/training/articles/security-ssl.html">official Security with HTTPS and SSL</a> and <a href="https://developer.android.com/training/articles/security-config.html">Network Security Configuration</a>.</p><h4>M4 — Insecure Authentication</h4><p>In this category we include the bad user authentication and session management, like failing to identify and/or maintain the identification during the app life.</p><p>Once an attacker understand and exploit a weak authentication process, he would be able to perform malicious request to our backend services,</p><p>Some ways to prevent these attacks: Ensure you always perform auth in the backend side, do not store credentials locally. If you need to keep any auth info in the device always do it encrypted. Do not use weak auth mechanisms like 4 digits Pin codes.</p><h4>M5 — Insufficient Cryptography</h4><p>So you are using cryptography but is not strong enough or your encryption process has flaws and weakness. In this scenario an attacker that have access to our device, if we are storing sensitive information encrypted but this is not strong enough or we are managing wrongly our keys, the data could be extracted and decrypted.</p><p>To avoid this scenarios use a strong cryptographic standards, avoid (if possible) to store sensitive information, use hardware backed encryption (if possible), etc.</p><h4>M6 — Insecure Authorisation</h4><p>Important here to understand the difference between Authorisation and Authentication. Where authentication is the process to identify an user, authorisation is the mechanism to check that the user has the right permission to perform a task.</p><p>Weak or flawed authorisation process might allow an attacker to perform actions as administrator of the system.</p><p>To avoid this scenario store the rules for authorisation only in the backend and do relay on device stored rules, perform authorisation checks when the app is hitting the backend on task requests, etc.</p><h4>M7 — Client Code Quality</h4><p>Here as mobile developers is where we have a big responsibility. Poor code standards, either intentionally (taking shortcuts, workarounds, tech debt or even malicious developers) or unintentional (junior or low skilled developers) can end up in poor quality code. And this will make vulnerable to <a href="https://en.wikipedia.org/wiki/Memory_leak">memory leaks</a>, <a href="https://www.owasp.org/index.php/Buffer_overflow_attack">buffer overflows</a>, etc.</p><p>In order to avoid this maintain consistent coding practices, perform code reviews, use automated tools to detect leaks and other defects in the code base, implement a continuos learning and improving policy in your team, etc.</p><h4>M8 — Code Tampering</h4><p>There are different attack vectors in code tampering, like reverse engineering and modifying resources or even code source of the released app package, change dynamically the content of the memory at runtime of the app, replace the API that the app is using, etc.</p><p>Applications like games are quite susceptible of these attacks for example to skip payment for paid versions of the game, new features, etc.</p><p>For more information about this refer to this <a href="https://www.owasp.org/index.php/OWASP_Reverse_Engineering_and_Code_Modification_Prevention_Project">OWASP project</a>.</p><h4>M9 — Reverse Engineering</h4><p>Hackers can download the app from the store and decompile our binary looking for source code, libraries used, assets, algorithms, etc. trying to find vulnerabilities and points of attack.</p><p>There are a few tools and solutions that we can use to obfuscate and make reverse engineering as difficult as possible, like the well known <a href="https://www.guardsquare.com/en/proguard">Proguard</a> or more complete and complex commercial solution like <a href="http://www.arxan.com/">Arxan.</a></p><h4>M10 — Extraneous Functionality</h4><p>An attacker can download the app and analyse it looking into logs, source code, configuration files, etc. and try to find extraneous functionalities. They will try to find hidden switches or backend APIs in order to perform an attack.</p><p>To avoid this, before releasing the app check for any app configuration settings where you disclose switches or hidden back doors. Check for public logs disclosing sensitive information, check that all APIs are well documented and no hidden administrative or debug endpoints are available.</p><h3>Conclusion</h3><p>As we have see the Android and others mobile platforms are not 100% secure. There are many attack vectors that hackers can exploit and we as developers have a massive responsibility to keep our systems and users safe.</p><p>A security breach can destroy the reputation and even the whole company itself so let’s do all what is in our hands to prevent crime, be aware of the risks and develop software with security always in mind.</p><p>As usual please leave any comments or suggestions that you might have.</p><p>Safe coding!</p><p><em>Originally published at </em><a href="https://davidguerrerodiaz.wordpress.com/2017/08/27/security-matters-a-quick-introduction-and-some-tips-for-android-developers/"><em>davidguerrerodiaz.wordpress.com</em></a><em> on August 27, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11fac2d2c76d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuilding a legacy app from the scratch (II): Adding Continuous Integration with Travis CI]]></title>
            <link>https://davidguerrerod.medium.com/rebuilding-a-legacy-app-from-the-scratch-ii-adding-continuous-integration-with-travis-ci-70c72fe39861?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/70c72fe39861</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Sun, 04 Dec 2016 18:11:14 GMT</pubDate>
            <atom:updated>2016-12-04T18:27:52.760Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Integration (CI) is a Software engineering practice where developers in a team continuously integrate their work in the main stream of source code at least once a day.</p><h3>Why?</h3><p>The main goal of the CI practice is to reduce the integration problems that quite often happen when we have a team of several people working in different features and parts of our system. The sooner we integrate our code the easier is to identify problems like dependencies between modules, compilation issues, regression, duplication in code, etc, etc.</p><h3>How?</h3><p>Continuous Integration is overall an attitude and good Software practice. In order to achieve it we need some tools and organisation.</p><p>First of all we need our source code in a repository, in our case to maintain MadridBus app we are using <a href="https://github.com/Quoders/madridbus-android">Github in a public repository</a>.</p><p>Next we need a platform to perform the automatic builds of our code every time we push code to the repository. For our app we are going to use <a href="https://travis-ci.org/">Travis CI</a>. Travis is a hosted distributed CI platform, it’s free for public repositories and it’s quite easy to integrate and configure in our project.</p><p>Finally we need a good suite of Unit Test that are going to run every time a new build is launched, that as we mentioned before is going to happen for each push that we make in our repo. We will talk about the testing strategy in further posts but in the mean time you can take a look to one of my <a href="https://davidguerrerodiaz.wordpress.com/2016/03/04/a-beginners-guide-to-an-effective-android-testing-strategy/">previous posts</a>.</p><h3>TRAVIS CI configuration</h3><p>So first thing is going to <a href="https://travis-ci.org/">https://travis-ci.org/</a> and we sign in with the Github account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/0*0melO2Clxr839bdy." /></figure><p>where we have allocated the Android project.</p><p>Then we are going to select the project we want to set up with continuous integration and that’s pretty much it, we can start building!</p><p>But not so fast, probably your build is going to fail as we need to set it up properly for Android projects, and the way to do this is adding the “.travis.yml” configuration file.</p><p>Below you can see the current MadridBus Travis configuration file:</p><pre>language: android jdk: oraclejdk8 cache: false sudo: true env: global: - ANDROID_API_LEVEL=25 - ANDROID_BUILD_TOOLS_VERSION=25.0.0 - ANDROID_ABI=armeabi-v7a - ADB_INSTALL_TIMEOUT=20 # minutes (2 minutes by default - see #247) android: components: - platform-tools - tools - build-tools-$ANDROID_BUILD_TOOLS_VERSION - android-$ANDROID_API_LEVEL # Google Play Services - extra-google-google_play_services # Support library - extra-android-support # Latest artifacts in local repository - extra-google-m2repository - extra-android-m2repository # Specify at least one system image - sys-img-armeabi-v7a-android-$ANDROID_API_LEVEL # Emulator Management: Create, Start and Wait before_script: - echo no | android create avd --force -n test -t android-21 --abi armeabi-v7a - emulator -avd test -no-skin -no-audio -no-window &amp; - android-wait-for-emulator - adb shell input keyevent 82 &amp; script: - android list target - ./gradlew connectedAndroidTest licenses: - &#39;android-sdk-preview-license-.+&#39; - &#39;android-sdk-license-.+&#39; - &#39;google-gdk-license-.+&#39;</pre><p>Right, so let’s take a look to the interesting parts. As you can see in the first two lines we are specifying the project type with “language: android” and the JDK version 8 to be used to compile with “jdk: oraclejdk8”.</p><p>Right now by default Travis will build our project with Android SDK 24, so if we want to install and build with a latest SDK and use any other additional component we need to specify it as we can see it in the section “components” under the “android” tag.</p><p>As you can see in the example we are indicating that we want to use Build Tools version 25.0.0, Android SDK 25 and also that we are using Google Play Services adding “extra-google-google_play_services”. One important thing here is to tell Travis to accept all the licences when installing additional components, otherwise the build will fail. For this we are adding the section “licenses” as you can see above.</p><p>Finally we want to launch an emulator so we can run the tests. To accomplish this we are adding the section “before_script” where we are launching and waiting until is running for the emulator with the image type as configured in the field “sys-img-armeabi-v7a-android-$ANDROID_API_LEVEL”.</p><p>And that’s it! We just need to push new code to the repository and Travis will build automatically the project and run the tests for us.</p><p>In next posts we will see how to add our testing strategy including Unit Tests with JUnit, Integration Tests with Espresso, mocking with Mockito, etc.<br> Stay tunned!</p><p><em>Originally published at </em><a href="https://davidguerrerodiaz.wordpress.com/2016/12/04/rebuilding-a-legacy-app-from-the-scratch-ii-adding-continuous-integration-with-travis-ci/"><em>davidguerrerodiaz.wordpress.com</em></a><em> on December 4, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70c72fe39861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuilding a legacy app from the scratch: MadridBus revamp (I)]]></title>
            <link>https://davidguerrerod.medium.com/rebuilding-a-legacy-app-from-the-scratch-madridbus-revamp-i-d00d58680999?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d00d58680999</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Sun, 20 Nov 2016 23:19:49 GMT</pubDate>
            <atom:updated>2016-12-02T09:19:47.605Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://play.google.com/store/apps/details?id=com.quoders.apps.MadridBus">MadridBus</a> was the second application that we released in <a href="http://www.quoders.com/">Quoders</a> to the app store. It is an adaptation from the original <a href="https://play.google.com/store/apps/details?id=com.quoders.apps.BilbaoBus">BilbaoBus</a>, an app to get public transport information like routes, stops info, timetable, etc. It was born just as a learning side project but we got good traction from the beginning and it grew up having more public transport agencies, improved UI, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/0*1hs4KKw51p_DtKY9." /></figure><p>On the other hand MadridBus wasn’t so popular, probably because there were already a few decent applications in the market for the city of Madrid, so we didn’t focus so much on it. As a result, now days the app looks and feel really outdated, the UI is clunky and the plumbing of the app are really ugly and not maintainable.</p><p>So for this reason I have decided to rebuild the app from the scratch as one of my side projects. It will be open source <a href="https://github.com/Quoders/madridbus-android">published in Github</a>. I will be explaining here in the blog all the design and implementation decisions, the different techniques, libraries, etc. The goal, apart from having a new and better application, is to have a project that could be a reference for new Android developers and hopefully help them to have a better understanding in how to implement from zero an Android app following good practices, patterns and explain the usage of Android concepts and most used libraries.</p><p>In this post I am going to give a quick summary of the different features, patterns, design and other elements that I am going to use following the best practices and modern Android development techniques. In following post I will be describing in more detail each of these elements and explaining the implementation and the source code will be available on Github.</p><h3>Minimum Viable Product scope and featuresw</h3><p>So first thing first, let’s define the MVP (Minimum Viable Product) features and requisites.</p><p>The current published version of MadridBus has five main features:</p><ul><li><strong>Go To</strong>: This feature allows the user to search a route between point A to B, either pointing in the map or searching by address. This functionality, despite being really useful when you don’t know the city or the best route, interestingly it’s not very used as our Google Analytics data reveals.</li><li><strong>Line List</strong>: Display the list of all the lines (day and night) available and allows the user to see the stops for a specific line and then the next bus time.</li><li><strong>Stops List</strong>: Display a list of all the bus stops in the network. This functionality again is not really very useful, unless you know the name of the stop and want to look up.</li><li><strong>Favourites</strong>: This is really useful as the user can save here to have quick access to the favourites stops, like work, home, etc.</li><li><strong>News</strong>: Display a list of news fro the rss service of the bus agency. Useful when there are disruptions, changes, etc.</li></ul><p>So for the MVP of the new app, taking into account what features the users are really using in the published app, I’m going to go for the Line List, Favourites and News. Also we will be releasing an Android Wear app that will displayFor the V2, we will be adding the Go To feature and maybe the Stops list.</p><h3>App architecture: Data access and storage</h3><p>A public transport application needs to work with an extensive and complex source of data containing lines information, time tables, real time, geolocation, etc.</p><p>For MadridBus we are going to need two different set of data that we will retrieve from the Madrid public transport agency web servers:</p><p>The first one are static data that needs to be downloaded periodically and stored in the device for quick access offline. This set of data contains the bus lines info, route s, stops position, etc.</p><p>The second type of data are the real time information, this will be accessed when we needs to display the real time info of the next bus for a specific stop.</p><p>To accomplish this network access we are going to use the well known library <a href="https://square.github.io/retrofit/">Retrofit</a> from <a href="http://square.github.io/">Square</a>. There are other options like <a href="https://developer.android.com/training/volley/index.html">Volley</a> from Google but in my personal opinion and as you can see in some reviews like <a href="http://instructure.github.io/blog/2013/12/09/volley-vs-retrofit/">this</a>, Retrofit is much better option. For more information you can check my <a href="https://davidguerrerodiaz.wordpress.com/2015/04/29/android-http-communication-with-retrofit/">blog post</a> about Retrofit.</p><p>For the data storage on the device we are going to use a local data base managed with the library <a href="https://realm.io/products/realm-mobile-database/">Realm</a>. Databases in Android usually is a pain to implement using the SQLite API, but with real we simplify and make more robust and less error prone our data base implementation. It supports multithreading, encryption, reactive extensions, etc.</p><h3>UI Layer: Material design</h3><p>So now let’s talk about the UI layer. As we mentioned before, for the version 1 we are going to implement just the Line list, Favourites and News functionalities.</p><p>We can see clearly three different features that will need three direct access from the home screen. So following the Material Design guidelines we are going to use the recently added Bottom Navigation widget that will give us access to the three different features of the app. As we can see in the <a href="https://material.google.com/components/bottom-navigation.html">documentation</a>, this component is recommended for between three and five sections. In case we needed more is recommended to use a Tab view component or maybe using the left navigation drawer.</p><p>So the first option is the Home view and it will display a Google Maps showing the location of the user and the nearest bus stops. The second option will be the Line List, using a Recycler view to display the lines info, and the third option will be News screen, again using a Recycler view. We will post designs and wireframes in a future post when we start implementing this.</p><h3>UI Layer: The MVP pattern</h3><p>The MVP is now days one of the most used patterns in the Android community when it comes to organise the UI layer. There are multiple benefits like much more modular, reusable and testable code. For a complete description and explanation of the pattern take a look to one of my previous <a href="https://davidguerrerodiaz.wordpress.com/2015/10/13/a-brief-introduction-to-a-cleaner-android-architecture-the-mvp-pattern/">blog post</a>.</p><p>As a quick summary, the Activities, Fragments and custom views will be the View layer of the pattern and they will contain only pure UI functionalities.</p><p>The Presenter will be a man in the middle layer that will work as intermediary between the Views and the Model. They will respond to events and actions from the user on the View and it will perform any action required using the Model layer.</p><h3>Modules wiring and communication</h3><p>So as we are going to have different layers in the app following we need some mechanism to communicate with each other, passing data, etc.</p><p>There are different ways to accomplish this, we have just the traditional way using listeners, but we agree that this comes with many problems and we end up with the infamous hell of listeners.</p><p>Another better solution would be using an event bus, but this again has its own downside. The code end up being less readable it grows up having multiple events dispatching from everywhere with unexpected results.</p><p>There is a better solution and will be using RxJava. As we know it’s one of the library and techniques that has focused the attention of the Android community for a while now.</p><p>We will see in a future post and in the code of the app how to use RxJava and how to architect the app using it and all the benefits that it has. In the mean time you can have a look to my <a href="https://davidguerrerodiaz.wordpress.com/2016/09/03/introduction-to-rxjava-for-android-by-examples-i/">blog post</a> about it.</p><h3>Testing and Continuous Integration</h3><p>Testing is often one of the most neglected aspects of the applications development process. For our application we are going to implement two main type of test: Integration Test using Espresso (UI test) and Unit Test when relevant with JUnit.</p><p>For more information about a good testing strategy take a look to <a href="https://davidguerrerodiaz.wordpress.com/2016/03/04/a-beginners-guide-to-an-effective-android-testing-strategy/">my blog post</a> about it.</p><p>Continuous Integration is another key piece of our app development as it allows us to have a build of our app everytime we submit changes to the code repository. This way we can launch our tests suite every time we make a change in the code validating it’s correctness.</p><p>For this functionality we are going to use <a href="https://travis-ci.org/">Travis</a>, a CI platform totally free for open source projects. Once again we will be explaining the configuration in next posts.</p><h3>Summary</h3><p>So that’s it for today, as mentioned before we are going to be publishing blog posts to comment and explain the implementation of the different parts of the new app as we progress coding it.</p><p>Stay tuned!</p><p><em>Originally published at </em><a href="https://davidguerrerodiaz.wordpress.com/2016/11/20/rebuilding-a-legacy-app-from-the-scratch-madridbus-revamp-i/"><em>davidguerrerodiaz.wordpress.com</em></a><em> on November 20, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d00d58680999" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to RxJava for Android by examples (I)]]></title>
            <link>https://davidguerrerod.medium.com/introduction-to-rxjava-for-android-by-examples-i-98653ced2ecb?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/98653ced2ecb</guid>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Sat, 03 Sep 2016 17:17:29 GMT</pubDate>
            <atom:updated>2016-09-09T07:43:19.181Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/206/0*yzG2DozGWC2LSkmj." /></figure><p>Reactive programming is one of the hottest topics amongst the Android community these days. Lot of big guys in the industry are embracing and using RxJava in their platforms and applications, even Google has release their own version of a reactive library called <a href="https://github.com/google/agera">Agera</a>.</p><p>One of the problems of Rx programming is the initial learning curve, the complexity of the paradigm itself and the extension of the library operators and classes.</p><p>The goal of this post is to make a very simple and easy to understand introduction with some examples and be able to start programming and design our apps using RxJava.</p><h3>What is RxJava?</h3><p>RxJava is just a library that implements <a href="http://reactivex.io/">ReactiveX</a> extensions, which basically facilitate the implementation of asynchronous programming using observables data streams.</p><p>It can be described as a combination of the Observer (there is one entity emitting data and one or many listening or it) and Iterator (the data flow are dispatched in onNext events sequences) patterns using the <a href="https://en.wikipedia.org/wiki/Functional_programming">Functional Programming</a> paradigm (we get data in declarative style methods and avoiding mutable objects).</p><p>RxJava is one of the language implementations of the ReactiveX libraries. At the moment there are also other versions available for languages like JavaScript, C#, C++, Swift, Kotlin, etc…</p><h3>Why RxJava?</h3><p>So if there is the learning curve and complexity issue, why to bother learning RxJava? These are some of the main reasons:</p><ul><li><strong>Abstraction of complexity of async data flows and events. </strong>It’s quite common to fall into the hell of nested and multiple listeners, the hell of multiple events from everywhere when using an event bus, etc. With RxJava we can simplify all this using just asynchronous stream of transformable data.</li><li><strong>Filtering, composition, transformation. </strong>Thanks to the massive amount of operators we can easily transform any stream of data transmitted. As we will see later we can filter, combine, transform, create, etc. any kind of data stream.</li><li><strong>Error handling</strong>. Very straightforward error handling by centralising in a single callback method any error, stopping the data sequence.</li><li><strong>Easy testing. </strong>Having a single source/destination of the data source and testing helper classes make it quite easy to test.</li><li><strong>Light and high performance.</strong> RxJava is light and fast, at the moment it weights around 1 MB and it’s quite fast streaming our data.</li></ul><h3>The key components</h3><p>So let’s take a quick look to the key elements that compose the RxJava library.</p><h4>The Observable</h4><p>This is the data source, the object that will be emitting the sequences of data items that the entities who are interested in the data they provide, will be subscribing. It implements all the operators mentioned before to be able to transform the data streams. Observables can be divided in two types: “Hot” observables which might emit data as soon as they are created and “Cold” observables which wait until an Observer subscribes to it.</p><h4>The Observer</h4><p>This is the type of object that will be subscribing and “observing” the data emitted by the Observable, they will “react” somehow using the data provided. Typically they implement the three main events OnNext, OnError, OnComplete as we will see later.</p><p>More info in the official reference <a href="http://reactivex.io/documentation/observable.html">here</a>.</p><h4>Operators</h4><p>These is one of the key and most powerful features of RxJava. There are quite a lot operators of different types that will help us to manipulate and transform in many ways the data streams. We can group them in different categories such as Creating, Transforming, Filtering, Combining, Mathematical, etc.</p><p>For a complete list of operators take a look to the documentation following this <a href="http://reactivex.io/documentation/operators.html">link</a>.</p><h4>Schedulers</h4><p>The <a href="http://reactivex.io/documentation/scheduler.html">Schedulers</a> will help us to implement multithreading in our data streaming. Calling the Observable method “SubscribeOn” and indicating one of the Schedulers we can select in which thread the Observable will do it’s data stream job. On the other hand, calling the method “ObserveOn”, will set up the thread where we will be receiving and observing its data stream.</p><p>In RxJava the most common Schedulers are “<strong>NewThread</strong>” (create a new thread for each job), “<strong>io</strong>” (for input/output operations), “<strong>computation</strong>” (event-loops, callbacks processing, etc), “<strong>immediate</strong>” (perform the job immediately in the current thread), etc.</p><h4>Subject</h4><p>A <a href="http://reactivex.io/documentation/subject.html">Subject</a> is object that is able to act as Observable and Observer. It can emit data streams and at the same time can subscribe to another data stream source (Observable), so we can think in it like a sort of bridge between two data streams.</p><h3>Example 1: Simple subscription to a source of data</h3><p>For our first example, we have a method that create a list of numbers and in order to simulate a long operation, we have added a 100 milliseconds thread pause in the loop.</p><p>The method look like this:</p><pre>private List&lt;Integer&gt; getOddNumbers() { <br>    List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;(); <br>    for(int i=0; i&lt;100; i++) { <br>        if(i%2 == 0) { <br>           try { <br>                   Thread.sleep(100); <br>           } catch (InterruptedException e) { <br>               e.printStackTrace(); <br>     } <br>   } <br>} return numbers; }</pre><p>Now we create the Observable that is going to emit that list of numbers when the list is created. As you can see the “.just()” method takes the list of numbers and create the Observable from it that “just” will emit the data.</p><pre>private Observable&lt;Integer&gt; getOddNumbersObservable() { <br>    return Observable.just(getOddNumbers()); }</pre><p>Right, so now that we have an Observable which is going to emit some data, what we need next is to create an Observer that is going to subscribe to that source of data and receive the numbers list. Let’s have a look to a standard Observer:</p><pre>private Observer getOddNumbersObserver() { <br>    return new Observer&lt;Integer&gt;() { <br>       @Override public void onCompleted() {<br>           LogHelper.addLog(mTvLog, &quot;getOddNumbers() - onCompleted()&quot;); <br>     } @Override public void onError(Throwable e) { LogHelper.addLog(mTvLog, &quot;getOddNumbers() - onError()&quot;); } <br>       @Override public void onNext(Integer integer) {  LogHelper.addLog(mTvLog, &quot;getOddNumbers() - onNext()&quot; + integer); }  }; <br>}</pre><p>As we can see, the Observer implements three fundamental methods: <strong>onNext</strong> will be called when the Observable emit an item. <strong>onCompleted</strong> will be called when the Observable has finished emitting data. And finally <strong>onError</strong> will be called if there has been any exception or error when emitting data.</p><p>We can simplify the Observer in case we just want a single event that will receive the list of numbers and we don’t need to know about the OnComplete and OnError events. To accomplish this we just need to create an Action instead of the Observable, something like this:</p><pre>private Action&lt;Integer&gt; getOddNumbersAction() { <br>     return new Action&lt;List&lt;Integer&gt;() { <br>         @Override public void call(List&lt;Integer&gt; integers) {<br>           LogHelper.addLog(mTvLog, &quot;getOddNumbersAction() - call: &quot; + integers); <br>          } <br>     }; <br>}</pre><p>So the last step would be to subscribe this Observer to the Observable, and it would be as simple as this:</p><pre>observable.subscribe(observer);</pre><p>And that’s it! When the getOddNumbers() method has finished the calculation of numbers and return, the Observable will dispatch the list of numbers and the Observer will receive the data.</p><h3>Summary</h3><p>So this has been the introduction and basic operations with RxJava.<br> You can find all the examples in this public <a href="https://github.com/DGuerrero/android-bootstrap/blob/develop/app/src/main/java/com/quoders/apps/androidbootstrap/rxjava/RxFragment.java">repository</a>.</p><p>In next posts we will be looking deeper into more elements of the Reactive extension, like the Operators and Schedulers, etc.</p><p>In the mean time please leave here any comments, suggestion or corrections you might find!</p><p><em>Originally published at </em><a href="https://davidguerrerodiaz.wordpress.com/2016/09/03/introduction-to-rxjava-for-android-by-examples-i/"><em>davidguerrerodiaz.wordpress.com</em></a><em> on September 3, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98653ced2ecb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginners guide to an effective Android testing strategy]]></title>
            <link>https://davidguerrerod.medium.com/a-beginners-guide-to-an-effective-android-testing-strategy-d5ddf7a994a3?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5ddf7a994a3</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Fri, 04 Mar 2016 08:59:08 GMT</pubDate>
            <atom:updated>2016-04-04T08:40:57.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing quite often is one of the most neglected aspect in many Software projects, and in Android this has been particularly a common issue since the beginning of the platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/0*l3slM6gbgrZyc7Za." /></figure><p>Even Google didn’t seem to be making big efforts to encourage testing: Documentation was almost nonexistent, the tools and frameworks were confusing or hard to use and there was almost impossible to find an open source project with good testing implementation.</p><h3>Why testing?</h3><p>Implement a good suite of different type of tests with a good coverage ratio and maintain it requires time and discipline from the dev team. In some cases the member of the team might not be familiar with the testing frameworks or even never have implemented any type of test. So what are the benefits of this time and resource investment? Here some of the reasons:</p><ul><li>Testing allows us to check the correctness of the app features. We should never rely on the QA team to find defects in our code. Is a very common practice to implement some feature, test a couple of use cases, send it to the quality team and wait until they find a few bugs for us and then fix it. This is really a bad practice that a professional developer should never do. We should be confident that the deliverables that we release to QA team shoulders been tested throughly, has a good test code coverage and that our quality colleagues should almost never find a bug.</li><li>Improves the design and modularity of our code base. If we create a new feature with a <a href="https://en.wikipedia.org/wiki/Test-driven_development">TDD</a> approach, we will be building our classes in short iterations, thinking in the interface and driving the implementation with the proper user requirements in mind. This will make our modules and classes small, independent and with one only responsibility unit.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/0*tdmtgARQ-SraAcg4." /></figure><ul><li>Help us to implement new features or refactor existing one with much more confidence that our changes will not break current working and tested<br> functionalities. If every time we add a new piece of code to our project we run our test and all pass, we can be sure that we didn’t implement anything that is affecting and having negative side effects on the existing features.</li></ul><h3>Types of test</h3><p>In the Android platform, generally we will implement two categories of tests: Unit Tests and Integration Tests.</p><ul><li><strong>Unit Tests</strong>. We will test small and independent pieces of code. It might be a single class, an interface or just a method. We can consider it as the smallest possible testable piece of code part of an specific independent module. In Android we will use JUnit running either locally on the JVM (prefer this one as fastest method) or in an emulator or real device.</li><li><strong>Integration Tests</strong>. We are testing more than one individual module working together that implements a complete functional part of our system. For example we test the Login feature of our application where different entities works together and and we want to test that the login process is accomplished successfully on different scenarios. In this case in Android we will implement UI Instrumentation tests with <a href="http://developer.android.com/tools/testing-support-library/index.html#Espresso">Espresso</a> and Automation tests with UI <a href="http://developer.android.com/tools/testing-support-library/index.html#UIAutomator">Automator</a>.</li></ul><h3>Architecting the app for testing</h3><p>As we mentioned before one of the complains of the Android community was that testing the platform was a difficult task. Apart from the lack of a good testing framework, the developers faced the problems of implementing tests for modules (Activities, Fragments, etc) coupled to multiple Android SDK dependencies.</p><p>In order to mitigate this issue, one best and most common solutions is to architect our application using the <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter">MVP</a> pattern. With this approach we manage to have a clear separation of concerns of our modules making much more easy to unit test our models and use cases classes without having to mock and get around of all the Android SDK dependencies.</p><p>Typically we will have our View layer with the Activity or Fragment that have almost no logic at all. A Presenter acting as a bridge and a Model which will have our use cases and where we will probably focus most of our unit tests.</p><p>In a previous I made a <a href="https://davidguerrerodiaz.wordpress.com/2015/10/13/a-brief-introduction-to-a-cleaner-android-architecture-the-mvp-pattern/">basic introduction of the MVP pattern</a> where you can see all these concepts with more detail.</p><h3>Test Pyramid</h3><p>Following the TestPyramid concept described by <a href="https://www.mountaingoatsoftware.com/company/about-mike-cohn">Mike Cohn</a>, Unit Tests should be around</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/0*lC4tMzkuBv-RJAdb." /></figure><p>60–70% of our test code base and the rest 30% should be implemented as End-to-End tests (Integration, functional, UI tests).</p><p>The reason for this is that the end to end tests has a few problems, like you need to wait until the app is deployed and running in a device. Then probably the test will have to deal with things like login, registrations, database access, etc.<br> Also if you find a bug it will be hard to figure out where exactly the problem is, as it could be in any of the multiple modules and components that are involved in the specific user flow.</p><p>On the other hand Unit Tests are fast, reliable and they isolate the test scope to very specific and isolated pieces of the system which makes it a much better way to identify the defects in our system.<br> If we have build our code base using TDD, we will probably have test covered almost all modules of our application which will give us peace of mind that all parts of the application are being tested and any regression would be detected.</p><h3>Implementing Unit Tests</h3><p>First let’s add to the project build.gradle file the required dependencies for Espresso, JUnit, UIAutomator, etc.</p><pre>// Dependencies for unit testing testCompile &#39;junit:junit:4.12&#39; testCompile &#39;org.mockito:mockito-all:1.10.19&#39; testCompile &#39;org.hamcrest:hamcrest-all:1.3&#39; // Android Testing Support Library&#39;s runner and rules androidTestCompile &#39;com.android.support.test:runner:0.3&#39; androidTestCompile &#39;com.android.support.test:rules:0.3&#39; // Espresso UI Testing androidTestCompile &#39;com.android.support.test.espresso:espresso-core:2.2&#39; androidTestCompile &#39;com.android.support.test.espresso:espresso-intents:2.2&#39; // UIAutomator Testing androidTestCompile &#39;com.android.support.test.uiautomator:uiautomator-v18:2.1.1&#39; compile &#39;javax.inject:javax.inject:1&#39;</pre><p>As we mention before we have two options to run Unit Tests, one is locally on the JVM and the other is running with UI Instrumentation runner. We will favour the local JVM test as they will compile and run much faster. The downside is that these can’t have any Android SDK dependency, but that should be our goal as we saw before using a MVP pattern.<br> One way to overcome this issue is providing any Android dependency using a mocking framework like for example <a href="http://mockito.org/">Mockito</a>.<br> This will be fine if we just need to mock a couple of dependencies with not many interactions between our code and the SDK, but if we have more complex interactions and we need to spend hours mocking classes, this would be a signal that we should run those test in a emulator or device using Instrumentation Test.</p><p>To add the tests in the project we haver will need two folders, one for each type of test as you can see in the picture below, the Unit Test lives in the folder named “test” and the UI test are located in the folder “androidTest”. Both have to be at the same level that our main folder of the project. This is important because otherwise Android Studio will not be able to identify these classes as tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*AHIhC-AjY-ueefP-." /></figure><h3>Anatomy of a Unit Test</h3><p>So now we are ready to add a Unit Test, to do this just add a new class to the Test folders of your project and now we will have to specify which runner we want to use, the size type of the test, etc. Let’s have a look at the example below and we will go through the different parts.</p><pre>@RunWith(MockitoJUnitRunner.class) @SmallTest public class ExampleTest { EmailValidator mEmailValidator; @Before public void setUp() throws Exception { mEmailValidator = new EmailValidator(); } @Test public void givenValidEmail_ReturnsValid() throws Exception { String validEmail = &amp;amp;amp;quot;david.guerrero@quoders.com&amp;amp;amp;quot;; Assert.assertTrue(mEmailValidator.isValidEmail(validEmail)); } @Test public void givenInvalidEmail_MissingHost_ReturnsError() throws Exception { String invalidEmail = &amp;amp;amp;quot;david.guerrero.com&amp;amp;amp;quot;; Assert.assertFalse(mEmailValidator.isValidEmail(invalidEmail)); } @After public void tearDown() throws Exception { mEmailValidator.releaseResources(); } }</pre><p><strong>@RunWith(MockitoJUnitRunner.class)</strong><br> We specify the runner we want to use, it might be JUnit runner, the Instrumentation, Automation runner or even a custom runner. It depends on how and where we want to run our test.</p><p><strong>@SmallTest</strong><br> This annotation define the type of test we are runing, where “SmallTest” is usually a Unit Test, a “LargeTest” an end to end UI or Automation test and a “MediumTest” is when we are testing more than one module working together, like an Integration Test. See the table below to compare these different types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/0*WlCqK8PfNyFypfEG." /></figure><p><strong>@Before</strong><br> The method marked with this annotation will be called every time before a test is launched. It useful to initialise and arrange any data needed for the tests.</p><p><strong>@Test</strong><br> This define a test method. It usually should follow the “Arrange-Act-Assert” pattern:<br> — Arrange all necessary preconditions and inputs.<br> — Act on the object or method under test.<br> — Assert that the expected results have occurred.</p><p><strong>@After</strong><br> This method will be execute after each test and we will use it to release resources, close files, etc.</p><h3>Running the tests</h3><p>Finally to run the tests we need to select “Unit Test” on the Build Variant menu. After this we can just right click at the Test package folder and then on “Run Tests..” (or Debug or Run with Coverage).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*WekZeQJ9oCC7-Q-d." /></figure><h3>Implementing Integration Tests</h3><p>As we saw before, these type of test should cover around the rest 30 or 20 percent of our test code base. We will use the Instrumentation and/or Automation frameworks that basically allows us to simulate user interactions on the application that will run in a real device or an emulator.</p><p>We are going to use Espresso as our Instrumentation test framework. With it we can click on buttons, enter texts, do scrolls, etc. See below an example of a Sign Up screen tests.</p><pre>@RunWith(AndroidJUnit4.class) @LargeTest public class SingupTest { @Rule public ActivityTestRule&amp;amp;lt;SignupActivity&amp;amp;gt; mSignupActivityRule = new ActivityTestRule&amp;amp;lt;&amp;amp;gt;(SignupActivity.class); @Test public void testperformValidCompleteSignup() throws Exception { // Fill up new user fields onView(withId(R.id.editTextCreateUserName)).perform(typeText(&amp;amp;quot;david_&amp;amp;quot; + System.currentTimeMillis())); onView(withId(R.id.editTextCreateEmail)).perform(typeText(&amp;amp;quot;david.guerrero@quoders.com_&amp;amp;quot; + + System.currentTimeMillis())); onView(withId(R.id.editTextCreatePassword)).perform(typeText(&amp;amp;quot;password&amp;amp;quot;)); onView(withId(R.id.editTextPasswordConfirm)).perform(typeText(&amp;amp;quot;password&amp;amp;quot;)); // Click on Sign Up button onView(withId(R.id.editTextPasswordConfirm)).perform(click()); // Check progress dialog is showed onView(withText(R.string.signup_progress)).check(matches(isDisplayed())); // Assert Home screen has been launched onView(withText(R.string.title_activity_home)).check(matches(isDisplayed())); } }</pre><p>As we can see in the example, we are introducing all the fields needed to perform a new user registration, then clicking on the Sign Up button and assert that the Home Activity is launched correctly after this.<br> Notice how we have marked the test with the “LargeTest” annotation and we are running it with the “AndroidJUnit4” runner.<br> To run this test we now need to change to Build Variant to the “Android Instrumentation Test” option and then we just need to choose where to deploy and run the app and the test, either in a real or emulated device.</p><h3>Summary</h3><p>So that was a quite brief introduction to a much more complex subject as the testing strategy in Android. There are much more to talk about testing but that will be probably part of further posts.</p><p>You can find these examples on my work in progress open source project <a href="https://github.com/Quoders/treepolis-android/tree/develop">Treepolis</a> in Github.</p><p>As usual please leave any comments, suggestion or corrections. What’s your testing strategy?</p><p><em>Originally published at </em><a href="https://davidguerrerodiaz.wordpress.com/2016/03/04/a-beginners-guide-to-an-effective-android-testing-strategy/"><em>davidguerrerodiaz.wordpress.com</em></a><em> on March 4, 2016.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5ddf7a994a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Share your Android and iOS application with Google App Invites API]]></title>
            <link>https://davidguerrerod.medium.com/share-your-android-and-ios-application-with-google-app-invites-api-cbf4043d3acc?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbf4043d3acc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Sun, 18 Oct 2015 10:33:31 GMT</pubDate>
            <atom:updated>2015-10-18T10:33:31.437Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most common features that we usually implement in our apps is the ability of the user to share the app with friends. This is a great way to make our app grow and a free mechanism of user acquisition.</p><p>Normally we have implemented this functionality with some kind of custom message and allowing the user to send it by email, text message, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*LO4aHwvDMFN92Y7g.jpg" /></figure><p>Now we can achieve this with a much better user experience and customisable way using the new <a href="https://developers.google.com/app-invites/">Google App Invites Beta API</a> that was announced in the last <a href="https://events.google.com/io2015/">Google I/O 2015</a>.</p><p>With App Invites we not only can share the app but also send deep links, customised invite cards, link with Google Analytics to track the flow, etc.</p><p>So lets start to set up our project adding the Google Play Services metadata in the app manifest:</p><pre>&lt;meta-data android:name=&quot;com.google.android.gms.version&quot; android:value=&quot;@integer/google_play_services_version&quot; /&gt;</pre><p>Then we need to add the dependency to our top-level build.gradle:</p><pre>classpath &#39;com.google.gms:google-services:1.3.0-beta1&#39;</pre><p>and also apply the gsm plugin to our app-level build.gradle:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;</pre><p>Finally we add the Google Play Services dependency in the app’s Gradle file:</p><pre>compile &#39;com.google.android.gms:play-services:7.5.+&#39;</pre><p>Right, next thing we need to add to our project is a Json configuration file that we will get from Google that provides service information specific to our app. To do this we will have to add in the Google Developer Console our application package name and the SHA1 key from our key store. Click <a href="https://developers.google.com/mobile/add?platform=android&amp;cntapi=appinvite&amp;cnturl=https:%2F%2Fdevelopers.google.com%2Fapp-invites%2Fandroid%2Fguides%2Fapp%3Fconfigured%3Dtrue%23add%2Dconfig&amp;cntlbl=Continue%20Adding%20App%20Invites">here</a> to access the dev portal to do so.</p><p>Once we have the configuration google-services.json file we just need to copy it into the app/ or mobile/ directory of our project.</p><p>Ok, so now that we have finished the integration let’s do the funny part, and send an app invitation. To achieve this we just need to build and start an Intent, something like this:</p><pre>Intent intent = new AppInviteInvitation.IntentBuilder(&quot;Try this app!&quot;) .setMessage(&quot;Hey take a look to this awesome app that I&#39;m using!&quot;) .build(); startActivityForResult(intent, REQUEST_INVITE);</pre><p>If everything went well, when we launch our app and we launch this intent we should see a really nice interface that will show the user’s contacts list and the option to send the invite.</p><p>When the destination user receives the invite, depending on if he or she has installed the app different things might happens as we can see in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*lHGwK6t_iPufbag0.jpg" /></figure><p>So that’s it! This is just an introduction but there are more interesting options to explore as the integration with Google Analytics, deep links features, etc.</p><p>You can find an example of the integration and use for Android in my examples project <a href="https://github.com/DGuerrero/android-bootstrap">here</a>. And as usual any comments and feedback are more than welcome!</p><p><em>Originally published at </em><a href="https://davidguerrerodiaz.wordpress.com/2015/06/29/share-your-android-and-ios-application-with-google-app-invites-api/"><em>davidguerrerodiaz.wordpress.com</em></a><em> on June 29, 2015.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbf4043d3acc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A brief introduction to a cleaner Android architecture: The MVP pattern]]></title>
            <link>https://davidguerrerod.medium.com/a-brief-introduction-to-a-cleaner-android-architecture-the-mvp-pattern-5cf80cb59c31?source=rss-2f152e258d5a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf80cb59c31</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[mvp]]></category>
            <dc:creator><![CDATA[David Guerrero]]></dc:creator>
            <pubDate>Sat, 17 Oct 2015 17:32:50 GMT</pubDate>
            <atom:updated>2015-10-17T17:32:50.493Z</atom:updated>
            <content:encoded><![CDATA[<p>As the Android platform has been maturing, developers found that the standard approach to organise the architecture and design of the application code wasn’t the best at all. Usually we ended up having a massive monolithic module, an Activity or a Fragment, containing business and UI logic, creating an unmaintainable and untestable messy project.</p><p>Google itself haven’t provided so far a good practice guideline or code examples showing a modular and decoupled approach that implements any of the well known and widely used design patterns, like for example <strong>MVC</strong> which is encouraged by default on the <strong>iOS</strong> platform or the common <strong>MVVM</strong> in <strong>Microsoft</strong> environments.</p><p>One of the most common pattern that the community of Android developers has been using for a while and that has got lot of attention is the<strong> Model View Presenter (MVP)</strong> pattern and we will focus on it on this post. We will not go through a deep academic description of the pattern but we will focus on the advantages and practical use of it. For an awesome analysis of the MVP and other patterns take a look at this classic post from <strong>Martin Fowler</strong> about <a href="http://martinfowler.com/eaaDev/uiArchs.html"><strong>GUI architecture</strong></a><strong>.</strong></p><h4>So what’s MVP?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*UltdusGOit-w9ZK3DDEonw.jpeg" /></figure><p>Basically MVP is an architectural design pattern that divides our application code in three entities in order to achieve a modular design, implementing the separation of concerns concept, allows an easier implementation of unit tests and making possible to reuse and replace modules either of our UI, data or business layer.</p><p>MVP is an evolution of MVC and it has multiple variants and implementations. There has been a lot of conversations and debate about the best and proper way to adopt it on Android. I’m going to expone my way which I have been using in a couple of projects and I reckon works better for me. Of course it doesn’t mean is the best or only one that works on Android, so please leave any comment and suggestions if you find any area of improvement.</p><p>Ok so let’s see who is who in this approach.</p><h4>The View</h4><p>This entity is going to include the visual part of our app, it is only the UI and it will not have any logic or knowledge of the data displayed. The View doesn’t know anything about the business logic or how to get the data it has to show to the user.</p><p>Activities, Fragments, Dialogs, etc… would be included in this category. This elements will contain only initialisation and display functionalities of the visual components and elements to display information to the user. It will not contain any functional or business logic like access to database or web server for example.</p><p>This module (Activity, Fragment, etc) exports an interface that will be used by the Presenter, which is responsible and have the knowledge and logic about how, when and what to show in the View. This interface will have methods like “showProgressBar”, “showLoginErrorMessage” or “launchSignupActivity”. Here is an example:</p><pre>public interface WelcomeView {</pre><pre>    void launchHomeActivity();<br>    void LaunchSignupActivity();<br>    void closeActivity();</pre><pre>    void setWrongUsernameError();<br>    void setWrongPasswordError();</pre><pre>    void showLoginErrorAlertDialog();<br>}</pre><h4>The Presenter</h4><p>As we mentioned before, this entity is going to have all the logic and knowledge about what, how and when to display in the user interface. It will be responsible of capture events raised by the user when interacting with the UI and perform any action.</p><p>The presenter also acts as a bridge between the View and the Model fetching any data needed from the data layer, making any transformation and display this info to the user on the View.<br>This entity ideally shouldn’t have any dependency of the Android SDK such us Context or Activity references.</p><p>The Activity will have a reference to the Presenter interface and it will use it to communicate any event occurred on the View, like the user tap on a button or the user enter any data in a TextView and then it will decide what to do in reaction of that event.</p><p>Here is an example of a Presenter interface:</p><pre>public interface WelcomePresenter {<br>    void onCreateAccountClick();<br>    void onActivityResultCalled(int requestCode, int result);<br>    void onLoginClick();<br>}</pre><p>So for example let’s say that if the user tap on a Logout button, the View call the exported method “onLogoutClick” of the Presenter interface. Then the it knows what interactor of the Model layer needs to invoke to perform a Logout action on the app.</p><p>Once the log out success callback has been received, the Presenter will perform any action on the View, for example closing the Activity and displaying a home screen Activity.</p><h4>The Model</h4><p>In this entity we will include the “<em>interactors</em>” (use cases of our business logic) that will perform and manage any business layer logic and data access, like fetching data from our web service, accessing the database, etc.</p><p>Once we have that piece of data the interactor will send it back to the Presenter and this will decide what to do with this data and how to show it to the View as we saw in the previous point.</p><p>Here an example of an implementation of an interactor:</p><pre>public class WelcomeInteractorImpl implements WelcomeInteractor {</pre><pre>    private WelcomeInteractorListener   mListener;</pre><pre>    public WelcomeInteractorImpl(WelcomeInteractorListener listener) {<br>        this.mListener = listener;<br>    }</pre><pre>    @Override<br>    public void loginWithUserName(String username, String password) {</pre><pre>        ParseUser.logInInBackground(username, password, new LogInCallback() {<br>            public void done(ParseUser user, ParseException e) {<br>                if (mListener != null) {<br>                    if (user != null) {<br>                        mListener.onLoginSuccessful();<br>                    }<br>                    else {<br>                        mListener.onLoginError(e);<br>                    }<br>                }<br>            }<br>        });<br>    }<br>}</pre><h4>Summary</h4><p>So this is a very brief summary of what is MVP and how to use it on Android to achieve a cleaner, modular and testable source code. This is just an interpretation of the pattern and is not a silver bullet or the perfect solution for our apps, so any comments or critics are more than welcome!</p><p>To see an example of this implementation you can take a look to one of my open source experimental apps “<strong>Treepolis</strong>”. Is still an in progress project and you can find it here in <a href="https://github.com/Quoders/treepolis-android/tree/develop"><strong>Github</strong></a><br>To see a practical example of the pattern used for the Welcome screen and login functionality check this <a href="https://github.com/Quoders/treepolis-android/tree/develop/app/src/main/java/com/quoders/apps/android/treepolis/ui/welcome"><strong>folder</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf80cb59c31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>