<?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 Elia Maracani on Medium]]></title>
        <description><![CDATA[Stories by Elia Maracani on Medium]]></description>
        <link>https://medium.com/@elia.maracani?source=rss-995bccff7c34------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rRxN_GFEI6GNlW7KmnRTRA.jpeg</url>
            <title>Stories by Elia Maracani on Medium</title>
            <link>https://medium.com/@elia.maracani?source=rss-995bccff7c34------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:58:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@elia.maracani/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[Intro to Android Architecture Components]]></title>
            <link>https://medium.com/@elia.maracani/intro-to-android-architecture-components-e7cd3558c4af?source=rss-995bccff7c34------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7cd3558c4af</guid>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[livedata]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Elia Maracani]]></dc:creator>
            <pubDate>Tue, 16 Jan 2018 17:20:45 GMT</pubDate>
            <atom:updated>2018-01-16T17:22:27.081Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pre-introduction</h3><p>Ok so, first I’ve got to say that I got to know about this new Google set of libraries thanks to Udacity. More precisely to the Google Android Developer Scholarship 2017 course on Udacity. <br> Little after I started the course, I got interested in learning the best practices for programming with Android, so I started surfing the web for a place to learn them.<br> The first thing I did was to head straight to the <a href="https://developer.android.com/">developer.android.com</a> website (as I always do when I want to have a deeper knowledge of how things work in Android). This is where I stumbled into the Architecture Components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*XUhYdhAXLCo_qMaMdunHxQ.jpeg" /></figure><h3>Introduction</h3><p>As we all know, and Android app is made of different parts: Activities, fragments, content providers, broadcast receivers, services, etc.<br> Each of these components have its own lifecycle. Some might have a longer one than others, for example an Activity’s lifecycle is longer than the Fragment’s it contains, but none of them is under our control. It often happens, for example, that an Activity gets destroyed and recreated, the most common scenario is probably when we change the orientation of the device; or that an activity replaces fragments in it, see a navigation drawer that when a different item is clicked shows a different fragment in the Activity.<br> If we keep references to any View in the fragments in the Activity, the fragments won’t be able to be garbage collected, and thus result in a memory leak.</p><p>We should avoid storing any app data in these components too. Picture this scenario: we want to give the user the chance to visualize the POIs close to him in a map or in a list. We create an Activity that contains two fragments, one with the list and the other with the map. They both use the same data (the same list of POIs). I have two options now:</p><ol><li>The Fragment gets the list of POIs every time it is created from the web server (the Fragment stores the data);</li><li>The Activity gets the list of POIs every time it is created from the web server and the fragment ask the activity for the list (the Activity stores the data).</li></ol><p>Let’s analyze these two scenarios in detail:</p><p>In the first case the fragments are responsible for getting the data from the web server and store it. The problem here is that every time the user changes the type of visualization mode, the fragment that was shown before is destroyed and the new one is created. Since the data is stored in the fragment, this new fragment will have to ask the server for the data, since it won’t be able to access that of the other fragment (it has been destroyed remember?). This means every time the fragment will have to wait for the server to display the data. It also results in a waste of processing and network traffic. All in all, it’s a pretty bad situation.</p><p>The second case is what someone might think of doing to solve the problems of the previous scenario. You tell me that if the fragment stores the data then it needs to ask the server for it every time it is created resulting in possible waste of time, network traffic and processing? Ok, then I let the activity store the data and the fragment will ask the Activity for it, so that the web server is asked for new data only when the Activity is created. There’s a catch to this solution: the activity gets destroyed and recreated every time the user changes the device orientation, for example. So what? Should we wait for the activity to get the data from the server every time the user changes the device orientation? It turns out there is a third way we could go that solves all of the before mentioned problems, and also gives the code a much cleaner look!</p><p>We need a way to store the data got from the web server so that it will live longer than the single fragment or activity. This is where the Architecture Components come to our rescue, but before we can dive into them, we need a brief introduction of the Architecture Pattern they are based on: the MVVM.</p><h3>MVVM? What’s that?</h3><p>MVVM is an Architecture Design Pattern that stands for Model-View-ViewModel. It improves over the MVC and MVP patterns.</p><p>It is made up of these three main modules:</p><ul><li>View — it’s goal is to display the data got from the ViewModel and inform it of the user actions;</li><li>ViewModel — it’s goal is to expose the data necessary to the View. It is responsible of storing the data. Since it’s lifecycle is longer that that of the Activity or the Fragment, it survives configuration changes, thus not needing to get the data every time.</li><li>Model — it abstracts how the data source. The ViewModel uses the Model to get and save the data from the source.</li></ul><p>For further details on how this pattern works or which are the differences with the other patterns I recommend you to read <a href="https://medium.com/upday-devs/android-architecture-patterns-part-3-model-view-viewmodel-e7eeee76b73b">this article</a> from Florina Muntenescu.</p><p>Android Architecture Components implement this MVVM pattern.</p><h3>What’s the big deal with Architecture Components?</h3><p>So, what should I do if I can’t store data in any app component? Remember before when I said we have two options for dealing with storing data in an app that shows POIs in a list or on a map? Well, thanks to Architecture Components, there actually is a third option:</p><p><em>A third class (the ViewModel) will be responsible for getting the list of POIs from the web server and expose them to both the Activity and the two Fragments (neither the activity nor the fragments stores the data)</em>.</p><p>Something important about programming in general, that should be burned into our minds, is the <strong>separation of concerns principle</strong>. It states that every component should have a specific goal, and should contain only the code necessary to achieve that goal, so anything related to the UI should be in the Activity’s or Fragment’s class, and not in the ViewModel, vice-versa anything <strong>not</strong> related to UI or displaying data should not be in the Activity’s or Fragment’s class.</p><p>Going forward we will stick with the use case of an app that displays POIs to the user either with a list or on a map.</p><p>The UI will consist of an Activity (<a href="https://gist.github.com/communikein/c843b6330887069a6f046b7993c9de3f"><em>MainActivity.java</em></a>) that will show either one of the two fragments (<a href="https://gist.github.com/communikein/7b5ac7c3b55be42fe39dfb52f38476a3"><em>PoisListFragment.java</em></a> and <a href="https://gist.github.com/communikein/13ae17d296e29a95d67ca90a8926c3f6"><em>PoisMapFragment.java</em></a>) based on whether the user wants to see a list of POIs or a map with them on. Their layout files are, respectively: <a href="https://gist.github.com/communikein/ecc705774ce5ae0bd8a3ffa0688bf6fc"><em>activity_main.xml</em></a>; <a href="https://gist.github.com/communikein/3c5c43a35818267f686653f26baea08c"><em>fragment_pois_list.xml</em></a>; <a href="https://gist.github.com/communikein/e21f456ef69e7220456e54cffb66cdc7"><em>fragment_pois_map.xml</em></a>.</p><p>We will use the <a href="https://gist.github.com/communikein/df51b43202a134fc0f3df3aadb6ad624"><em>Poi.java</em></a> class as the Model and the <a href="https://gist.github.com/communikein/a8c68efcf66ca88f84367c31a9a4aaf2"><em>PoisViewModel.java</em></a> class as the ViewModel that drives the UI.</p><p>The <strong><em>ViewModel</em></strong> will act as an interface between the UI component (in this case the <em>MainActivity</em>) and the source of the data (in this case the <em>AppRepository</em> that will be introduced later). It doesn’t know about the view and is not affected by configuration changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25362f4e36858f70a55169d8078d9bad/href">https://medium.com/media/25362f4e36858f70a55169d8078d9bad/href</a></iframe><p>Still something is missing. We need a way for the Fragments to be able to know when the data is ready or changed, so that it can display it. Enter LiveData.</p><p><strong><em>LiveData</em></strong> is an observable data holder. It lets app components observe for changes without creating a tightly coupled dependency between them. LiveData is also lifecycle aware. This means that it cleans after itself when it is not needed anymore, preventing the app from consuming more precious memory.</p><p>Keep in mind that we also didn’t have to handle the configuration changes. This is thanks to the ViewModel. It can outlive the Activity / Fragment lifecycle. This is also the main reason why we should never reference any View directly in the ViewModel, to prevent memory leaks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-yY0l4XD3kLcZz0rO1sfRA.png" /></figure><h3>Fetching the data</h3><p>Now everything is perfect. The view registers an observer to listen for new data from the ViewModel. This way the View doesn’t care where the data is coming from, being it from internet or a local DB. Now we need a way for the ViewModel to know where to fetch the data from: the web or a local DB? It would be nice if the ViewModel could simply ask for the data and let some other class worry about where to get it from.</p><p>Let’s start with creating the class that will be responsible for fetching the date from the web. To make things easy in this guide we will use <em>Retrofit</em> to access the backend server (in future I’ll show you how to move from this to Firestore). The new class is called <a href="https://gist.github.com/communikein/bfc04b7d4565a5226356c426a6b7c56c">WebService.java</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d22f96344796e0b12b3e76d19bda63/href">https://medium.com/media/52d22f96344796e0b12b3e76d19bda63/href</a></iframe><p>At the beginning of this chapter I said that it would be nice if the ViewModel could simply ask another class for the data, and let this class worry about where to get it from. Enter the <a href="https://gist.github.com/communikein/64261e5afcec4b52d6e47f3c9063fa2f"><strong><em>Repository</em></strong></a>.</p><p>This class has the goal of abstracting the origin of the data. The ViewModel that interact with the repository won’t know whether the data it is receiving are from the web server, a local DB or maybe use some other source, like SharedPreferences, Account Manager, etc. This way we can swap the origin of the data with another one without the ViewModel noticing it. I will only have to tweak the repository class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43a330aae6124779ae6b8cde83b73674/href">https://medium.com/media/43a330aae6124779ae6b8cde83b73674/href</a></iframe><h3>Persisting the data — the Room library</h3><p>The problem with this implementation of the Repository class is that after fetching the data, it does not store it. If, for example, our app included another Activity, every time the user leaves the POIs activity and re-enters it, the app will re-fetch the data, the same happens if the app is killed either by the user or by the OS.</p><p>This behavior is bad for two reasons: it wastes valuable network bandwidth and forces the user to wait for the new query to complete.</p><p>What should we do then? To address this, we will add a Database source to our repository, and to do so we will take advantage of the <strong>Room</strong> library.</p><p><em>“</em><strong><em>Room</em></strong><em> is an object mapping library that provides local data persistence with minimal boilerplate code. At compile time, it validates each query against the schema, so that broken SQL queries result in compile time errors instead of runtime failures. Room abstracts away some of the underlying implementation details of working with raw SQL tables and queries. It also allows observing changes to the database data (including collections and join queries), exposing such changes via LiveData objects. In addition, it explicitly defines thread constraints that address common issues such as accessing storage on the main thread.” — </em>developer.android.com</p><p>This is maybe the one library I like the most. It saves us from writing <strong>a lot</strong> of boilerplate code, check for SQL errors at compile time, <strong>and</strong> let us observe for changes in the database through LiveData.</p><p>To have a working DB in our app we need to code the followings:</p><ol><li>The schemas to add to the DB;</li><li>The Database itself;</li><li>A Database Access Object (DAO), that will allow us to interact with the DB.</li></ol><p>Let’s see how easy and simple this is.</p><p>First things first, the <a href="https://gist.github.com/communikein/df51b43202a134fc0f3df3aadb6ad624">schemas</a>:</p><ol><li>To define our <strong><em>schemas</em></strong>, so that Room knows which are the objects we want to map in the Database, we simply need to add the annotation @Entity just above the declaration of the class. In our case the only class we want to map is the Poi.java.</li><li>Every schema must have a <strong><em>primary key</em></strong>. To tell Room which one it is we add the annotation @PrimaryKey to the field we want as primary key.</li><li>1. If, for any reason, we want to exclude some fields from being mapped to the DB, we simply use the @Exclude annotation.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcacfb007f7a8ccb033c52a324a79aa7/href">https://medium.com/media/bcacfb007f7a8ccb033c52a324a79aa7/href</a></iframe><p>Let’s move the <a href="https://gist.github.com/communikein/aaf6dec594f35557c5cb34ea88e4f6e2">Database</a> itself:</p><ol><li>Create an abstract class that extends from RoomDatabase;</li><li>Mark the just created class with the @Database annotation;</li><li>Tell the Database which are the schemas, by using the parameter <em>entities</em> in the @Database annotation;</li><li>Tell the Database which version it is, by using the parameter <em>version</em> in the @Database annotation.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*y6Jf24V51cSbNzQSNH_vCg.png" /></figure><p>Now on to the <a href="https://gist.github.com/communikein/83fc6988f50288d893d0a829963d2bdd">DAO</a>. <br>Let’s create an interface, mark it with the @Dao annotation and declare all the methods we want to have access to:</p><ol><li>To <strong><em>insert</em></strong> a new Poi, we declare a method that returns void and accepts, as the only parameter, the Poi we want to add; we then mark this method with the @Insert annotation;</li><li>To <strong><em>insert</em></strong> multiple entries, we do the same as before, only using a List&lt;Poi&gt; object as parameter;</li><li>To <strong><em>get</em></strong> a Poi, we declare a method with Poi as return type and has the Poi’s id as a String parameter; mark it with the @Query annotation and write the actual query to get the Poi inside of the annotation.</li><li>To <strong><em>get</em></strong> all the Pois in the database, we do the same as before, only we don’t provide any parameter, and the return type will be a List&lt;Poi&gt;.</li><li>To <strong><em>delete</em></strong> a Poi, we do the same as in 2.3. only, it will return void, and instead of the SELECT statement as query we will use a DELETE statement.</li><li>To <strong><em>update</em></strong> a Poi, we declare a method that returns an int (the number of rows affected by this operation) or void and has as single parameter, a Poi object; finally, we will mark it with the @Update annotation.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8540d09a56c4eac800fe874c3662351/href">https://medium.com/media/e8540d09a56c4eac800fe874c3662351/href</a></iframe><p>We talked earlier about how LiveData lets us observe for changes in the data. How cool would it be if we could use it out of the box to listen to changes in the DB data? Well, as it turns out, we can, and the changes we need to make are quite simple: <br>Modify the getter method so that it will return a LiveData&lt;Poi&gt;, instead of Poi. <br>It’s that simple.<br>Room knows when the database is modified, and it will automatically notify all active observers when the data changes. Because it is using LiveData, this will be efficient since it will update the data only if there is at least one active observer.</p><p>Now, as the last step, we need to reference the DAO from our Database. We do so, by adding a public abstract method of type PoisDao.<br>This is how the Database will look like when it’s done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3503ea603671e9087ba70653513de591/href">https://medium.com/media/3503ea603671e9087ba70653513de591/href</a></iframe><p>Now that the database is all set and done, we can integrate it in the <a href="https://gist.github.com/communikein/b933037a87a6c8f128d7c20cbbf79612">Repository</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a64201089ee31e80d0fddbe303e8e24/href">https://medium.com/media/3a64201089ee31e80d0fddbe303e8e24/href</a></iframe><p>You might be wondering “<em>Hey but… We just changed where the data comes from, shouldn’t we also change the ViewModel or the Fragments’ code to reflect this change?</em>” The great thing about using a Repository is that <em>you don’t need to do that</em>. The repository serves as an abstraction level for the data.<br> Also, this way, it’s easier to test too, since we can switch to a fake Repository while testing the ViewModel.</p><p>Now our code is complete. No matter if the user opens the app after two minutes or two weeks, or if the user comes back to the list fragment after having the map one open, the data will be ready to be used instantly. Meanwhile, our Repository will update the data in the background if needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7cd3558c4af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Data Binding: passing a variable to an <include>d layout]]></title>
            <link>https://medium.com/@elia.maracani/android-data-binding-passing-a-variable-to-an-include-d-layout-3567099b58f?source=rss-995bccff7c34------2</link>
            <guid isPermaLink="false">https://medium.com/p/3567099b58f</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-data-binding]]></category>
            <dc:creator><![CDATA[Elia Maracani]]></dc:creator>
            <pubDate>Thu, 28 Dec 2017 11:20:40 GMT</pubDate>
            <atom:updated>2017-12-28T16:02:42.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say I have a main layout that &lt;include&gt;s a secondary one, and that I want to use in the secondary layout the variable that you are passing to the main layout. How can I do it? Is it even possible?!</p><p>The answer is YES. <br>Well, maybe. <br>It depends.</p><h3>The primary layout</h3><p>First things first, this is how the main layout, looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26eba30952e0e881818be48ece206d51/href">https://medium.com/media/26eba30952e0e881818be48ece206d51/href</a></iframe><p>A few important things about this file:</p><ul><li>The &lt;layout&gt; tag has a new attribute: <em>xmlns:bind=”http://schemas.android.com/apk/res-auto&quot;<br></em>This is necessary to use <em>bind:secondaryUser</em> later.</li><li>The &lt;data&gt; tag contains the variable name and type that we will send to the secondary layout.</li><li>The &lt;include&gt; tag has a new attribute:<br><em> bind:secondaryUser=”@{mainUser}”</em><br>This tells the secondary layout that the main layout is passing him a variable named <strong><em>mainUser</em></strong>, and that it will have to map it to its variable named <strong><em>secondaryUser</em></strong>.</li></ul><h3>The secondary layout</h3><p>This is how the secondary layout looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1d823e43d048100e5cb5067c7f91654/href">https://medium.com/media/c1d823e43d048100e5cb5067c7f91654/href</a></iframe><p>What’s important about this file?</p><ul><li>The <em>&lt;data&gt;</em> tag includes a <em>&lt;variable&gt;</em> tag that has the same name that we used in the main layout to pass the data to the secondary layout: <strong><em>secondaryUser</em></strong>. Also it has the same type of the variable declared in the main layout.</li></ul><h3>The UserDetailActivity class</h3><p>Once both the layouts are set, the only thing left to do is to bind the User variable to the main layout in the Activity, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13dffbe0a910d7243410494a2bca8d65/href">https://medium.com/media/13dffbe0a910d7243410494a2bca8d65/href</a></iframe><p>You simply have to create the User object, and pass it to the Binding class. <br>Notice that the method you use to do so is called <em>set</em><strong><em>MainUser</em></strong><em>().</em> This is not random. It uses the name you declared for the variable in the main layout.</p><p>For each variable you declare in the layout, there will be a setter method for it.</p><h3>Final observation</h3><p>Ok so, at the beginning of this article I’ve said that it depends whether it’s possible to pass the variable to a secondary layout or not. The reason for this is the following:<br>Data binding does not support include as a direct child of a merge element. For example, <strong>the following layout is not supported:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6915ea30b0b508a85363d0e12916fe0/href">https://medium.com/media/e6915ea30b0b508a85363d0e12916fe0/href</a></iframe><p>Ok, this is it.</p><p>Try it.</p><p>Test it.</p><p>Have fun with it ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3567099b58f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>