<?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 Adam Styrc on Medium]]></title>
        <description><![CDATA[Stories by Adam Styrc on Medium]]></description>
        <link>https://medium.com/@styrc.adam?source=rss-e95fb12fae5e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Vew9UVq5pPAZEmfs.</url>
            <title>Stories by Adam Styrc on Medium</title>
            <link>https://medium.com/@styrc.adam?source=rss-e95fb12fae5e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:28:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@styrc.adam/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[Coordinating floating action button along Bottom Sheet]]></title>
            <link>https://medium.com/vattenfall-tech/coordinating-floating-action-button-along-bottom-sheet-45c37c43c1ef?source=rss-e95fb12fae5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/45c37c43c1ef</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-bottomsheet]]></category>
            <category><![CDATA[floating-action-button]]></category>
            <category><![CDATA[coordinatorlayout]]></category>
            <dc:creator><![CDATA[Adam Styrc]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 13:14:29 GMT</pubDate>
            <atom:updated>2020-06-16T06:37:48.588Z</atom:updated>
            <content:encoded><![CDATA[<p>At InCharge app, we currently work hard on a full app redesign and so far I can tell we’ll use <strong>Bottom Sheets</strong> heavily 😎 Bottom Sheet itself is not that hard to add, assuming we use <em>CoordinatorLayout </em>as a parent.</p><p>Let’s look at a case study I’m going to focus on today. We want <strong>sticking out bottom sheet</strong> with a list of items on a map if any. The bottom sheet could be dragged down or expanded to a fullscreen size. And above the sheet we want a <strong>Floating Action Button</strong> that <strong>will move along our bottom sheet</strong>, except when expanding the bottom sheet, it will get overlapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2185mFZWmOquhfh2QuCt6w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcST4XRcmEXUHN58zTIStg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKmyyfmnCsRziVwQ-ae2cw.jpeg" /></figure><p>We’ll start from nesting the XML layout and as I mentioned we will need a <strong>CoordinatorLayout </strong>because thanks to the <strong>Behaviours</strong> we can describe any views moves dependencies!</p><h3>In the xml</h3><p>Instead of using official Floating Action Button, I’ll just use ImageView.</p><pre>&lt;androidx.coordinatorlayout.widget.CoordinatorLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:layout_marginTop=&quot;72dp&quot;&gt;<br><br>    &lt;ImageButton<br>        android:id=&quot;@+id/ivMyLocation&quot;<br>        android:layout_width=&quot;40dp&quot;<br>        android:layout_height=&quot;40dp&quot;<br>        android:layout_gravity=&quot;bottom|end&quot;<br>        android:layout_marginEnd=&quot;@dimen/general_margin&quot;<br>        android:layout_marginBottom=&quot;56dp&quot;<br>        android:background=&quot;@drawable/circle_incharge_white&quot;<br>        android:src=&quot;@drawable/ic_my_location_blue&quot;      app:layout_behavior=&quot;com.nuon.laadpalen.ui.MapFloatingButtonBehavior&quot;/&gt;<br><br>    &lt;androidx.core.widget.NestedScrollView<br>        android:id=&quot;@+id/svBottomSheetChargingLocationsList&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:background=&quot;@drawable/rounded_top_incharge_white&quot;<br>        android:orientation=&quot;vertical&quot;<br>        app:behavior_hideable=&quot;true&quot;<br>        app:behavior_peekHeight=&quot;@dimen/charging_locations_list_peek_height&quot;      app:layout_behavior=&quot;com.google.android.material.bottomsheet.BottomSheetBehavior&quot;&gt;<br><br>        &lt;LinearLayout<br>            android:id=&quot;@+id/layoutChargingLocationsListContent&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:orientation=&quot;vertical&quot;&gt;<br>...<br>        &lt;/LinearLayout&gt;<br><br>    &lt;/androidx.core.widget.NestedScrollView&gt;<br>&lt;/androidx.coordinatorlayout.widget.CoordinatorLayout&gt;</pre><p>So as we see there are 2 behaviours:</p><ol><li><strong><em>com.google.android.material.bottomsheet.BottomSheetBehavior</em></strong><em> </em>— it will handle bottom sheet scroll behaviour for us. It is built in the Android dependency <em>‘androidx.coordinatorlayout:coordinatorlayout:1.1.0’. </em>Note that we have to put additional parameters to make the bottom sheet collapsable to desired height (sticking out height):</li></ol><pre>app:behavior_hideable=&quot;true&quot;   app:behavior_peekHeight=&quot;@dimen/charging_locations_list_peek_height&quot;</pre><p>2. <strong><em>com.nuon.laadpalen.ui.MapFloatingButtonBehavior </em></strong><em>—</em><strong><em> </em></strong><em>this is something custom, we will need to create MapFloatingButtonBehavior class as a subclass of </em><strong>CoordinatorLayout.Behavior</strong>.</p><p>⚠️ When passing a custom Behavior make sure to put full path of the class instead of e.g. “ui.MapFloatingButtonBehavior” ! ️⚠️</p><p>🧨 Otherwise, you might not get any futher than:</p><blockquote>android.view.InflateException: Binary XML file line … Could not inflate Behavior subclass ui.MapFloatingButtonBehavior <em>🥺</em></blockquote><h3>Implementing the Behavior</h3><p>Finally, we get to the <strong>MapFloatingButtonBehavior </strong>implementation. If we plan on using the Befhavior just from the xml, a 2-argument constructor (Context, AttributeSet) is sufficient.</p><p>In the custom <em>Behavior</em> we need to indicate a dependency with our bottom sheet view (via <em>layoutDependsOn</em>) and then add a callback <em>onDependentViewChanged which </em>will only refer to the bottom sheet changes:</p><pre>class MapFloatingButtonBehavior(<br>        context: Context,<br>        attrs: AttributeSet?<br>) : CoordinatorLayout.Behavior&lt;View&gt;(context, attrs) {<br>    private val locationsListBottomSheetPeekHeight =<br>            context.<em>resources</em>.getDimension(R.dimen.<em>charging_locations_list_peek_height</em>)<br>    private val margin = context.<em>resources</em>.getDimension(R.dimen.<em>small_margin</em>)<br><br>    override fun layoutDependsOn(<br>            parent: CoordinatorLayout,<br>            child: View,<br>            dependency: View<br>    ): Boolean {<br>        return dependency.<em>id </em>== R.id.<em>svBottomSheetChargingLocationsList<br>    </em>}<br><br>    override fun onDependentViewChanged(<br>            parent: CoordinatorLayout,<br>            child: View,<br>            dependency: View<br>    ): Boolean {<br>        if (dependency.<em>y </em>&lt; parent.<em>height </em>- locationsListBottomSheetPeekHeight) {<br>            child.<em>y </em>= parent.<em>height </em>- locationsListBottomSheetPeekHeight - (child.<em>height </em>+ margin)<br>        } else {<br>            child.<em>y </em>= dependency.<em>y </em>- (child.<em>height </em>+ margin)<br>        }<br>        return false<br>    }<br>}</pre><p>Quite simple, isn’t it ?️️ 👯‍♀️ 🕺🏻 👯‍♀️</p><p>And here’s how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*9eWg2lo5XYAAjescH6_aOw.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45c37c43c1ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/coordinating-floating-action-button-along-bottom-sheet-45c37c43c1ef">Coordinating floating action button along Bottom Sheet</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Room Jurney #1: Complex model storing (DB relations)]]></title>
            <link>https://medium.com/vattenfall-tech/android-room-jurney-1-complex-model-storing-db-relations-98599bb418a6?source=rss-e95fb12fae5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/98599bb418a6</guid>
            <category><![CDATA[android-room]]></category>
            <category><![CDATA[android-persistence]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adam Styrc]]></dc:creator>
            <pubDate>Thu, 12 Dec 2019 18:13:47 GMT</pubDate>
            <atom:updated>2019-12-12T18:15:45.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Room Journey #1: Complex model storing (DB relations)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luK9YOWtd93JLXZxkvoiMg.png" /></figure><p>There are 3 ways of saving persistent data on Android:</p><ul><li>Shared Preferences</li><li>File</li><li>Database</li></ul><p>In many cases saving to a <strong>Shared Preferences</strong> is sufficient. You can not only keep the primitive values like <em>Integer</em>, <em>Boolean</em> and <em>String</em> but also serialize your data objects to a JSON and keep them as a String. Then, when relaunching the app, you could use Gson().fromJson() to restore your data.</p><p>In the InCharge app, this solution was used for a long time. It’s very simple, clear, you find out what is happening easily. There are no problems… until you reach the Shared Preferences <strong>limitations</strong> 🙄🙄 which are:</p><p><a href="https://stackoverflow.com/a/8517309/1845420">max String length = </a><a href="https://stackoverflow.com/a/8517309/1845420">Integer.MAX_VALUE (=2147483647)</a></p><p><a href="https://stackoverflow.com/a/43080588/1845420">some people claim it’s </a><a href="https://stackoverflow.com/a/43080588/1845420">1.42 MB (1428.51KB)</a></p><p>per key.</p><p>At some point, we started to face this limitation. We store long lists of complex objects and these JSONs started to swell. How to<strong> transition to a database</strong>? Here we go!</p><h3>Why Android Room?</h3><p>There are plenty of approaches to database topics on Android, from pure SQLite through Content Providers, many ORM like e.g. GreenDao, to even non-SQLite DBs like Realm. I’ve decided on yet youngest tool which is <strong>Android Room</strong>. My motivation to use Room was:</p><ul><li>the API looks clearer than all others ORM I’ve used in the past</li><li>there is <strong>advanced</strong> <strong>support</strong> <strong>of</strong> <strong>relationships</strong> between models</li><li>autoboxing data into <strong>LiveData</strong> which is very comfortable to use on a UI</li><li>support of <strong>RxJava</strong></li><li>and finally, it’s a most modern tool, made &amp; recommended by Google</li></ul><p>Now I’d like to share the challenges I faced while implementing Room and how I coped with them.</p><h3>Complex models challenge</h3><p>The complex model I mention at the very beginning of this article that started to grow is a list of user’s electric car chargings. The model of the charging has lots of data and the charging takes place every few days if not every day. That’s the reason the data’s been swelling up.</p><p>There are domain models that are used across the whole project, but the way they exist is not adjusted for Room entities. Thus, firstly I had to create corresponding database models and here I faced 2 problems:</p><ol><li><strong>Relations</strong> — model of charging session has a reference to charging station where it occurred and the charging station has a relation to charging points. Moreover charging session points out on which charging point the charging took place. This is how simplified data models related to <strong>ChargingSession</strong> looks like:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxZSVcmR-vVf34NuJEfs6A.png" /></figure><p>So the question emerges — how does Room handle these <strong><em>relations </em></strong><em>mapping</em><strong><em>?</em></strong></p><p>2. Models consists of <strong>enum fields</strong> that I’d like to keep for data integrity</p><h3>Relations mapping</h3><p>In this article, I’m going to skip full Room implementation as there are a lot of great articles on medium or just the official code lab:</p><p><a href="https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#0">https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#0</a></p><p>and focus on <em>Entities. </em>Starting from the bottom — <strong>ChargingPoint, </strong>we need to map it to a database entity <strong>DatabaseChargingPoint </strong>(some people might name it <em>ChargingPointDto</em> or <em>ChargingPointDbo</em>).</p><p>This will be the structure of data stored and read in a Database.</p><pre>@Entity(tableName = &quot;charging_point&quot;)<br>data class DatabaseChargingPoint(<br>        @PrimaryKey var id: Long = -1,<br>        @ForeignKey(<br>                entity = DatabaseChargingStation::class,<br>                parentColumns = [&quot;id&quot;],<br>                childColumns = [&quot;chargingStationId&quot;],<br>                onDelete = ForeignKey.<em>CASCADE</em>)<br>        var chargingStationId: Long? = null,<br>        var power: Watts = 0,<br>        var status: String = &quot;&quot;<br>) {<br><br>    companion object {<br>        fun fromDomainObject(chargingPoint: ChargingPoint, chargingStationId: String) =<br>                DatabaseChargingPoint(<br>                        id = chargingPoint.id!!,<br>                        chargingStationId = chargingStationId<br>                        status = chargingPoint.status,<br>                        power = chargingPoint.power<br>                )<br>    }<br><br>    fun toDomainObject() =<br>            ChargingPoint(<br>                    id = id,<br>                    power = power,<br>                    status = status<br>            )<br>}</pre><p>We connected <em>DatabaseChargingPoint</em> with a <em>DatabaseChargingSession</em> with @ForeignKey annotation so whenever a database object of charging station gets deleted, our charging points will be deleted as well.</p><p>The default values of parameters are recommended to omit the default constructor required by @Entity annotation.</p><p>I also added 2 methods for mapping from domain object ChargingPoint to DatabaseChargingPoint for storing in the database (<em>fromDomainObject())</em>, and in opposite direction for reading (<em>toDomainObject()</em>).</p><p>Let’s continue up the model tree:</p><pre>@Entity(tableName = &quot;charging_station&quot;)<br>data class DatabaseChargingStation(<br>        @PrimaryKey var id: Long = -1,<br>        @Embedded var location: Location = Location()<br>) {<br><br><br>    companion object {<br>        fun fromDomainObject(chargingStation: ChargingStation) =<br>                DatabaseChargingStation(<br>                        id = chargingStation.id,<br>                        location = Location.fromDomainObject(chargingStation.location)<br>                )<br>    }<br><br>    fun toDomainObject() =<br>            ChargingStation(<br>                    id = id,<br>                    location = location.toDomainObject(),<br>            )<br>}</pre><pre>data class Location(<br>        var address: String? = null,<br>        var latitude: Double? = null,<br>        var longitude: Double? = null<br>) {<br><br>    companion object {<br>        fun fromDomainObject(location: ChargingStation.Location) = Location(<br>                address = location.address,<br>                latitude = location.coordinates?.latitude,<br>                longitude = location.coordinates?.longitude)<br>    }<br><br>    fun toDomainObject(): ChargingStation.Location {<br>        var coordinates: Coordinates? = null<br>        if (latitude != null &amp;&amp; longitude != null) {<br>            coordinates = Coordinates(latitude!!, longitude!!)<br>        }<br><br>        return ChargingStation.Location(<br>                address = address,<br>                coordinates = coordinates<br>        )<br>    }<br>}</pre><p>DatabaseChargingStation creation was quite similar but @Embedded annotation was used to flatten the encapsulated structure on a database table. The address, latitude, and longitude will be stored on the same level as e.g. is of the charging station.</p><p>And last <em>Entity</em> to model:</p><pre>@Entity(tableName = &quot;charging_session&quot;)<br>data class DatabaseChargingSession (<br>        @PrimaryKey var id: Long = -1,<br>        var startDate: Date? = null,<br>        var endDate: Date? = null,<br>        var chargingPointId: String? = null,<br>        var chargingStationId: Long? = null,<br>) {<br><br>    companion object {<br>        fun fromDomainObject(chargingSession: ChargingSession) =<br>                DatabaseChargingSession(<br>                        id = chargingSession.id!!,<br>                        startDate = chargingSession.startDate,<br>                        endDate = chargingSession.endDate,<br>                        chargingPointId = chargingSession.chargingPoint?.id,<br>                        chargingStationId = chargingSession.chargingStation?.id<br>                )<br>    }<br>}</pre><p>Now it’s time to add a <strong>Dao</strong> classes. First thought would be to implement DAOs in a standard way:</p><pre>@Dao<br>interface ChargingPointDao {<br><br>    @Insert(onConflict = OnConflictStrategy.<em>REPLACE</em>)<br>    fun addChargingPoint(chargingPoint: DatabaseChargingPoint)</pre><pre>    @Query(&quot;SELECT * FROM charging_point WHERE id=:id}<br>    fun getChargingPoint(id: Long): DatabaseChargingPoint</pre><pre>@Dao<br>interface ChargingStationsDao {<br>    //like above<br>}</pre><pre>@Dao<br>interface ChargingSessionsDao {<br><br>    @Transaction<br>    @Query(&quot;SELECT * FROM charging_session ORDER BY id DESC&quot;)<br>    fun getChargingSessions()<br>            : List&lt;DatabaseChargingSession&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.<em>REPLACE</em>)<br>    fun addChargingSession(chargingSession: DatabaseChargingSession)<br>}</pre><p>All DAOs looks normal, like in Android Room Codelabs, but will it work the way we wanted? The answer is it depends 🙃 When building the final domain object of charging sessions we’d have to manually use all the DAOs and pull required DatabaseChargingStation and DatabaseChargingPoint… but this would be ugly. What we could actually do is to force Room to work for us!</p><pre>data class DatabaseChargingStationDetails(<br>        @Embedded var databaseChargingStation: DatabaseChargingStation,<br>        @Relation(<br>                parentColumn = &quot;id&quot;,<br>                entityColumn = &quot;chargingStationId&quot;,<br>                entity = DatabaseChargingPoint::class<br>        )<br>        var databaseChargingPoints: List&lt;DatabaseChargingPoint&gt;<br>) {<br>        fun toDomainObject(): ChargingStation? {<br>                val chargingStation = databaseChargingStation.toDto()<br>                chargingStation.chargingPoints = databaseChargingPoints.<em>map </em><strong>{ it</strong>.toDto() <strong>}<br>                </strong>return chargingStation<br>        }<br>}</pre><pre>data class DatabaseChargingSessionDetails(<br>        @Embedded var chargingSessionModel: DatabaseChargingSession,<br>        @Relation(<br>                parentColumn = &quot;chargingPointId&quot;,<br>                entityColumn = &quot;id&quot;,<br>                entity = DatabaseChargingPoint::class)<br>        var databaseChargingPoint: DatabaseChargingPoint? = null,<br>        @Relation(<br>                parentColumn = &quot;chargingStationId&quot;,<br>                entityColumn = &quot;id&quot;,<br>                entity = DatabaseChargingStation::class)<br>        var databaseChargingStation: DatabaseChargingStationDetails? = null<br>) {<br>        fun toDomainObject() =<br>                chargingSessionModel.toDomainObject().<em>apply </em><strong>{<br>                        </strong>chargingPoint = databaseChargingPoint?.toDomainObject()<br>                        chargingStation = databaseChargingStation?.toDomainObject()<br>                <strong>}<br></strong>}</pre><p>and now our DAOs will be even shorter and already pull charging sessions objects that contain charging point and charging station that contains it’s all charging points :) All the magic is obtained with @Relation annotation.</p><pre>@Dao<br>interface ChargingPointDao {<br><br>    @Insert(onConflict = OnConflictStrategy.<em>REPLACE</em>)<br>    fun addChargingPoint(chargingPoint: DatabaseChargingPoint)<br>}</pre><pre>@Dao<br>interface ChargingStationsDao {<br><br>    @Insert(onConflict = OnConflictStrategy.<em>REPLACE</em>)<br>    fun addChargingStation(databaseChargingStation: DatabaseChargingStation)<br>}</pre><pre>@Dao<br>interface ChargingSessionsDao {<br><br>    @Transaction<br>    @Query(&quot;SELECT * FROM charging_session ORDER BY id DESC&quot;)<br>    fun getChargingSessionsWithChargingStationAndPoint()<br>            : List&lt;DatabaseChargingSessionDetails&gt;<br><br>    @Insert(onConflict = OnConflictStrategy.<em>REPLACE</em>)<br>    fun addChargingSession(chargingSession: DatabaseChargingSession)<br>}</pre><p>In addition, we can replace the returned type from List&lt;&gt; to LiveData&lt;List&lt;&gt;&gt; so getting the data will be async!</p><pre>@Transaction<br>@Query(&quot;SELECT * FROM charging_session ORDER BY id DESC&quot;)<br>fun getChargingSessionsWithChargingStationAndPoint()<br>        : LiveData&lt;List&lt;DatabaseChargingSessionDetails&gt;&gt;</pre><h4>Transforming to domain objects</h4><p>Wrapping data access in a layer is generally a good idea. We could access domain models from a database source via some <strong>Repository </strong>class that could have e.g. <em>fetch()</em> method. From now on we could forget that we have the database models:</p><pre>interface ChargingSessionsRepository {<br><br>    fun fetchChargingSessions(): LiveData&lt;List&lt;ChargingSession&gt;&gt;<br><br>    fun saveChargingSessions(chargingSessions: List&lt;ChargingSession&gt;)<br>}</pre><pre>class DatabaseChargingSessionsRepository internal constructor(<br>        private val database: InchargeRoomDatabase<br>) : ChargingSessionsRepository {<br><br>    override fun fetchChargingSessions() = Transformations.map(<br>            database.chargingSessionsDao()<br>                    .getChargingSessionsWithChargingStationAndPoint()<br>    ) <strong>{ </strong>databaseChargingSession <strong>-&gt;<br>        </strong>databaseChargingSession.<em>map </em><strong>{<br>            it</strong>.chargingSessionModel.toDomainObject()<br>        <strong>}<br>    }</strong></pre><p><em>Transformations.map()</em> is used in order to transition from database to domain models 🤓</p><h3>Saving the data</h3><p>We did some nice work obtaining data from the database but so far it’s empty and we’ve not put anything yet 🙊</p><p>Here is the missing method of DatabaseChargingSessionsRepository class.</p><pre>override fun saveChargingSessions(chargingSessions: List&lt;ChargingSession&gt;) {<br>    database.runInTransaction <strong>{<br>        </strong>chargingSessions.<em>forEach </em><strong>{<br>            </strong>try {<br>                val chargingSessionModel = DatabaseChargingSession.fromDomainObject(<strong>it</strong>)<br><br>                <strong>it</strong>.chargingStation?.<em>let </em><strong>{ </strong>chargingStation <strong>-&gt;<br>                    </strong>database.chargingStationsDao().addChargingStation(<br>                            DatabaseChargingStation.fromDto(chargingStation)<br>                    )<br><br>                    chargingStation.chargingPoints.<em>forEach </em><strong>{ </strong>chargingPoint <strong>-&gt;<br>                        </strong>database.chargingPointsDao().addChargingPoint(<br>                                DatabaseChargingPoint.fromDto(chargingPoint, chargingStation.id)<br>                        )<br><br>                        chargingPoint.connectors.<em>forEach </em><strong>{ </strong>connector <strong>-&gt;<br>                            </strong>database.chargingConnectorDao().addChargingConnector(<br>                                    DatabaseChargingConnector.fromDto(connector, chargingPoint.id)<br>                            )<br>                        <strong>}<br>                    }<br>                }<br><br>                </strong>database.chargingSessionsDao().addChargingSession(chargingSessionModel)<br>            } catch (e: Exception) {<br>                e.printStackTrace()<br>            }<br>        <strong>}<br>    }<br></strong>}</pre><p>This is the point where I reached. Probably I will next play with wrapping the saving process into RxJava and throwing it on a separate thread. 🤔</p><h3>Conclusions</h3><p>Maintaining complex models and relations between them is definitely possible with <strong>Android Room</strong>. TBH our models are way more complicated as there are more things embedded and we have nested relations in relations. For clarity and brevity, I simplified it — however, the way to achieve it remains the same.😊</p><p>Transitioning to from Shared Preferences to Android Room took me 2 days and the first implementation worked surprising great from the scratch. Don’t fear to start using it! 🤘🤘🤘</p><p><strong>Recommended links:</strong></p><p><a href="https://medium.com/swlh/android-room-persistence-library-relations-in-a-nested-one-to-many-relationship-f2fe21c9e1ad">https://medium.com/swlh/android-room-persistence-library-relations-in-a-nested-one-to-many-relationship-f2fe21c9e1ad</a></p><p><a href="https://android.jlelse.eu/android-architecture-components-room-relationships-bf473510c14a">Android Architecture Components: Room — Relationships</a></p><p><a href="https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#0">https://codelabs.developers.google.com/codelabs/android-room-with-a-view-kotlin/#0</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98599bb418a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/android-room-jurney-1-complex-model-storing-db-relations-98599bb418a6">Android Room Jurney #1: Complex model storing (DB relations)</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android: Spinner customizations]]></title>
            <link>https://medium.com/vattenfall-tech/android-spinner-customizations-8b4980fb0ee3?source=rss-e95fb12fae5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b4980fb0ee3</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[spinner]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Adam Styrc]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 14:10:35 GMT</pubDate>
            <atom:updated>2022-01-14T10:12:09.963Z</atom:updated>
            <content:encoded><![CDATA[<p>Implement Android dropdown just the way you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHsKYI6FAtc4NZJH5x4xoA.jpeg" /></figure><h3>Custom Spinner</h3><p>In this article, I’ll describe two ways to achieve custom spinner for country selection that I had to implement at InCharge app. We officially support now 4 countries with charging stations, each country has specific legal rules, terms &amp; conditions, etc.</p><p>The screen mockups I received from our designer were exactly these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*no0UBNxTtnRr159SSl4cng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGPYRTWFISC6G2Lo9KfnTw.png" /><figcaption>Spinner Design ||| Spinner Design — dropdown</figcaption></figure><p>So the design for selection was not looking like a <a href="https://developer.android.com/guide/topics/ui/controls/spinner">default Android Spinner</a> as it had a header included when going to dropdown mode. Is it possible to implement using <a href="https://developer.android.com/reference/android/widget/Spinner.html">Spinner Widget</a>? Let’s see.</p><h3>Adjusting the Spinner widget</h3><p>OK, so let’s begin with implementing the layout:</p><blockquote>item_country.xml</blockquote><pre>&lt;RelativeLayout <br>	xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>	xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>	android:layout_width=&quot;match_parent&quot;<br>	android:layout_height=&quot;@dimen/country_item_height&quot;<br>	android:paddingLeft=&quot;@dimen/general_margin&quot;<br>	android:paddingRight=&quot;@dimen/general_margin&quot;&gt;<br><br>	&lt;ImageView<br>		android:id=&quot;@+id/ivCountry&quot;<br>		android:layout_width=&quot;32dp&quot;<br>		android:layout_height=&quot;32dp&quot;<br>		android:layout_alignParentLeft=&quot;true&quot;<br>		android:layout_centerVertical=&quot;true&quot;<br>		tools:src=&quot;@drawable/ic_united_kingdom&quot; /&gt;<br><br>	&lt;TextView<br>		android:id=&quot;@+id/tvCountry&quot;<br>		android:layout_width=&quot;wrap_content&quot;<br>		android:layout_height=&quot;wrap_content&quot;<br>		android:layout_marginLeft=&quot;@dimen/general_margin&quot;<br>		android:layout_toRightOf=&quot;@id/ivCountry&quot;<br>		android:layout_centerVertical=&quot;true&quot;<br>		android:textColor=&quot;@color/incharge_dark_grey&quot;<br>		android:textSize=&quot;18sp&quot;<br>		tools:text=&quot;United Kingdom&quot;/&gt;<br><br>	&lt;ImageView<br>		android:layout_width=&quot;16dp&quot;<br>		android:layout_height=&quot;16dp&quot;<br>		android:layout_alignParentRight=&quot;true&quot;<br>		android:layout_centerVertical=&quot;true&quot;<br>		android:src=&quot;@drawable/arrow_down_grey&quot;<br>		/&gt;<br>&lt;/RelativeLayout&gt;</pre><p>And add a Spinner widget:</p><pre>&lt;Spinner<br>            android:id=&quot;@+id/sCountry&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>			...<br>            android:background=&quot;@drawable/blue_outline&quot;<br>android:popupBackground=&quot;@drawable/blue_outline_white_background&quot;<br>            android:spinnerMode=&quot;dropdown&quot;<br>            tools:listitem=&quot;@layout/item_country&quot;<br>            /&gt;</pre><blockquote>blue_outline.xml</blockquote><pre>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;stroke android:color=&quot;@color/incharge_blue&quot; android:width=&quot;1dp&quot;/&gt;<br>    &lt;corners android:radius=&quot;@dimen/button_round_radius&quot;/&gt;<br>&lt;/shape&gt;</pre><p>In this way, we’ve just built a Spinner widget on our UI. Thanks to tools:listitem=&quot;@layout/item_country&quot; we can see in Android Studio Designer how the Spinner will look like and adjust paddings/margins properly :)</p><p>With property android:background we can add a blue outline when Spinner is in the selected state and with android:popupBackground the background of dropdown view - easy so far.</p><h3>Adapter</h3><p>The magic of adding a header will be done in our <strong>CountryAdapter</strong> class:</p><blockquote>CountryAdapter.kt</blockquote><pre>class CountryAdapter(<br>        context: Context<br>) : ArrayAdapter&lt;OperatedCountry&gt;(context, 0, OperatedCountry.values()) {</pre><pre>    val layoutInflater: LayoutInflater = LayoutInflater.from(context)</pre><pre>    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {<br>        val view: View<br>        if (convertView == null) {<br>            view = layoutInflater.inflate(R.layout.item_country, parent, false)<br>        } else {<br>            view = convertView<br>        }</pre><pre>        getItem(position)?.let { country -&gt;<br>            setItemForCountry(view, country)</pre><pre>        }</pre><pre>        return view</pre><pre>    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {<br>        val view: View</pre><pre>        if (position == 0) {<br>            view = layoutInflater.inflate(R.layout.header_country, parent, false)<br>            view.setOnClickListener {<br>                val root = parent.rootView<br>                root.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK))<br>                root.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK))<br>            }<br>        } else {<br>            view = layoutInflater.inflate(R.layout.item_country_dropdown, parent, false)</pre><pre>            getItem(position)?.let { country -&gt;<br>                setItemForCountry(view, country)<br>            }<br>        }</pre><pre>        return view<br>    }</pre><pre>    override fun getItem(position: Int): OperatedCountry? {<br>        if (position == 0) {<br>            return null<br>        }</pre><pre>        return super.getItem(position - 1)<br>    }</pre><pre>    override fun getCount() = super.getCount() + 1</pre><pre>    override fun isEnabled(position: Int) = position != 0</pre><pre>    private fun setItemForCountry(view: View, country: OperatedCountry) {<br>        val tvCountry = view.findViewById&lt;TextView&gt;(R.id.tvCountry)<br>        val ivCountry = view.findViewById&lt;ImageView&gt;(R.id.ivCountry)</pre><pre>        val countryName = Locale(&quot;&quot;, country.countryCode).displayCountry<br>        tvCountry.text = countryName<br>        ivCountry.setBackgroundResource(country.icon)<br>    }</pre><p>And an enum for supported countries is realized like this:</p><blockquote>OperatedCountry.kt</blockquote><pre>enum class OperatedCountry(val countryCode: String, val icon: Int) {<br>    UNITED_KINGDOM(&quot;UK&quot;, R.drawable.ic_united_kingdom),<br>    NETHERLANDS(&quot;NL&quot;, R.drawable.ic_netherlands),<br>    GERMANY(&quot;DE&quot;, R.drawable.ic_germany),<br>    SWEDEN(&quot;SE&quot;, R.drawable.ic_sweden),<br>}</pre><p>There are several parts that need to be explained…</p><p>Firstly, let’s see that getView() method will build UI when Spinner is in idle state and getDropDownView() will build particular items when Spinner dropdown gets opened. This is a place where we need to expect position == 0 to build a header with <em>&quot;Select option&quot;</em>.</p><p>Unfortunately, there is <strong>no Spinner public method to programmatically close the dropdown</strong>. So how could we close it, when the header item gets clicked? There are couples of hacks to overcome this problem and here is one of them:</p><pre>val root = parent.rootView<br>root.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK))<br>root.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK))</pre><p>so we pretend as if the <strong>BACK</strong> button got clicked. Yeah, hacky…</p><p>Also to prevent selections for header view and not trigger its Spinner behavior we override isEnabled method to return false in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*k4O4OU6-k0LT3GuNY7Aekg.gif" /><figcaption>Spinner after adjustments</figcaption></figure><h3>Drawbacks</h3><p>So we were able to implement the expected design somehow. But is it an ultimate solution? We had to use <strong>a hack with closing dropdown</strong> and make code dirty. Also, what if the designer suddenly changes his mind and wants to apply some animation for example arrow rotation? Built-in popup has entered animation which might interrupt these animations.</p><p>Technically android:popupAnimationStyle is applicable to Spinner style but it&#39;s from <em>SDK 24</em>, quite high, right?</p><p>Would there be another solution?</p><h3>Custom Spinner implementation</h3><p>If we look into the Android source code of Spinner, we will see that underneath a PopupWindow is used to render the dropdown. Implementing classes are private so we cannot use them. But how much work could that be to make it yourself? Let&#39;s try!</p><p>Let’s replace Spinner widget with anything else that could include <strong>item_country.xml</strong> Now, in setOnClickListener { ... } part (trying to override OnClickListener on Spinner would result in RuntimeException).</p><pre>vCountry.setOnClickListener {<br>	popupWindow?.dismiss()</pre><pre>	if (popupWindow == null) {<br>		provideCountryPopupWindow(it)<br>	}</pre><pre>	popupWindow!!.showAsDropDown(it, 0, -it.height)<br>}</pre><pre>private fun provideCountryPopupWindow(it: View) {<br>        popupWindow = PopupWindow(it.width, ViewGroup.LayoutParams.WRAP_CONTENT)<br>                .apply {<br>                    val backgroundDrawable = activity!!.getDrawable(<br>                            R.drawable.blue_outline_white_background)<br>                            .apply {  }<br>                    setBackgroundDrawable(backgroundDrawable)<br>                    isOutsideTouchable = true</pre><pre>                    val listView = layoutInflater.inflate(<br>                            R.layout.layout_country_dropdown,<br>                            null,<br>                            false) as ListView<br>                    listView.adapter = countryAdapter<br>                    listView.setOnItemClickListener { _, _, position, _ -&gt;<br>                        val selectedCountry = countryAdapter.getItem(position)!!<br>                        viewModel.setLegalCountry(selectedCountry)</pre><pre>                        popupWindow?.dismiss()<br>                    }<br>                    contentView = listView<br>                }<br>    }</pre><p>where</p><blockquote>layout_country_dropdown.xml</blockquote><pre>&lt;ListView<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/lvCountries&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:divider=&quot;@null&quot;<br>    tools:listheader=&quot;@layout/header_country&quot; /&gt;</pre><p>So here we handle the dropdown view by ourselves. We have full control of its UI! I chose ListView, could be anything else! All rendered by <em>layout_country_dropdown.xml</em>.</p><p>Note that you can use the very same CountryAdapter but rename the getDropDownView() method to getView(), and get rid of existing getView().</p><p>Thus… Not a lot of work was required to transition 8) That’s what we all love. This solution seems way cleaner, with no dirty hacks — just add popupWindow?.dismiss() when the header clicked. How does it look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*7u988bofZwjUV9KFdZ8XCw.gif" /><figcaption>Spinner — own implementation with PopupWindow</figcaption></figure><p>What about animation management? It’s easy. We could set custom animation for a PopupWindow or simply disable it with a parameter:</p><pre>PopupWindow.animationStyle = 0 // or R.style.YourCountryPopupAnimation</pre><p>then in CountryAdapter on header item creating add something like:</p><pre>view.findViewById&lt;ImageView&gt;(R.id.ivArrow)<br>                    .animate()<br>                    .rotation(180f)<br>                    .setDuration(200)<br>                    .start()</pre><p>And the result is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*3cvRzgD1i5_wB1DQIhLnfQ.gif" /><figcaption>PopupWindow — animations</figcaption></figure><p>Try writing rotation animation on dropdown close by yourself ;)</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b4980fb0ee3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/vattenfall-tech/android-spinner-customizations-8b4980fb0ee3">Android: Spinner customizations</a> was originally published in <a href="https://medium.com/vattenfall-tech">TechTalks@Vattenfall</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Dynamic Shortcuts — passing extras]]></title>
            <link>https://medium.com/@styrc.adam/android-dynamic-shortcuts-passing-extras-64db534621c1?source=rss-e95fb12fae5e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64db534621c1</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Adam Styrc]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 11:09:13 GMT</pubDate>
            <atom:updated>2018-09-13T11:18:43.878Z</atom:updated>
            <content:encoded><![CDATA[<p>The use case of this article is Incharge app where I would like to create few dynamic shortcuts. As the app serves to show charging stations on map for electric cars users, I would like to enable shortcuts to Android 7.1+ users to their favorites list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*erFzhpS0QHWjr0dZTM8Kaw.png" /><figcaption>Favorite stations addresses (shortcuts)</figcaption></figure><blockquote>Emulator Pixel 2 (API 26, Oreo)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*9MA_Lp-tTGS61sAaUpHs2w.png" /><figcaption>Charging Station Details Screen</figcaption></figure><p>So let’s begin with making an easy access to ShortcutManager by adding an extension function (e.g. ContextExtensions.kt file)</p><pre>@RequiresApi(Build.VERSION_CODES.<em>M</em>)<br>fun Context.getShortcutManager() = this.getSystemService&lt;ShortcutManager&gt;(ShortcutManager::class.<em>java</em>)</pre><p>Now, whenever favorite lists changes let’s set the dynamic shortcuts by applying below method:</p><pre>@RequiresApi(Build.VERSION_CODES.<em>M</em>)<br>private fun setFavoriteStationsShortcuts(favoriteStations: List&lt;ChargingStation&gt;) {<br>   val shortcutManager = applicationContext.<em>getShortcutManager</em>()<br><br>   val shortcuts = ArrayList&lt;ShortcutInfo&gt;()<br>   favoriteStations.<em>forEach </em><strong>{<br>      </strong>val intent = Intent(&quot;INCHARGE_OPEN_STATION_ACTION&quot;)<br><strong>      intent.putExtra(&quot;chargingStationId&quot;, chargingStation.id)<br></strong><br>      val shortcut = ShortcutInfo.Builder(applicationContext, <strong>it</strong>.id)<br>                    .setShortLabel(<strong>it</strong>.getAddress())<br>                    .setLongLabel(<strong>it</strong>.getAddressCity())<br>.setIcon(Icon.createWithResource(applicationContext, R.drawable.<em>marker_icon_green</em>))<br>                    .setIntent(intent)<br>                    .build()<br>      shortcuts.add(shortcut)<br>   <strong>}</strong></pre><pre><strong>   </strong>shortcutManager.setDynamicShortcuts(shortcuts)<br>}</pre><p>The outcome is as expected, after adding a station to favorite, the shortcut is created and visible after app launcher long click:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*z0nfI-5iRwS8SeaOoLp28A.png" /><figcaption>Shortcut appears after long click</figcaption></figure><p><strong>However </strong>what turns out — <strong>an extra in intent is not passed! </strong>I’m not sure what is the reason, but only the action was delivered, the extra bundle is empty.</p><p>I tried couple of different solutions when prepating the Intent with extra, like change the action to Intent.<em>ACTION_VIEW </em>or set the component name to my Activity but nothing helped, the extra is simply not there.</p><h3>URI approach</h3><p>I believe an extra missing is simply a bug so I decided to change the approach of creating the intent. I decided that the Activity that should be opened when a shortcut is clicked will listen to an uri invocation action. So the activity in manifest was changed with:</p><pre>&lt;intent-filter&gt;<br>    &lt;data android:scheme=&quot;incharge&quot; android:host=&quot;charging_station&quot; /&gt;<br>    &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>    &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>thus evenever the uri with <em>incharge://charging_station</em> will occur. Now the intent in shortcut definition is switched to:</p><pre>val uri = Uri.Builder().scheme(&quot;incharge&quot;)<br>        .authority(&quot;charging_station&quot;)<br>        .appendQueryParameter(&quot;id&quot;, chargingStation.id.toString())<br>        .build()<br>val intent = Intent(Intent.<em>ACTION_VIEW</em>, uri)</pre><p>And finally let’s read it when the Activity gets triggered:</p><pre>when(intent.<em>action</em>) {<br>   ...<br>   Intent.<em>ACTION_VIEW </em>-&gt; {<br>      if (intent.<em>data </em>!= null) {<br>         val uri = Uri.parse(intent.<em>dataString</em>)<br>         val id = uri.getQueryParameter(&quot;id&quot;).<em>toLong</em>()<br>         openChargingStationDetailsById(id)<br>      }<br>   }<br>}<br></pre><p>Now everything works fine :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64db534621c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>