<?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 Juraj Kušnier on Medium]]></title>
        <description><![CDATA[Stories by Juraj Kušnier on Medium]]></description>
        <link>https://medium.com/@jurajkunier?source=rss-d30c6483af22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fQzzdtr9Brw5ezV3.jpg</url>
            <title>Stories by Juraj Kušnier on Medium</title>
            <link>https://medium.com/@jurajkunier?source=rss-d30c6483af22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:08:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jurajkunier/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[Developing Android App in 2023]]></title>
            <link>https://medium.com/@jurajkunier/developing-android-app-in-2023-60504dd76e38?source=rss-d30c6483af22------2</link>
            <guid isPermaLink="false">https://medium.com/p/60504dd76e38</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Juraj Kušnier]]></dc:creator>
            <pubDate>Mon, 12 Dec 2022 21:09:41 GMT</pubDate>
            <atom:updated>2023-03-02T19:43:53.079Z</atom:updated>
            <content:encoded><![CDATA[<h4>Common and new best practices and recommendations every android developer should know in 2023</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*66VnZmcgIKzjQYz3f5vEdQ.jpeg" /></figure><p>In this short article, I summarize some common and new best practices and recommendations for android app developers. Feel free to use them either when you build a new greenfield project or when you want to remove the legacy look and feel from your existing apps.</p><h3>Java is dead, long live Kotlin</h3><p>If you really don’t know, several years have passed since Google <a href="https://developer.android.com/kotlin/first">announced</a> that Android development will be Kotlin-first. Kotlin is not only safer, better designed, and less verbose than Java but without Kotlin in your codebase, you won’t be able to use modern tools and libraries such as Jetpack Compose or asynchronous programming using Coroutines.<br>Switch to Kotlin if you haven’t done so already!</p><h3>Jetpack Compose</h3><p><a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a> is Android’s recommended modern toolkit for building native UI. It’s mature enough and lets you build UI easier, faster, and with less code. Moreover, Compose and View-based XML layouts could be combined. You can add Compose UI into an existing app that uses a View-based design or include an Android View hierarchy in a Compose UI. This approach is particularly useful if you want to use UI elements that are not yet available in Compose, like AdView or MediaPlayer. When you start a new project there is no reason to use XML layouts anymore.</p><h3>Kotlin Coroutines</h3><p>Asynchronous or non-blocking programming is an important part of Android development. You have to deal with asynchronous stuff every time when you want to perform I/O operations or extensive computations. Kotlin solves this problem in a flexible way by providing <a href="https://kotlinlang.org/docs/coroutines-overview.html">coroutine support</a> at the language level and delegating most of the functionality to libraries. There is no need to implement thread logic by yourself or start AsyncTasks anymore. If you find a tutorial where such things are used, be sure that it is very old.</p><h3>Asynchronous Flow</h3><p>Asynchronous streams are nothing new. You may be familiar with libraries like RxJava/RxAndroid which implement asynchronous programming with observable streams. However, this API is too complex for most use cases and the learning curve is very steep. I experienced projects where Rx streams were tied in a so complicated way that making simple changes took days instead of minutes. Fortunately, we already have a <a href="https://kotlinlang.org/docs/flow.html">Kotlin Flow</a>, a new asynchronous stream library from JetBrains, the company behind the Kotlin language. Sharing many similarities with Rx streams, Kotlin Flow is built on top of Kotlin Coroutines. It implements many well know operators you might know from the Rx world and simplifies working with asynchronous streams. Stop using RxJava and love the Flow!</p><h3>App Architecture</h3><p>App architecture design is an important consideration for ensuring that your apps are robust, testable, and maintainable. Google wasn’t always very opinionated about App Architecture. Fortunately, this changed and we have now the official <a href="https://developer.android.com/topic/architecture">guide to app architecture</a>. The guide discusses concepts such as separation of concerns, different app layers, modularization, or dependency injection. Read the whole guide before writing a single line of code!</p><h3>Material Design</h3><p>Your code should be clean but for User Interface it’s a double true since it’s visible to the user. It’s not easy to design an app to be beautiful and functional at the same time. Fortunately, we have <a href="https://material.io/">Material Design,</a> a design system built and supported by Google designers and developers. Material Design provides a lot of components, layouts, animations, and icons ready to be used as is or customized according to your needs. Users are already familiar with elements such as the Floating Action Button or Navigation Drawer there is no reason to invent different ways to do the same things. Also don’t forget to tell your design team that Android App shouldn’t look like pixel perfect copy of the iOS app!</p><h3>User Experience</h3><p>Mobile devices have some specific constraints such as small screen space, limited performance, battery capacity, or unstable internet connection. Based on these constraints I can give you a few hints about what is good to keep in mind. For example:</p><ul><li>The app should be able to perform all or a critical subset of its core functionality without access to the internet.</li><li>The app should preserve its state and user input. Android system may kill your app anytime. Users usually don’t want to write lengthy chat messages twice because they rotate the screen or switch between apps.</li><li>The app should clearly display its state. Users should see when the button was pressed, if the file is still uploading or if some error occurred.</li><li>The mobile screen is small, remove distraction, focus on one thing at a time and do it well. Split multi-step processes into more screens.</li></ul><p>The rule of thumb is to try not to frustrate the user. If you do everything right, the app with high-quality UX should be a result of your work.</p><h3>Example App</h3><p>I’m working on a small open-source project where I’m going to implement mentioned best practices.</p><p>You can find it here: <a href="https://github.com/jurajkusnier/stock-browser">https://github.com/jurajkusnier/stock-browser</a></p><p>The app itself is very simple. It loads market data from multiple 3rd party APIs and stores them in a local database. Then it allows users to search, browse and mark favorite items.</p><p>App uses <strong>MVI (Model View Intent)</strong> architecture pattern, implemented using <a href="https://orbit-mvi.org/">Orbit-MVI</a> library. Each screen has a matching ViewModel and ScreenState. ViewModel represents the source of truth for the screen. It handles all user input and returns the corresponding UI state that is displayed on the screen. In addition to state, ViewModel can also produce side effects used mainly for navigation between screens. ViewModel calls different use cases to get data to be displayed to the user. The logic for loading and saving data from different resources is implemented by repositories and data sources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dugW9WtoXYPw5zfYlZZ5Nw.png" /><figcaption>App Architecture diagram</figcaption></figure><p><strong><em>Thank you for reading. If you like this article, give it a thumbs up, leave feedback, and share it with your friends. Happy coding!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60504dd76e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to show Snackbar in Jetpack Compose?]]></title>
            <link>https://medium.com/@jurajkunier/how-to-show-snackbar-in-jetpack-compose-3f2d81891f87?source=rss-d30c6483af22------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2d81891f87</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Juraj Kušnier]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 19:55:46 GMT</pubDate>
            <atom:updated>2022-06-21T19:55:46.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fl-Ss_WW4wGzAHB6sGRjJQ.png" /></figure><p>I’m going to write about <strong>Snackbars</strong> and I’m going to show you, in my opinion, the easiest way how to display them in <strong>Jetpack Compose</strong>.</p><blockquote><strong>EDIT:</strong> If you rather watch than read, you can find this tutorial on<strong> </strong><a href="https://www.youtube.com/watch?v=nV3yape6qCk"><strong>YouTube</strong></a><strong> </strong>🍿</blockquote><p>So, without further ado, let’s start by clarifying the concepts.</p><h3>What are Snackbars?</h3><p>Snackbars are UI components providing lightweight feedback about something in the app. Basically, just a brief message informing users of some action that the app has performed or will perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgvi-_WEPrU2SKmP1i6mqA.png" /></figure><p>They appear temporarily and disappear automatically after a timeout or user interaction. A snackbar can contain a single action that is accessible by a text button. Usually something like “<em>try again</em>” or “<em>undo</em>”. And they shouldn’t interrupt the user experience.</p><h3>Implementation</h3><p>Let’s take a look at how are Snackbars implemented in Jetpack Compose. Basically, we have 3 main components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7383e7351d9723f2be95d382c032fc8f/href">https://medium.com/media/7383e7351d9723f2be95d382c032fc8f/href</a></iframe><ul><li><strong>Snackbar</strong> composable is just a visual representation of the Snackbar as defined in Material design guidelines, without show or hide options and without animations.</li><li><strong>SnackbarHost</strong>, this component is responsible for showing and hiding Snackbar as well as its animations. It’s a UI wrapper around the Snackbar mentioned before.</li><li><strong>SnackbarHostState</strong> controls the current Snackbar being shown inside the SnackbarHost as well as the queue of Snackbars supposed to be shown later. It guarantees to show at most one Snackbar at a time.<br>It has a suspended method <strong>showSnackbar()</strong> that you call to show a new Snackbar.</li></ul><p>OK, now, we are clear about what Snackbars are and how they are implemented. And as I mentioned in the beginning I’ll show you the best way how to display them. But first, I have to quickly introduce you to a Scaffold.</p><h3>Scaffold</h3><p>A <strong>Scaffold</strong> is a layout that implements the basic material design layout structure. You can add things like a TopBar, BottomBar, Floating Action Button (FAB), or a Drawer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3s0y5U7NsmhpLp7wzeUE6A.png" /><figcaption>Basic <strong>Scaffold</strong> layout wit Top App Bar, Bottom Navigation and Floating Action Button (FAB)</figcaption></figure><p>The scaffold makes sure everything is displayed together in the right place according to the material design guidelines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11145c0d2ff9e16a984bef41523d187c/href">https://medium.com/media/11145c0d2ff9e16a984bef41523d187c/href</a></iframe><p>As you can see above, Scaffold composable contains many parameters, for example, ScaffoldState with SnackbarHostState mentioned earlier or Snackbar Host. With this knowledge, we are ready to write some code.</p><h3>The Code</h3><p>Let’s start with a composable containing Scaffold and one button. The snackbar should appear when the user presses the button.</p><pre>@Composable<br>fun SnackbarDemo() {<br>Scaffold() {<br>        Button(onClick = {})<br>        {<br>            Text(text = &quot;Click me!&quot;)<br>        }<br>    }<br>}</pre><p>Let’s create a default ScaffoldState inside “remember” method to ensure that we use the same state even after re-composition. As I mentioned earlier, the ScaffoldState contains SnackbarHostState that we can use to show a new Snackbar. We just need to provide necessary parameters such as a message or action label. However, snowSnackbar is a suspended function and we can’t call it directly.</p><pre>@Composable<br>fun SnackbarDemo() {<br><strong>val scaffoldState: ScaffoldState = rememberScaffoldState()</strong><br> <br><br>Scaffold(<strong>scaffoldState = scaffoldState</strong>) {<br>    Button(onClick = {<br> <br>            <strong>scaffoldState.snackbarHostState.showSnackbar(<br>                message = &quot;This is your message&quot;,<br>                actionLabel = &quot;Do something&quot;<br>            )</strong><br>         <br>    }) {<br>        Text(text = &quot;Click me!&quot;)<br>    }<br>}<br>}</pre><p>Let’s use a coroutine scope to lunch a new coroutine without blocking the current thread. When we press the button now the Snackbar should appear on the screen, however, we don’t know if the Snackbar was dismissed or if the user clicked on the action in the Snackbar.</p><pre>@Composable<br>fun SnackbarDemo() {<br>val scaffoldState: ScaffoldState = rememberScaffoldState()<br><strong>val coroutineScope: CoroutineScope = rememberCoroutineScope()</strong><br><br>Scaffold(scaffoldState = scaffoldState) {<br>    Button(onClick = {<br>        <strong>coroutineScope.launch {</strong><br>            scaffoldState.snackbarHostState.showSnackbar(<br>                message = &quot;This is your message&quot;,<br>                actionLabel = &quot;Do something&quot;<br>            )<br>        <strong>}</strong><br>    }) {<br>        Text(text = &quot;Click me!&quot;)<br>    }<br>}<br>}</pre><p>To get this information we just need to check SnackbarResult returned by the suspended function. SnackbarResult is enum and can have value either Dimissined or ActionPerformed. Then we can implement our business logic accordingly.</p><pre>@Composable<br>fun SnackbarDemo() {<br>val scaffoldState: ScaffoldState = rememberScaffoldState()<br>val coroutineScope: CoroutineScope = rememberCoroutineScope()<br><br>Scaffold(scaffoldState = scaffoldState) {<br>    Button(onClick = {<br>        coroutineScope.launch {<br><strong>            val snackbarResult =</strong> scaffoldState.snackbarHostState.showSnackbar(<br>                message = &quot;This is your message&quot;,<br>                actionLabel = &quot;Do something&quot;<br>            )<br>            <strong>when (snackbarResult) {<br>                SnackbarResult.Dismissed -&gt; TODO()<br>                SnackbarResult.ActionPerformed -&gt; TODO()<br>            }</strong><br>        }<br>    }) {<br>        Text(text = &quot;Click me!&quot;)<br>    }<br>}<br>}</pre><p>To see the implementation in action please take a look at the YouTube video where I recorded the whole tutorial and the final result.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FnV3yape6qCk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnV3yape6qCk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FnV3yape6qCk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f80064b41333e3ee70927f271605b97/href">https://medium.com/media/8f80064b41333e3ee70927f271605b97/href</a></iframe><p><strong><em>If you like this article, give it a thumbs up, leave feedback, and share it with your friends. Happy coding!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2d81891f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating SharedPreferences to Jetpack DataStore]]></title>
            <link>https://medium.com/@jurajkunier/migrating-sharedpreferences-to-jetpack-datastore-9deb8259063?source=rss-d30c6483af22------2</link>
            <guid isPermaLink="false">https://medium.com/p/9deb8259063</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-development]]></category>
            <dc:creator><![CDATA[Juraj Kušnier]]></dc:creator>
            <pubDate>Fri, 25 Sep 2020 12:07:41 GMT</pubDate>
            <atom:updated>2020-09-25T17:32:11.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApGkqeOg86T2dEMh6MN5-g.png" /></figure><p><a href="https://developer.android.com/jetpack/androidx/releases/datastore">Jetpack DataStore</a> is a new library providing a handy alternative to SharedPreferences. It comes with two slightly different approaches <a href="https://developer.android.com/topic/libraries/architecture/datastore">Preferences DataStore</a> and <a href="https://developer.android.com/topic/libraries/architecture/datastore">Proto DataStore</a>.</p><p><strong>Preferences DataStore </strong>stores and accesses data using keys. This implementation does not require a predefined schema, and it does not provide type safety.</p><p><strong>Proto DataStore </strong>stores data as instances of a custom data type. This implementation requires you to define a schema using <a href="https://developers.google.com/protocol-buffers">protocol buffers</a>, but it provides type safety.</p><h3>What’s wrong with SharedPreferences?</h3><p>SharedPreferences interface provides an API for managing a small collection of key-values preferences saved in the XML file. Keys are always strings and values can be primitives or strings. API allows you reading preferences by variousget methods and saving them with Editor class. Here you should be careful because to be able to read preferences, android has to open an actual XML file and that is I/O operation and could take some time. All get methods are synchronous and have to wait until the preferences file is load into memory, so could potentially cause <a href="https://developer.android.com/topic/performance/vitals/anr">ANR</a> if they are called from UI thread. For writing preferences back to the file you have two methods: apply() which is asynchronous but doesn’t give you any information if the operation succeeded or failed and commit() which is synchronous therefore it shouldn’t be called from UI thread, but it returns a boolean value announcing if the operation succeeded or failed. Another pitfall is that SharedPreferences doesn’t guarantee type safety, which is error-prone and may lead to parsing errors and runtime exceptions.</p><h3><strong>What’s cool on Jetpack DataStore?</strong></h3><p>DataStore comes with nice interfaces using an asynchronous corutine based data streams for reading and writing data. It’s perfectly safe to be used on UI thread because all file operations are executed on an I/O thread by default. Data are no longer saved in XML format but rather in Google’s binary <a href="https://developers.google.com/protocol-buffers">protobuf</a> format. It’s not easily readable by a common text editor but fortunately, there are already plenty of tools that can help you to decode and read the data stored in this format. Last but not least DataStore handles data migration, guarantees data consistency, and handles data corruption.</p><h3>Typical SharedPreferences implementation</h3><p>Let’s say you already have an android application showing list of user’s favorite movies. You implement filtering movies by genre and sorting by name, year, and rating. For better user experience you want to keep these settings persistent even after user leaves the app and open it later, so you save the data using SharedPreferences. You follow <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns </a>design principle and <a href="https://developer.android.com/jetpack/guide">Android Architecture Patterns</a> and you pack all code handling SharedPreferences into the repository class that is used in your ViewModel. Your code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b011fd2ef7146109b2afe1e4313ee3e/href">https://medium.com/media/3b011fd2ef7146109b2afe1e4313ee3e/href</a></iframe><p>You have updateFilter() method for modifying filter preferences and updateSortOrder() for modifying order preferences and read-only variable userPreferencesFlow which returns StateFlow stream with current UserPreferences data object.</p><h3>Let’s migrate</h3><p>If previous lines convicted you to give DataStore a try, you should be aware that Jetpack DataStore is still in early alpha and many things may change in the future.</p><p>To be able to use Jetpack Data Store in your app, you will need to add it as a dependency to your gradle file. I’ll be using only Preferences DataStore so you need to add the following library.</p><pre>dependencies {<br>  implementation &quot;androidx.datastore:datastore-preferences:1.0.0-alpha01&quot;<br>}</pre><p>If you like to implement Proto Data Store you will need to add datastore-core library, which is also currently in version 1.0.0-alpha01.</p><p>When you have all the necessary dependencies, you can call createDataStore() to create SingleProcessDataStore. Keep in mind that you should have only one instance of DataStore acting on a file at a time. Preferences will be stored in a file with the name “datastore/” + name + “.preferences_pb”. Migration automatically handles the translation of all your keys saved by SharedPreferences to DataStore format.</p><pre>val dataStore: DataStore&lt;Preferences&gt; = context.<em>applicationContext.createDataStore</em>(<br>    name = USER_PREFERENCES_NAME,<br>    migrations = <em>listOf</em>(<em>SharedPreferencesMigration</em>(context, USER_PREFERENCES_NAME))<br>)</pre><p>DataStore provides efficient, cached (when possible) access to the latest durably persisted state. The flow will always either emit a value or throw an exception encountered when attempting to read from disk.</p><pre>val userPreferencesFlow: Flow&lt;UserPreferences&gt; = dataStore.data<br>    .<em>catch </em><strong>{ </strong>exception <strong>-&gt;<br>        </strong>if (exception is IOException) {<br>            emit(<em>emptyPreferences</em>())<br>        } else {<br>            throw exception<br>        }<br>    <strong>}<br>    </strong>.<em>map </em><strong>{ </strong>preferences <strong>-&gt;<br>        </strong>UserPreferences(<br>            sortOrder = SortOrder.valueOf(preferences[SORT_ORDER] ?: SortOrder.<em>NONE</em>.name),<br>            filter = Filter.valueOf(preferences[FILTER] ?: Filter.<em>NONE</em>.name)<br>        )<br>    <strong>}</strong></pre><p>edit() coroutine handles saving data. The coroutine completes when the data has been persisted durably to disk (after which DataStore.data will reflect the update). If the transform or write to disk fails, the transaction is aborted and an exception is thrown.</p><pre>suspend fun updateSortOrder(sortOrder: SortOrder) {<br>    dataStore.edit <strong>{ </strong>preferences <strong>-&gt;<br>        </strong>preferences[SORT_ORDER] = sortOrder.name<br>    <strong>}<br></strong>}</pre><p>The new repository code looks as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b2c23bf52d4e91ff43106b7afd6a524/href">https://medium.com/media/2b2c23bf52d4e91ff43106b7afd6a524/href</a></iframe><p>updateFilter() and updateSortOrder() methods are now coroutines so you have to use CoroutineScope (viewModelScope in this case) to call them. userPreferencesFlow didn’t change but contains error handling now and we don’t need MutableStateFlow to manually emit changes, because this is implemented by DataStore itself.</p><p>Let’s look at changes in the file-system after migration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*420k_hqRon_1bpBirv56WQ.png" /><figcaption>File system before migration. <strong>SharedPreferences</strong> implementation.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0avbq_xaiWz1lO4ZAFs2Og.png" /><figcaption>File system after migration. <strong>DataStore</strong> implementation.</figcaption></figure><p>The migration process remove the old files used by SharedPreferences. Ensure that you don’t use those files anymore in the code, as well as old SharedPreferences implementation.</p><p>As you can see, migration from SharedPreferences to Preferences DataStore is really easy and straightforward. And as a bonus, you get coroutines, UI safety, and error handling for free.</p><p><strong><em>If you like this article, give it a thumbs up, leave feedback, and share it with your friends. Happy coding!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9deb8259063" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlinx Json vs Gson]]></title>
            <link>https://medium.com/@jurajkunier/kotlinx-json-vs-gson-4ba24a21bd73?source=rss-d30c6483af22------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ba24a21bd73</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[songs]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Juraj Kušnier]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 18:12:21 GMT</pubDate>
            <atom:updated>2020-01-03T18:12:21.777Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGWZzDuPE05SVFKXCMBivA.jpeg" /></figure><p>If you have ever implemented any REST API in your mobile app, you should be familiar with JSON format.</p><blockquote><a href="https://en.wikipedia.org/wiki/JSON">JSON</a> is an open-standard file format or data interchange format that uses human-readable text to transmit data objects consisting of attribute-value pairs and array data types.</blockquote><p>The most common way how to parse JSON-format data to java/kotlin objects is by using one of the popular libraries like <a href="https://github.com/FasterXML/jackson">Jackson</a>, <a href="https://github.com/square/moshi">Moshi</a> or <a href="https://github.com/google/gson">Gson</a>. It’s likely that you are using kotlin, however, all previously mentioned libraries are java-based. Kotlin is 100% interoperable with java, however, because of some small nuances, sometimes you could encounter unexpected results.</p><p>Let’s define the <strong>User</strong> data class with some optional fields and default values. Don’t forget that data class and optional fields are kotlin features, not available in java.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0f24bc211168304db7578f6774793fc/href">https://medium.com/media/e0f24bc211168304db7578f6774793fc/href</a></iframe><p>And now you want to parse very simple JSON string.</p><pre>{<br>    &quot;name&quot; : &quot;John Doe&quot;,<br>    &quot;email&quot; : &quot;john.doe@email.com&quot;<br>}</pre><p>Let’s add <a href="https://github.com/google/gson">Gson</a> dependencies to your project and create a unit test to see how this java library handles your input.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21ae5bca8932a943d0e4ac9cc7d0bd79/href">https://medium.com/media/21ae5bca8932a943d0e4ac9cc7d0bd79/href</a></iframe><p>The test has passed! As you can see, gson library totally ignores your default values and uses <em>0</em> to complete missing primitive field and <em>null</em> instead of missing enum object. This means that gson deserialization even breaks kotlin null-safety and may cause app crash. To prevent this unwanted behavior, you could use nullable types and add supplementary code to handle these edge cases or you can use a smarter kotlin-based serialization library that can solve it for you.</p><h3>Kotlin serialization comes to rescue us!</h3><p><a href="https://github.com/Kotlin/kotlinx.serialization">Kotlin serialization</a> is kotlin oriented cross-platform reflectionless serialization library from JetBrains. This library doesn’t use reflectionless but rather explicit annotation @Serializable. After applying the annotation, the compiler plugin adds a special function serializer() on your companion object, returning serializer of type KSerializer. KSerializer object implements interfaces required for serializing and deserializing your data class. Library provides three ready to use formats: JSON, CBOR, and Protobuf. The advantage of this approach is that it works also outside of the JVM world, for example in Kotlin/Native or JavaScript.</p><p>Using Kotlin Serialization requires kotlin compiler v1.3.30 or higher. You have to add serialization plugin to your gradle build script, apply the plugin and add the dependency on the serialization runtime library. All information about the configuration are available in the <a href="https://github.com/Kotlin/kotlinx.serialization">documentation</a>.</p><p>Now, you can Json class from kotlinx.serialization.json to serialize your input string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57f3f28350a69530623190a80c2ff432/href">https://medium.com/media/57f3f28350a69530623190a80c2ff432/href</a></iframe><p>All tests have passed! <strong>Json</strong> takes advantage of kotlin language features and returns a more predictable output.</p><p>You might have noticed that IDE complains about Json.parse() call. At the time of writing this article, the library is stable, however, there are no API compatibility guarantees between versions, that’s why some methods are called experimental and IDE shows you a warning when you try to use them.</p><h3>Kotlinx.serialization + Retrofit</h3><p><a href="https://github.com/square/retrofit">Retrofit</a> is a very popular HTTP client for android and java from square. It doesn’t have build-in support for kotlin serialization but it allows you to add a converter factory for serialization and deserialization of objects. You could write your own converter factory or you can use one form Jake Wharton.</p><p><a href="https://github.com/JakeWharton/retrofit2-kotlinx-serialization-converter">https://github.com/JakeWharton/retrofit2-kotlinx-serialization-converter</a></p><p>To start using Retrofit 2 Converter.Factory for Kotlin serialization just add library dependencies and add a converter factory when building your Retrofit instance using the asConvertFactory extension function.</p><pre>val contentType = &quot;application/json&quot;.<em>toMediaType</em>()<br><br>val retrofit = Retrofit.Builder()<br> .baseUrl(&quot;https://www.example.com&quot;)<br> <strong>.addConverterFactory(Json(JsonConfiguration(strictMode = false)).<em>asConverterFactory</em>(contentType))</strong><br> .build()</pre><p>You can also use <strong>JsonConfiguation</strong> to configure Json serializer, for example, to turn on/off encoding default values or to enable/disable strict mode. Strict mode is turned on by default, which prohibits unknown keys in the JSON and non-numerical values in floating-point numbers. It’s good practice to keep strict mode enabled in debug build and turn it off in release build of your app.</p><p>This article covers only very basic usage of kotlin serialization. If you want more information about how serializer works under the hood or how to write your own encoder/decoder, I would recommend you to read the <a href="https://github.com/Kotlin/kotlinx.serialization">documentation</a> and watch the talk from <a href="https://www.youtube.com/watch?v=IhKTIFlNrC4&amp;t=299s">KotlinConf 2019: Design of Kotlin Serialization by Leonid Startsev.</a></p><p><strong><em>If you like this article, give it a thumbs up, leave feedback and share it with your friends. Happy coding!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ba24a21bd73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Shared Preferences Listener implemented by RxJava and LiveData]]></title>
            <link>https://medium.com/@jurajkunier/android-shared-preferences-listener-implemented-by-rxjava-and-livedata-cfac02683eac?source=rss-d30c6483af22------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfac02683eac</guid>
            <category><![CDATA[rxjava]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Juraj Kušnier]]></dc:creator>
            <pubDate>Sun, 26 Aug 2018 15:03:13 GMT</pubDate>
            <atom:updated>2018-08-26T15:03:13.183Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have a relatively small collection of key-values that you’d like to save, you should use the <a href="https://developer.android.com/training/data-storage/shared-preferences">SharedPreferences APIs</a>. A <a href="https://developer.android.com/reference/android/content/SharedPreferences">SharedPreferences</a> object points to a file containing key-value pairs and provides simple methods to read and write them. The basic implementation may look as follows:</p><pre>val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)</pre><pre><em>//Read value from default shared preferences</em><br>val value = sharedPreferences.getInt(PREFERENCE_KEY, 0)</pre><pre><em>//Increase value and write it back</em><br>sharedPreferences.edit().putInt(PREFERENCE_KEY,value + 1).apply()</pre><p>Let’s imagine we have Activity with two Fragments using data from the same preference key. When the first Fragment changes the value we want to see changes immediately in the second Fragment. Shared Preferences APIs provide <a href="https://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListener">Preferences Change Listener </a>for this purpose. The interface defines a callback to be invoked when a shared preference is changed, added or removed. Let’s look at the following example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3354e1a955586edfe1228ca705a2ef7/href">https://medium.com/media/d3354e1a955586edfe1228ca705a2ef7/href</a></iframe><p>In the beginning, we create a new listener. We watch only certain key and when the change occurs, listener updates TextView in the UI. Constants and methods handling UI updates are defined in the parent class. The listener is registered in onResume(), when the Fragment comes to the foreground and UI is ready to be used. In onPause() the listener is unregistered because we don’t want to update UI when the Fragment may not be loaded anymore and also to avoid memory leaks. Listener updates UI only when preferences data change. If we want to have data available immediately after app starts, we have to add another update call in onResume().</p><p>This implementation is straightforward and it provides us with everything we need. However, it has a few drawbacks. We handle data, business logic and UI in the Fragment what is again the <a href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns </a>design principle. In addition, we have to override a Fragment’s methods to handle its lifecycle. Can we do it better?</p><p>Let’s implement the same functionality using <a href="https://developer.android.com/topic/libraries/architecture/viewmodel"><strong>ViewModel</strong></a> and <a href="https://developer.android.com/topic/libraries/architecture/livedata"><strong>LiveData</strong></a>.</p><ul><li><strong>LiveData</strong> is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as Activities, Fragments, or Services.</li><li>The <strong>ViewModel</strong> store and manage UI-related data in a lifecycle conscious way.</li></ul><p>In the following code snippet, we create two classes. LiveDataViewModel class provides an instance of the LiveSharedPreferences, which extends LiveData and implements preferences listener. The listener is registered when an object is being used, which means when the object get at least one observer and unregistered when the number of active observers changes to zero.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c465f90518ae3420d8d12f4aa07a7c22/href">https://medium.com/media/c465f90518ae3420d8d12f4aa07a7c22/href</a></iframe><p><a href="https://developer.android.com/topic/libraries/architecture/">Android Architecture Components </a>provide methods helping to obtain an instance of ViewModel. The new instance of ViewModel is created when Fragment is created for the first time. When the Fragment is re-created because of configuration changes the same instance of ViewModel is retained. In this case we implement our custom ViewModelFactory to instantiate new LiveDataViewModel and initialize its properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80a65aff4c28029dd231d00fdb029cc5/href">https://medium.com/media/80a65aff4c28029dd231d00fdb029cc5/href</a></iframe><p>To access LiveData we use observe() method, where we define <a href="https://developer.android.com/topic/libraries/architecture/lifecycle#lco">Lifecycle Owner</a> and <a href="https://developer.android.com/reference/android/arch/lifecycle/Observer">Observer</a>. Lifecycle Owner is the Fragments itself. It means that Observer callback will not be called when the Fragment is not in active state. When data change during Fragment’s inactive state callback will be invoked when Fragment becomes active again.</p><p>ViewModel does not provide LifecycleOwner object. When we want to observe LiveData in ViewModel we have to use observeForever() method. This call is similar to observe with a LifecycleOwner, which is always active. This means that the given observer will receive all events and will never be automatically removed. We should manually call to stop observing this LiveData with removeObserver().</p><p>LifeData is a nice implementation of the lifecycle-aware observer pattern. However, sometimes we don’t need the observer to be lifecycle-aware or we want to access data as a stream or do more advanced transformations. Then <strong>RxJava</strong> comes to help.</p><p><a href="https://github.com/ReactiveX/RxJava"><strong>RxJava</strong></a> extends the observer pattern to support sequences of data/events and adds operators that allow you to compose sequences together declaratively while abstracting away concerns about things like low-level threading, synchronization, thread-safety and concurrent data structures. In the following code snippet, we can see the same preferences listener implemented by RxJava.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d0fd6a689fd60f2fcc6080c9d54c17f/href">https://medium.com/media/2d0fd6a689fd60f2fcc6080c9d54c17f/href</a></iframe><p>We create new observable from scratch using Observable.create(). There are plenty of more advanced approaches how to create observable in RxJava (for example syncOnSubscribe(), fromCallable() or fromEmitter()) but for purpose of this demo, it’s good enough. New preferences listener is registered for each observer which subscribes the observable. And it’s unregistered when the observer disposes of the resource. Observable is subscribed in ViewModel where we can eventually do additional modifications and the result is put to LiveData object which is observed in the Fragment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9tGFJLfnwywWyhQaNSDWg.gif" /></figure><p>In the end, all three approaches get you the same result. Every method has pros and cons and it‘s suitable for a slightly different use case. It’s up to you and your project needs for which solution you decide.</p><p>I hope this article was useful for you. If you enjoyed reading it please share this article with others! Also, don’t hesitate to leave feedback. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfac02683eac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing UI tests with Dagger Android and MockWebServer]]></title>
            <link>https://medium.com/@jurajkunier/writing-ui-tests-with-dagger-android-and-mockwebserver-aed9564e89b3?source=rss-d30c6483af22------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed9564e89b3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[espresso]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Juraj Kušnier]]></dc:creator>
            <pubDate>Fri, 03 Aug 2018 17:13:37 GMT</pubDate>
            <atom:updated>2019-03-18T16:10:57.601Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s imagine we have a simple Android app that interacts with user inputs, communicates with REST API server and shows some data back to the user. The code is well structured and decoupled with using Dagger 2 dependency injection framework. The app contains only one screen with <a href="https://developer.android.com/reference/android/widget/SearchView">SearchView</a> for user input and <a href="https://developer.android.com/guide/topics/ui/layout/recyclerview">RecyclerView</a> for server output.</p><p>Our task is to write an instrumented UI test to prove that our app works correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*08MOXwrK_VDK25Tc2MGX9Q.gif" /></figure><h3>Introduction</h3><p>Before we dig into the task, let’s look at the code structure, dependencies, and patterns used in this project.</p><p><a href="https://en.wikipedia.org/wiki/Dependency_injection"><strong>Dependency injection</strong></a> is a technique whereby one object (or static method) supplies the dependencies of another object.</p><p><a href="https://google.github.io/dagger/"><strong>Dagger 2</strong></a><strong> </strong>is a fully static, compile-time dependency injection framework for both Java and Android. If you are not familiar with Dagger 2 please read the <a href="https://google.github.io/dagger/users-guide">documentation</a>. It’s not in my intent to explain to you how this library works. I want to focus more on the right implementation and testing. Although you can write an android app in Java, many of the patterns commonly applied to code intended for Android are contrary to those applied to other Java code. When we look at the following code, we can see the problem. This implementation breaks a core principle of dependency injection.</p><blockquote>A class shouldn’t know anything about how it is injected.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf2f1ca541892a7ec15fc9bff158783e/href">https://medium.com/media/bf2f1ca541892a7ec15fc9bff158783e/href</a></iframe><p><a href="https://google.github.io/dagger/android.html"><strong>Dagger Android</strong></a><strong> </strong>is a part of the Dagger 2 library that can help you solve this problem. It provides useful classes like DaggerApplication, DaggerActivity or DaggerFragment witch implements AndroidInjection to inject the dependencies under the hood. The same activity may looks as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aae55ecaaae34036bf92b3aac914c259/href">https://medium.com/media/aae55ecaaae34036bf92b3aac914c259/href</a></iframe><p>Best practice how to keep source code clean, readable and easy to test is to have a well-structured code divided into multiple modules, where each module is responsible for different part of the app like network communication, data storage, user interface, etc.</p><p><a href="https://developer.android.com/training/testing/ui-testing/"><strong>User interface testing</strong> </a>lets you ensure that your app meets its functional requirements and achieves a high standard of quality such that it is more likely to be successfully adopted by users.</p><p>You could have heard that automated UI tests are flaky, fragile and unreliable. Especially when you are testing the app working with 3rd party API service. Sure, the network connection is unreliable and server responses are not in your hands. Luckily when we have multiple decoupled modules we can just swap network module out for a fake network module during the test to simulate the behavior of API services and have constant responses to certain requests.</p><p><a href="https://github.com/square/okhttp/tree/master/mockwebserver"><strong>MockWebServer</strong></a><strong> </strong>is handy library from square contains scriptable web server for testing HTTP clients. It allows you to specify responses to app requests, simulate server errors, slow loading, and more useful things. You can find more info about this library in the <a href="https://github.com/square/okhttp/tree/master/mockwebserver">documentation</a>.</p><p>A <strong>test runner</strong> is a tool that executes tests and shows you test results.</p><p>The <a href="https://developer.android.com/training/testing/espresso/"><strong>Espresso</strong></a> testing framework is an instrumentation-based API and works with the <a href="https://developer.android.com/reference/android/support/test/runner/AndroidJUnitRunner"><em>AndroidJUnitRunner</em></a> test runner. Espresso has basically three main components:</p><ul><li><em>ViewMatchers </em>allow finding the view in the current view hierarchy</li><li><em>ViewActions </em>allow performing actions on the views</li><li><em>ViewAssertions </em>allow asserting state of a view</li></ul><p>Base Espresso test looks as follows:</p><pre><strong>onView</strong>(ViewMatcher)       <br> .<strong>perform</strong>(ViewAction)     <br>   .<strong>check</strong>(ViewAssertion);</pre><h3><strong>UI Test</strong></h3><p>To enable Dagger 2 annotation processor in <strong><em>androidTest</em></strong> folder we need to add a few lines to <strong><em>build.gradle</em></strong>.</p><pre><strong>kaptAndroidTest</strong> &quot;com.google.dagger:dagger-compiler:$dagger_version&quot;<br><strong>kaptAndroidTest</strong> &quot;com.google.dagger:dagger-android-processor: $dagger_version&quot;</pre><p>Next, we need to create a fake network module that will connect to <strong><em>MockWebServer</em></strong> instead of the real API server. We don’t even need to change the whole module only the part that provides base URL to API server.</p><p>As you can see in the following code snippet we created MockUrlModule which provides MockWebServer instance and url to this server. Because Android doesn’t allow network operations on main thread we need to perform these operations on another thread. We still block main thread because we are waiting until these threads finish but we don’t need to worry about it because this code will be executed only in the testing environment. You can use also asynchronous approach if you want cleaner solution but you will need to change also production code in that case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c52910b3b0ab7f164b30e8697d180bb/href">https://medium.com/media/4c52910b3b0ab7f164b30e8697d180bb/href</a></iframe><p>We create <strong><em>TestAppComponent</em></strong> that extend our <strong><em>AppComponent</em></strong> and replace original <strong><em>UrlModule::class</em></strong><em> </em>out for <strong><em>MockUrlModule::class</em></strong>. We want a direct access to a mock web server from the testing environment so we add an abstract function getMockWebServer(). We don’t need to worry about implantation. Dagger will create DaggerTestAppComponent that implements this interface for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfc71ea233885878196e1a8ef5b624f9/href">https://medium.com/media/dfc71ea233885878196e1a8ef5b624f9/href</a></iframe><p>And we can finally write our first instrumented test. If you are not familiar with UI test I recommend you to read the <a href="https://developer.android.com/training/testing/ui-testing/">android documentation</a>.</p><p>As you can see on the line number 5 in the following snippet, we create ActivityTestRule for the MainActivity under test. We want to start the activity in touch mode but not automatically, because we want to manually inject dependencies. Next, we create an injector and launch activity.</p><p>In the first test, we find out whether the app can handle server error or not. The app should show snackbar with an error message. We setup how mock web server should respond to our request and simulate user input. Espresso doesn’t directly support SearchView, so we have to write custom ViewAction for this View as we can see on the line number 61. Test waits for 1s and after then check if snackbar with error message appears on the screen. Sleep is not the best way how to wait for the network response, but until we use our mock web server we don’t need to worry about it. The better way is to use <a href="https://github.com/JakeWharton/okhttp-idling-resource">Idling Resource</a> but we will need to change also production code in that case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae91bc2e7c63326678c7f5c998f4be27/href">https://medium.com/media/ae91bc2e7c63326678c7f5c998f4be27/href</a></iframe><p>In the second test, we find out whether the app shows a correct number of items in RecyclerView. Again we setup mock web server and simulate user input. To find out a number of items in RecyclerView we need to implement custom matcher. The matcher is implemented in the following snippet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a2a94a16af01d090c599f0db6744dbf/href">https://medium.com/media/1a2a94a16af01d090c599f0db6744dbf/href</a></iframe><p>Now we can connect our android device and run the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2-c5G8qmVbMIsL9gKHGMA.png" /></figure><p>If we made everything right we should see that <strong>All Tests Passed</strong>.</p><p><a href="https://github.com/jurajkusnier/android-app-template">The project source code is available on GitHub</a></p><p>I hope this article was useful for you. If you enjoyed reading it please share this article with others! Also don’t hesitate to leave a feedback. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed9564e89b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>