<?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 Dharma Sai Seerapu on Medium]]></title>
        <description><![CDATA[Stories by Dharma Sai Seerapu on Medium]]></description>
        <link>https://medium.com/@dharmasai.seerapu?source=rss-bd4c0a844456------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aRmkO_d-EVia81dEhJmJ3g.jpeg</url>
            <title>Stories by Dharma Sai Seerapu on Medium</title>
            <link>https://medium.com/@dharmasai.seerapu?source=rss-bd4c0a844456------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:37:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dharmasai.seerapu/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[java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase]]></title>
            <link>https://medium.com/@dharmasai.seerapu/this-issue-has-happened-for-one-of-the-production-apps-in-the-play-store-on-16th-sept-2019-takes-2-1c2ea69a629e?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2ea69a629e</guid>
            <category><![CDATA[room]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[migration]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Wed, 18 Sep 2019 14:05:37 GMT</pubDate>
            <atom:updated>2019-09-22T12:13:50.337Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: (database path)</strong></p><pre>java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: (database path)</pre><pre>Database Migration Issues</pre><p>This issue has happened for one of the production apps in the play store on <strong>16th Sept 2019(Takes 2 sleepless nights to Fix it)</strong>.</p><p>From the above statement, I have understood that <strong>I closed SQLiteDatabase somewhere. So started investigating it in the code</strong>.</p><h4>My Investigations are :</h4><ol><li>I rechecked all the database related code multiple times. But, everything is fine. <strong>Ahhh then, what is the exact problem? : Half-day wasted</strong></li><li>So, I started googling for the solution. Search Gaint provided all the possible search results. I read Medium blogs, conversations in the Github issues, answers for the Stack Overflow Questions and tried every possible way that I can do. : <strong>Full-day wasted</strong></li></ol><p>I read Following Github Issues &amp; Medium Blogs</p><ul><li><a href="https://github.com/googlesamples/android-architecture-components/issues/276">https://github.com/googlesamples/android-architecture-components/issues/276</a></li><li><a href="https://android.jlelse.eu/android-architecture-components-room-migration-1a269e1aeef7">https://android.jlelse.eu/android-architecture-components-room-migration-1a269e1aeef7</a></li><li><a href="https://proandroiddev.com/migrating-to-room-in-the-real-world-part-3-152e2307c934">https://proandroiddev.com/migrating-to-room-in-the-real-world-part-3-152e2307c934</a></li><li><a href="https://medium.com/@manuelvicnt/android-room-upgrading-alpha-versions-needs-a-migration-with-kotlin-or-nonnull-7a2d140f05b9">https://medium.com/@manuelvicnt/android-room-upgrading-alpha-versions-needs-a-migration-with-kotlin-or-nonnull-7a2d140f05b9</a></li><li><a href="https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975">https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975</a></li></ul><p>With the updated knowledge(After reading the blogs and conversations) I rechecked and started doing trial &amp; error methods into the code</p><ul><li><strong>Accessing the database on the Main Thread</strong>. (It&#39;s important that all the database transactions should happen only on a background thread) : <strong>Nothing wrong here</strong></li><li><strong>Keep the database version unchanged</strong> (Looks like you’ve changed schema but forgot to update the version number. You can simply fix this by increasing the version number.)— <strong>App crashes</strong>: <strong>Nothing wrong here</strong></li></ul><pre>java.lang.IllegalStateException: Room cannot verify the data integrity</pre><ul><li><strong>Version increased, but no migration provided </strong>(Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.)— app crashes</li></ul><pre>java.lang.IllegalStateException: A migration from 1 to 2 is necessary. Please provide a Migration in the builder or call fallbackToDestructiveMigration in the builder in which case Room will re-create all of the tables.</pre><ul><li>fallbackToDestructiveMigration() enabled and addMigrations() added — <strong>It simply clears the database</strong>. Ohh no... It&#39;s too dangerous. : <strong>Nothing wrong here</strong></li></ul><blockquote>Most of the Migration issues will solve by <strong>forgetting one of the above 4 points</strong>. If non of the above trails works, Yes… Come and join me.. You also have the same problem</blockquote><blockquote>None of the above trails gave me a hint to the problem. So, I came to where I was started : <strong>One and Half day wasted</strong></blockquote><blockquote><strong>Customers are complaining and their positive reviews (5*) turned into 1* review in an hour. Oh, noo...</strong></blockquote><blockquote><strong>I took a deep breath and thinking deeply for the solutions in a calm environment.</strong></blockquote><p>I have two questions in my mind.</p><ol><li>Am I investigating the problem in the right direction?</li><li>Does that above statement really give me a hint for the root cause of the problem?</li></ol><p>I started debugging the whole database code and their implementations hours and hours (<strong>Total 8 Hours</strong>). At last, I found the root cause of the problem :</p><h4>Root Cause for the Problem: indices’ names mismatch</h4><p>Some of the columns for our entities were used as SQL indexes, and Room expects that entity models correctly map to them, both in terms of name and respective column. Cupboard uses a naming convention that goes like, while Room uses index_${tableName}_${columnName}. We decided to keep the existing names and to simply have the Room map to them:</p><blockquote>What is this? <strong>The Problem statement and solution doesn’t match at all?</strong></blockquote><h3>Okay. What was the issue in my code?</h3><p>Deep look into the AttemptedTests table creation in the <strong>Migration Code</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*bVsGgxO056eA5qHMWVQ92Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*mVOo3oDAbPMrmMhjj-uRKA.png" /></figure><blockquote>What was the Fix here?</blockquote><blockquote><strong><em>Problem :</em></strong><em>created</em><strong><em> AttemptedTests</em></strong><em> table with column </em><strong><em>test_id </em></strong><em>without defining NOT NULL(Error is here only in the Left Pic)</em></blockquote><blockquote><strong><em>Fix : </em></strong><em>Just Added </em><strong><em>NOT NULL(in the right pic) to test_id column.</em></strong></blockquote><h3>Okay, How did you find this root cause?</h3><p>For Example If the RoomDatabase Extended Class Name AppDatabase.Java after the build, there will be a class Call AppDatabase_Impl.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSgGW3RX9Quoz1iViGBRvg.png" /></figure><p>In the above Pic, Please look into highlighted words</p><ul><li><strong>Expected:</strong> Room is Expecting the created_it column should define as notNull=true</li></ul><p>created_at=Column{name=&#39;created_at&#39;, type=&#39;INTEGER&#39;, affinity=&#39;3&#39;, <strong>notNull=true</strong>, primaryKeyPosition=0}</p><ul><li><strong>Found: </strong>But in the actual Table creation code in the Migration class has the created_it column is notNull=false</li></ul><p>created_at=Column{name=&#39;created_at&#39;, type=&#39;INTEGER&#39;, affinity=&#39;3&#39;, <strong>notNull=false</strong>, primaryKeyPosition=0}</p><p>By evaluating the values of <strong>Expected </strong>&amp; <strong>Found </strong>using <strong>Evaluate Expression, </strong>provides me the root cause of the problem and fixed it.</p><blockquote>This difference in the created_idcolumn we call it as <strong>indices’ names mismatch</strong></blockquote><p>My Suggestion for this problem :</p><ul><li>Check the SQLite queries multiple times.</li><li>If you think there is no problem with queries, Don’t worry check the same <strong>query Hundred times. Yes, a Hundred times. The problem is in the query only.</strong></li><li>Copy and paste the table creation code createOpenHelper methodfrom AppDatabase_Impl.java class</li></ul><p>Yahooooo… I have fixed the migration issue. I pushed updated APK into the play store. Working like a charm.</p><p>Customers are Happy… My Product Manager is Happy… This world is happy(Just Kidding :P)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2ea69a629e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are @JVMStatic, @JVMOverloads, and @JVMFields in Kotlin?]]></title>
            <link>https://medium.com/@dharmasai.seerapu/what-are-jvmstatic-jvmoverloads-and-jvmfields-in-kotlin-81a399dabe36?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/81a399dabe36</guid>
            <category><![CDATA[jvmoverloads]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jvmstatic]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[jvmfield]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 09:02:43 GMT</pubDate>
            <atom:updated>2019-09-10T09:06:38.871Z</atom:updated>
            <content:encoded><![CDATA[<p>The conversation between Junior and Lead Android Developer goes on like this…………</p><p><strong>Junior: </strong>Lead, Please explain why we are migrating our project to Kotlin from Java?</p><p><strong>Lead:</strong> Kotlin is best because we can write the same in a much precise way having a lesser number of lines of code (there are other benefits too)</p><p><strong>Junior:</strong> How? Any example?</p><p><strong>Lead: </strong>Let’s take the RetryWithDelay Pojo class in our project where it helps in retrying the same API(when it fails) with a given number of times and specified time gap in milliseconds.</p><p>Eg : Fetch Students List 3(<strong>maxRetriesCount</strong>) times and with time gap 2(<strong>retryDelayInMillis</strong>) seconds</p><ul><li>Java Pojo Class :</li></ul><pre><strong>public class RetryWithDelay</strong> {<br>    <br>    <strong>private int maxRetriesCount</strong>; // Number of Retries of same API<br>    <strong>private </strong>int <strong>retryDelayInMillis=2000</strong>; // TimeGap in retrying api</pre><pre>    public int getMaxRetriesCount() {<br><strong>        </strong>return<strong> </strong>maxRetriesCount<strong>;</strong><br><strong>    </strong>}</pre><pre>    public void<strong> </strong>setMaxRetriesCount(String maxRetriesCount) {<br>        this.maxRetriesCount = maxRetriesCount;<br>    }</pre><pre>    public int<strong> </strong>getRetryDelayInMillis() {<br>        return retryDelayInMillis<strong>;</strong><br>    }</pre><pre>    public void<strong> </strong>setRetryDelayInMillis(int retryDelayInMillis) {<br>        this.retryDelayInMillis<strong> </strong>= retryDelayInMillis;<br>    }<br>}</pre><ul><li>Kotlin Data Class :</li></ul><pre><strong>data class </strong>RetryWithDelay <strong>@JvmOverloads</strong> <strong>constructor</strong>(<strong>private val maxRetries</strong>: Int, <strong>private val retryDelayInMillis</strong>: Int = 2000)</pre><p>Junior: Awww... But Lead, we can’t migrate the entire project at once. So is there any way to use Kotlin &amp; Java in the same project?</p><p>Lead: As we know, Both Java and Kotlin are <strong>JVM dependent</strong>. We can use Kotlin code in our Java code. So, if we have migrated to Kotlin from Java then we can use our existing Java projects and make changes by using the Kotlin language. Another benefit of this <strong>interoperability</strong> is that if we are using Kotlin and at some time we are finding it difficult to implement something using Kotlin then we can implement the same using Java also.</p><p><strong>Junior:</strong> Okay. But how to achieve this?</p><p><strong>Lead:</strong> Okay here are some of the below annotations we use</p><h3>@JVMStatic:</h3><p>In Kotlin, We can make static methods for functions that are defined in some companion object or named object by using the <strong>@JvmStati</strong>c <strong>annotation</strong>. Let’s consider Retrofit Exception class For example</p><pre><strong>class </strong>RetrofitException{</pre><pre><strong>companion object </strong>{</pre><pre>    <strong>@JvmStatic</strong> <strong>fun </strong>networkError(exception: IOException): RetrofitException {<br>       //Body of Static function<br>    }<br></pre><pre>    <strong>fun </strong>apiError(@NonNull message: String): RetrofitException {<br>       //Body of Non-static function<br>    }</pre><pre>}<br>}</pre><p>Here, <strong>networkError()</strong> is a static function and <strong>apiError()</strong> is a non-static function.</p><p>So, to call the above methods in Java, write the below code:</p><pre>RetrofitException.networkError(); <em>// works fine</em><br>RetrofitException.apiError(); <em>// error: not a static method</em><br>RetrofitException.Companion.networkError(); <em>// instance method remains</em><br>RetrofitException.Companion.apiError(); <em>// the only way it works</em></pre><p>For named objects, the same procedure can be followed:</p><pre><strong>object </strong>RetrofitException{</pre><pre>    <strong>@JvmStatic</strong> <strong>fun </strong>networkError(exception: IOException): RetrofitException {<br>       //Body of Static function<br>    }<br></pre><pre>    <strong>fun </strong>apiError(@NonNull message: String): RetrofitException {<br>       //Body of Non-static function<br>    }<br>}</pre><p>So, to call the above methods in Java, write the below code:</p><pre>RetrofitException.networkError(); <strong><em>// works fine</em></strong><br>RetrofitException.apiError(); <strong><em>// error</em></strong><br>RetrofitException.INSTANCE.networkError(); <strong><em>// works, a call through the singleton instance</em></strong><br>RetrofitException.INSTANCE.apiError(); <strong><em>// works too</em></strong></pre><h3>@JvmOverloads</h3><p>Let’s create a class with some variables, few of them are initialized and few of them are not initialized. So, we use the above <strong>RetryWithDelay class. </strong>By default, we will take the <strong>retryDelayInMillis</strong> to the 2000(2Sec) if we don’t pass a value while making an object of the class.</p><pre><strong>class </strong>RetryWithDelay(<strong>private val maxRetriesCount</strong>: Int, <strong>private val retryDelayInMillis</strong>: Int = 2000)</pre><p>So, if we are calling from Kotlin, the following code will run with no error:</p><pre>val retryOne = RetryWithDelay(3)<br>val retryTwo = RetryWithDelay(3, 1000)</pre><p>But if we are calling the same from the Java then we have to pass all the parameters otherwise we will get some error:</p><pre>RetryWithDelay retryOne = <strong>new</strong> RetryWithDelay(3);<strong><em>//Here we are passing only one argument so we will encounter error</em></strong></pre><pre>RetryWithDelay retryTwo = <strong>new</strong> RetryWithDelay(3, 1000);<strong><em>//No error</em></strong></pre><p>We have pass both the parameters. So, what’s the use of default value if we have to pass both values.</p><p>So, to use the default value, we can use the <strong>@JvmOverloads annotation</strong>. Now, after using the annotation, the Kotlin code will be:</p><pre><strong>class </strong>RetryWithDelay <strong>@JvmOverloads</strong> <strong>constructor</strong>(<strong>private val maxRetries</strong>: Int, <strong>private val retryDelayInMillis</strong>: Int = 2000)</pre><p>Here, we have used the @JvmOverloads annotation. Now, calling from Java, we need not pass all the parameters:</p><pre>RetryWithDelay retryOne = <strong>new</strong> RetryWithDelay(3);<strong><em>//No error</em></strong></pre><pre>RetryWithDelay retryTwo = <strong>new</strong> RetryWithDelay(3, 1000);<strong><em>//No error</em></strong></pre><h3>@JVMField</h3><p>Let’s take the same example of the RetryWithDelay class that we used in the above example.</p><p>If we are writing the same code in Java then we must have to include some getters and setters for the properties of the class. For example, for the <strong>maxRetriesCount</strong> of the <strong>RetryWithDelay</strong> we have to make a getter method:</p><pre><strong>public</strong> <strong>class</strong> <strong>RetryWithDelay</strong> {<br>    <strong>public</strong> <strong>final</strong> int <strong>maxRetriesCount</strong>;</pre><pre>    <strong>public</strong> <strong>getMaxRetriesCount</strong>(int <strong>maxRetriesCount</strong>) {<br>        <strong>this</strong>.<strong>maxRetriesCount</strong> = <strong>maxRetriesCount</strong>;<br>    }<br>}</pre><p>And the Kotlin code for the same will be:</p><pre><strong>data class </strong>RetryWithDelay(<strong>private val maxRetriesCount</strong>: Int, <strong>private val retryDelayInMillis</strong>: Int = 2000)</pre><p>So, if we are accessing the properties of the class then the code in Kotlin is:</p><pre>val retryOne = RetryWithDelay(3, 1000)<br>val maxNumberOfRetries = retryOne.<strong>maxRetriesCount</strong></pre><p>But in Java, we have to use the getter method:</p><pre>RetryWithDelay retryOne = <strong>new</strong> RetryWithDelay(3, 1000);<br>int maxNumberOfRetries = retryOne.<strong>getMaxRetriesCount</strong>();</pre><p>So, if we want a particular field to be used as normal field and not as getter or setter then we have to tell the compiler not to generate any getter and setter for the same and this can be done by using the <strong>@JvmField annotation</strong>. So, the Kotlin code after using the @JvmField annotation will be:</p><pre><strong>data class </strong>RetryWithDelay(@JvmField<strong> val maxRetriesCount</strong>: Int, <strong>private val retryDelayInMillis</strong>: Int = 2000)</pre><p>Now, in Java also, we can access the fields of the class in the same way as in Kotlin:</p><pre>RetryWithDelay retryOne = <strong>new</strong> RetryWithDelay(3, 1000);<br>int maxNumberOfRetries = retryOne.<strong>maxRetriesCount</strong>;</pre><p><strong>Junior:</strong> Awww… Sounds great!!!. I will change our API RetryWithDelay class into Kotlin right away and use these annotations at exactly where needed.</p><p><strong>Senior:</strong> Kotlin is on pretty solid footing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81a399dabe36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Android 10 Features]]></title>
            <link>https://medium.com/@dharmasai.seerapu/google-android-10-features-f0ffd2b01380?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ffd2b01380</guid>
            <category><![CDATA[secure]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dark-theme]]></category>
            <category><![CDATA[android-10]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 12:01:06 GMT</pubDate>
            <atom:updated>2019-09-09T12:01:06.129Z</atom:updated>
            <content:encoded><![CDATA[<p>Google has recently launched the latest version of its Android operating system for smartphones. The new features integrated into the current version are quite innovative. Keep in mind not all the mentioned features are launching for all devices, they will appear first for the Google device Pixel.</p><h3>1. Fordable Phone</h3><p>Samsung was the first to officially announce foldable phones, Google decided to upgrade its OS to be compatible with the foldable phones. Support for foldable UI and big screen devices is one of the major features of Android 10. This has completely transformed the development of dynamic, and scalable apps that work in foldable window mode.</p><h3><strong>2. Multi-Resume</strong></h3><p>Android 10 most unique feature is the support of multi-resume functionality, allowing mobile users to operate multiple apps simultaneously, without pausing. Yes, a lot of modes were present earlier like the split-screen, freeform and picture-in-picture. But, these features were present only on the app when it is resumed. While Google has instructions for the multi-window, but <a href="https://www.androiddeveloper.co.in/"><strong>Android app development company</strong></a><strong> </strong>don’t take these instructions on a serious note. This causes apps to get crashed in the paused state. This was a major drawback with earlier Android versions, which has been addressed. With Android 10, an advanced Split Screen is offered, which allow apps to run in the background easily.</p><h3><strong>3. Pixel Presence</strong></h3><p>Initially, the Smart Lock feature was only available for the Pixel phones. However, with Android 10 OS launch, this feature will be available for all Android phones, with a new tag ‘Pixel Presence.’ Smart Lock feature provides smooth and quick unlocking of the mobile device in numerous scenarios.</p><ul><li>When contact with the user’s body.</li><li>When present in a trusted location.</li><li>Identify user’s face and voice.</li><li>When identifying the Bluetooth device.</li></ul><h3><strong>4. Dark Theme</strong></h3><p>There’s a Dark Theme available in Android 10, having all menus, fonts, notification panels, &amp; buttons, in addition to the Android system UI. It makes the UI design quite engaging as well as smooth for the eyes. In addition to that, other important benefits are:<br>• Low power usage.<br>• Users with low vision enjoy the dark theme.<br>• Easy to access in a low-light environment.</p><p><strong>Steps to enable Dark Theme:</strong><br>1. Setting -&gt; Display -&gt; Theme -&gt; Select Dark Theme<br>2. Once enabled, select from the notification panel.<br>3. Pixel phones by default enable Dark theme when the battery is low.</p><h3><strong>5. Highly Secure</strong></h3><p>Android with its latest release focusing more on user privacy by offering a feature related to the app permission. It actually gives the user more control over the data being shared with apps. Let’s make it simple for you with an example, if an app is using your location it requires proper permission to access it. The features like runtime permission can easily access the location when an app is running and can limit the data a particular app can gather. The location access by the app can be blocked as well in Android 10 and also you can manage the photos, videos, and audio files which were not possible with earlier versions.</p><h3><strong>6. Native Screen Recording</strong></h3><p>Native screen recording is the feature that has been in very much demand is now available in Android 10 version. To enable it to have a look into the developer option. The feature will work properly giving you feature to record the screen and the voiceover as well.</p><p><strong>Steps to enable Screen Recording:</strong></p><ul><li>Go to Settings -&gt; System -&gt; Developer options and navigate to the Feature flags mentioned in the Debugging sub-menu.</li><li>To activate the feature, press the power button and press the screenshot button to open the dialog box having different options.</li><li>Then select it to use the feature to record the native screen on your smartphone.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ffd2b01380" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Different Ways to Reduce Your Android App APK Size]]></title>
            <link>https://medium.com/@dharmasai.seerapu/different-ways-to-reduce-your-android-app-apk-size-5b2f737f29ad?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b2f737f29ad</guid>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[apk-size]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Sat, 13 Apr 2019 10:36:58 GMT</pubDate>
            <atom:updated>2019-04-13T17:05:46.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Try the New R8 Code Shrinker</h3><p>Code shrinking can help you reduce the size of your APK by deleting unused code and resources.</p><p>According to Google, shrinks code faster than ProGuard.</p><p>To try R8 for yourself, make sure you’re running <strong>Android Studio 3.3 beta 1 or higher</strong>, and then add the following to your <strong>gradle.properties</strong> file:</p><p>android.enableR8=true</p><h3>2. Shrink Your Code With ProGuard</h3><p>At the time of writing, <strong>R8 was still in preview</strong>, so until it’s stable you might prefer to use ProGuard to remove unused classes, methods, fields, and attributes from your code.</p><p>To enable ProGuard, add the following to your module-level <strong>build.gradle</strong> file:</p><pre>buildTypes {</pre><pre>release {</pre><pre>minifyEnabled true</pre><pre>proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;</pre><pre>}</pre><pre>}</pre><pre>}</pre><h3>3. Examine Your APK Using Android Studio’s APK Analyzer</h3><p>You can identify the biggest contributors towards the size of your APK by using Android Studio’s new <em>APK Analyzer</em>. This tool lets you explore the absolute and relative size of different categories of files, and even the size of individual files, so you’ll know <em>exactly</em> where you should be focusing your efforts.</p><p>To analyze an APK, just select <strong>Build</strong> &gt; <strong>Analyze APK</strong> from Android Studio’s menu bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*1Wr_albSkAy2FlaJQstMyg.png" /><figcaption>percentage of the Download size that the folder takes up.</figcaption></figure><p>For each file and folder, the APK Analyzer displays:</p><ul><li><strong>Raw file size. </strong>This is the unzipped size of this item on the disk.</li><li><strong>Download size. </strong>This is the estimated compressed size of the item, as it would be delivered by Google Play.</li><li><strong>% of total download size. </strong>The percentage of the APK’s total download size that this item represents.</li></ul><p>This isn’t the only feature the APK Analyzer has to offer.</p><h3>4. Enable Resource Shrinking</h3><p>The second largest component in your apk size is your res folder, which contains all the images, raw files, and XML. You cannot add/remove/modify your XML, as they are containing your layouts. But we can decrease the image files.</p><ul><li>“<strong><em>shrinkResources</em></strong>” attribute will remove all the resources, those are not used anywhere in the project. Enable this in your build.gradle file by adding below line:</li></ul><pre>buildTypes {</pre><pre>release {</pre><pre>shrinkResources true</pre><pre>minifyEnabled true</pre><pre>proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;</pre><pre>}</pre><pre>}</pre><ul><li>“<strong><em>resConfigs</em></strong>” attribute will remove all the other localized resources while building the application. In our case, “Anti-Theft Screen Lock” only supports the English language. While all the support libraries may have localized folders for other languages. Which we don’t need. So, add the following line to allow only English resources to be added in APK file.</li></ul><pre>buildTypes {</pre><pre>release {</pre><pre>shrinkResources true</pre><pre>minifyEnabled true</pre><pre>//strip other than english resources    <br>resConfigs &quot;en&quot;</pre><pre>proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;</pre><pre>}</pre><pre>}</pre><h3>4.Convert Your PNGs, JPEGs, and BMPs Into WebP</h3><p>If your project contains a number of drawables, then compressing them can significantly reduce the size of your APK.</p><p>If your project’s minSdkVersion is 18 or higher, then you can compress your PNGs, JPEGs, and BMPs by converting them to WebP format.</p><p>First, control-click the drawable that you want to convert and select <strong>Convert to WebP… </strong>Choose between lossy, or lossless encoding. Select <strong>Skip images when the encoded result is larger than the original</strong> and click <strong>OK</strong> to convert the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*d4MEbQdV7z9HijQAQQpvuQ.png" /><figcaption>Right click on any image and click on convert to WebP image.</figcaption></figure><p>It will convert all the png images to webp format one-by-one. If the webp image is having a larger size than png, Android Studio will automatically skip that file</p><h3>7. Avoid enumerations and use @IntDef annotation</h3><h4>8. Use aaptOptions { cruncherEnabled = false } to compress images</h4><p>In the individual apps’s build.gradle, section android {}, insert:</p><pre>aaptOptions {  <br>    cruncherEnabled = false  <br>}</pre><p><strong>9.</strong> Use <strong><em>Remove Unused Resources</em></strong> android studio built-in function to remove all the unused resources in the application</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqQxUh7tL32aV_0hOo7bpg.png" /></figure><p>10 . Use <strong><em>Code Cleanup </em></strong>android studio built-in function to remove</p><ul><li>non-used import</li><li>Abstraction issues</li><li>Code style issues</li><li>Java Beans issues etc</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*ggwCyU_clmNSZC8BYmx0nQ.png" /></figure><blockquote><strong>Note: Go enable it! (*just double and triple check everything works afterwards)</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b2f737f29ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inject into Workers (androidx.WorkManager API)]]></title>
            <link>https://medium.com/@dharmasai.seerapu/inject-into-workers-androidx-workmanager-api-7404146cb37f?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/7404146cb37f</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dagger-android]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[worker-manager]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Tue, 12 Feb 2019 17:50:00 GMT</pubDate>
            <atom:updated>2019-02-12T17:51:49.816Z</atom:updated>
            <content:encoded><![CDATA[<p>From latest Google I/O you just presented the new `androidx.work.Worker` class, part of the new [WorkManager API](<a href="https://developer.android.com/topic/libraries/architecture/workmanager">https://developer.android.com/topic/libraries/architecture/workmanager</a>).</p><p>Since the `Worker` class is created by the framework (we only pass the Worker class type to the `WorkManager`), how can we <a href="http://twitter.com/Inject">@Inject</a> fields into the Worker?</p><p>Let’s see how we @Inject fields into the worker?</p><p><strong>Step 1: </strong>Create <strong><em>AndroidWorkerInjection.class</em></strong> Responsible for injecting dependencies into [WorkManager API](<a href="https://developer.android.com/topic/libraries/architecture/workmanager">https://developer.android.com/topic/libraries/architecture/workmanager</a>).</p><pre><strong>public class </strong>AndroidWorkerInjection {<br><br>    <strong>public static void </strong>inject(Worker worker) {<br>        <em>//TODO : Check not null<br><br>        </em>Object application = worker.getApplicationContext();<br><br>        <strong>if </strong>(!(application <strong>instanceof </strong>HasWorkerInjector)) {<br>            <strong>throw new </strong>RuntimeException(<br>                    String.<em>format</em>(<br>                            <strong>&quot;%s does not implement %s&quot;</strong>,<br>                            application.getClass().getCanonicalName(),<br>                            HasWorkerInjector.<strong>class</strong>.getCanonicalName()));<br>        }<br><br>        AndroidInjector&lt;Worker&gt; workerInjector =<br>                ((HasWorkerInjector) application).workerInjector();<br>        <em>checkNotNull</em>(workerInjector, <strong>&quot;%s.workerInjector() returned null&quot;</strong>, application.getClass());<br>        workerInjector.inject(worker);<br>    }<br>}</pre><p><strong>Step 2: </strong>Create a <strong>AndroidWorkerInjectionModule.class </strong>responsible for the binding same type of classes into one. In our case, all the class extends <strong>Worker class</strong></p><pre>@Module<br><strong>public abstract class </strong>AndroidWorkerInjectionModule {<br><br>    @Multibinds<br>    <strong>abstract </strong>Map&lt;Class&lt;? <strong>extends </strong>Worker&gt;, AndroidInjector.Factory&lt;? <strong>extends </strong>Worker&gt;&gt;<br>    workerInjectorFactories();<br>}</pre><p><strong>Step 3:</strong> Let&#39;s define our <strong>AppComponent.class</strong> and add above modules into it as below</p><pre>@Singleton<br>@Component(modules = {<br>        AppModule.<strong>class</strong>,<br>        AndroidInjectionModule.<strong>class</strong>,<br>        AndroidWorkerInjectionModule.<strong>class, </strong>// Worker injection module referenced in the AppComponent<br>        WorkerModule.<strong>class</strong>}) // Worker Module<br><strong>public interface </strong>AppComponent {<br><br>    @Component.Builder<br>    <strong>interface </strong>Builder {<br><br>        @BindsInstance<br>        Builder application(Application application);<br><br>        AppComponent build();<br>    }<br><br>    <strong>void </strong>inject(MyApplication myApplication);<br>}</pre><p><strong>Step 4:</strong> Define <strong>HasWorkerInjector </strong>as how we usually define Injectors for Activities <strong>HasActivityInjector, </strong>Services <strong>HasServiceInjector </strong>and etc..</p><pre><strong>public interface </strong>HasWorkerInjector {<br>    AndroidInjector&lt;Worker&gt; workerInjector();<br>}</pre><p><strong>Step 5:</strong> let&#39;s implement <strong>HasWorkerInjector </strong>in the Application class. In our case Application is: <strong>MyApplication.class</strong></p><pre><strong>public class MyApplication</strong> <strong>extends </strong>Application <strong>implements </strong>HasWorkerInjector{<br><br>    @Inject<br>    DispatchingAndroidInjector&lt;Worker&gt; <strong>workerDispatchingAndroidInjector</strong>;<br><br>    <strong>private </strong>AppComponent <strong>appComponent</strong>;<br><br>    @Override<br>    <strong>public void </strong>onCreate() {<br>        <strong>super</strong>.onCreate();<br><br>        initializeDaggerComponent();<br>    }<br><br>    @Override<br>    <strong>public </strong>AndroidInjector&lt;Worker&gt; workerInjector() {<br>        <strong>return workerDispatchingAndroidInjector</strong>;<br>    }<br><br>    <strong>private void </strong>initializeDaggerComponent() {<br><br>        <strong>appComponent </strong>= DaggerAppComponent.<em>builder</em>().application(<strong>this</strong>).build();<br>        <strong>appComponent</strong>.inject(<strong>this</strong>);<br>    }<br>}</pre><p><strong>Step 6:</strong> Let’s define our WorkerModule class and each individual modules into it.</p><pre>@Module(subcomponents = {<br>        ProfileWorkerModule.<strong>class<br></strong>})<br><strong>public abstract class </strong>WorkerModule {<br>    @Binds<br>    @IntoMap<br>    @WorkerKey(ProfileWorker.<strong>class</strong>) //Define your Worker class extends <strong>Worker </strong>class<br>    <strong>abstract </strong>AndroidInjector.Factory&lt;? <strong>extends </strong>Worker&gt; bindProfileWorkerFactory(WorkerComponent.Builder profileWorker);<br>}</pre><p><strong>Step 7: </strong>Create the corresponding Module i.e.,<strong> ProfileWorkerModule.class</strong></p><pre>@Subcomponent<br><strong>public interface </strong>ProfileWorkerModule <strong>extends </strong>AndroidInjector&lt;ProfileWorker&gt; {<br><br>    @Subcomponent.Builder<br>    <strong>abstract class </strong>Builder <strong>extends </strong>AndroidInjector.Builder&lt;CustomWorkManager&gt;{}<br>}</pre><p>Step 8: Let&#39;s create <strong>ProfileWorker.class </strong>and inject the dependencies. As simple as that.</p><pre><strong>public class </strong>ProfileWorker <strong>extends </strong>Worker {<br><br>    <strong>public static final </strong>String <strong><em>MODEL_OBJECT </em></strong>= <strong>&quot;sync_model&quot;</strong>;<br><br>    @Inject<br>    SomeClass <strong>someClass</strong>; // Dependency is injected here<br><br>    <strong>public </strong>ProfileWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {<br>        <strong>super</strong>(context, workerParams);<br>    }<br><br>    @NonNull<br>    @Override<br>    <strong>public </strong>Result doWork() {<br><br>        AndroidWorkerInjection.<em>inject</em>(<strong>this</strong>);// Injecting worker class here.<br>        <strong>return </strong>Result.Success.<em>success</em>();<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7404146cb37f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FirebaseInstanceIdService is deprecated ?]]></title>
            <link>https://medium.com/@dharmasai.seerapu/firebaseinstanceidservice-is-deprecated-5289c46f6cb6?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/5289c46f6cb6</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[fcm]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Thu, 06 Dec 2018 09:37:28 GMT</pubDate>
            <atom:updated>2018-12-06T09:37:28.406Z</atom:updated>
            <content:encoded><![CDATA[<h3>FirebaseInstanceIdService is deprecated ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Ds5dCQ2Z54MdELW8pWTh6Q.png" /></figure><p>FirebaseInstanceIdService is deprecated ? The answer is <strong>YES. </strong>Recently we got many updates in dependencies of <a href="https://firebase.google.com/"><strong>Firebase Cloud Messaging (FCM)</strong></a></p><p><em>Check this class </em><strong><em>FirebaseInstanceIdService</em></strong><em> extends </em><a href="https://developer.android.com/reference/android/app/Service.html"><em>Service</em></a></p><blockquote><strong><em>This class was deprecated.</em></strong><em><br> In favour of overriding </em>onNewToken<em> in </em>FirebaseMessagingService<em>.</em> Once that has been implemented, this service can be safely removed.</blockquote><p>Above deprecated class tells us that, No need to useFirebaseInstanceIdService service to get FCM token. You can safely remove FirebaseInstanceIdService service</p><p><strong>Old and deprecated code :</strong></p><ol><li><strong>Remove the service from Manifest.xml which extends </strong>FirebaseInstanceIDService</li></ol><p>Manifest.xml :</p><pre>&lt;service android:name=&quot;.fcm.FCMListenerService&quot;&gt;<br>    &lt;intent-filter&gt;<br>       &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><pre><strong>&lt;!--Deprecated and removed below listener which extends FirebaseInstanceIdService--&gt;<br>&lt;!--Commented below code --&gt;</strong></pre><pre>&lt;service android:name=&quot;.FCMIdListenerService&quot;&gt;<br>    &lt;intent-filter&gt;<br>      &lt;action android:name=&quot;com.google.firebase.INSTANCE_ID_EVENT&quot;/&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><p><strong>2. Removed the class: </strong>FCMIdListenerService</p><pre>// Removed class<br>public class FCMIdListenerService extends <strong>FirebaseInstanceIdService</strong> {<br><br>    <em>/**<br>     * This method is deprecated<br>     */<br>    </em>@Override<br>    public void onTokenRefresh() {<br>        startService(new Intent(this, SaveFCMIdService.class));<br>    }<br>}</pre><p>3. Get Token in your activity: <strong>getToken() </strong>is<strong> </strong>deprecated</p><pre>String refreshedToken = FirebaseInstanceId.getInstance().getToken();</pre><p><strong>So, what is the updated code and solution for it?</strong></p><ol><li>We need to @Override onNewToken() method to get a new token in the class which extendsFirebaseMessagingService</li></ol><p>Check FCMListenerService code :</p><pre>public class FCMListenerService extends FirebaseMessagingService {<br><br>    <em>/**<br>     * When newtoken is generated. Save and register FCM with this    token<br>     */<br>    </em>@Override<br>    public void onNewToken(String s) {<br>        super.onNewToken(s);<br>        startService(new Intent(this, SaveFCMIdService.class));<br><br>    }</pre><p>2. Get Token in your Activity :</p><pre>FirebaseInstanceId.<em>getInstance</em>().getInstanceId().addOnSuccessListener(instanceIdResult -&gt; {<br>    try {<br>        String refreshedToken = instanceIdResult.getToken();<br>         // Yay.. we have our new token now.<br>    } catch (Exception e) {<br>        Timber.<em>e</em>(e.getMessage());<br>    }<br>});</pre><p>Hope you will found your solution here.</p><p>If you like, keep clapping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5289c46f6cb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android App Bundles : What are they and how to create them?]]></title>
            <link>https://medium.com/@dharmasai.seerapu/android-app-bundles-what-are-they-and-how-to-create-them-a5b53d51d5f5?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b53d51d5f5</guid>
            <category><![CDATA[app-bundle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-app-bundle]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Tue, 13 Nov 2018 07:09:38 GMT</pubDate>
            <atom:updated>2018-11-13T08:57:43.320Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android App Bundles : What are they and how to create them?</h3><p>At Google I/O 2018, the search giant introduced Android App Bundles, a new file type built to keep file size and complexity under control. The new file is meant to better serve the diverse spread of devices that run Android.</p><h3><strong>Problems with multiple apk files</strong></h3><p>Making an app that works on the tiniest smartphone and the biggest Android TV can create a seriously large file, making it inaccessible to a number of lower-end devices. To keep file sizes low, some developers create multiple APKs containing files for specific screen densities or processors. Developers can upload these different files to Google Play, and Google will push the relevant ones to a device when the user installs it.</p><h3><strong>Solution with Android App Bundles</strong></h3><p>The problem with that method is it makes for more complex builds — that’s where Android App Bundles come in. The new file format includes all your app’s compiled code and resources, but allows Google Play to generate and serve optimized APKs for each user’s device.</p><h4><strong>How Android App Bundles Solving the space?</strong></h4><ol><li>App bundles sends the relevant chunks to individual devices. Hence, actual size of an apk becomes much smaller.</li><li>The total number of permutations for language packs, screen densities, and supported CPU architectures can grow very quickly</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9iQdbTTncIELzny48hfb9Q.jpeg" /></figure><ul><li>According to Google, list of apps which shown in image could shrink around <strong>35%</strong></li><li>In other cases this could be has high as 50%</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X1qfgqfG19zZRTNkbH6o-Q.jpeg" /></figure><ul><li>According to Twitter, its app can be delivered in one of 500 different combinations via Android App Bundles.</li></ul><p>Maintaining 500 separate APK files would be time consuming and costly. This way Twitter can build one bundle and let Google Play sort out all the different permutations.</p><h3><strong>How to create Android App Bundles</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3oIQ_k5HPMOP_6pxBhlEw.jpeg" /></figure><ul><li>Android Studio has been updated to handle this new build process and now developers can build a signed Android App Bundle ready for upload to Google Play.</li><li>There is a new Build Bundle option in the Build menu, alongside the traditional Build APK option.</li></ul><blockquote><strong>Note : </strong>An app bundle is different from an traditional APK in that developer can’t deploy directly to a device.It first needs go to the Play Store, where Google Play will then handle the bundle and deliver the necessary tailored APK to devices.</blockquote><h3><strong>Dynamic Delivery</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Zsgmm27v4wz_OtDmIMfPA.jpeg" /></figure><p>Now that bundles allow an app to be split into different chunks, the next logical progression is to offer functionality in chunks. If a user doesn’t need certain functionality, why download it? The example Google gives is of app that allows consumers to sell and purchase items over the web. <strong><em>Many users will only ever purchase and never sell, and the selling code will sit on the device wasting resources. With Dynamic Delivery, the selling functionality isn’t included in the base APK installed</em></strong>. When the user wants sell something, the app will download the extra code and resources needed.</p><h3><strong>Wrap Up</strong></h3><ul><li>Android App Bundles can be a game changer for every app delivery and management</li><li>It provides not only getting space optimized apps, but the possibilities of Dynamic Delivery means functionality can be added to apps if needed.</li></ul><h3><strong>Links</strong></h3><p><a href="https://developer.android.com/studio/run/">Build and run your app | Android Developers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b53d51d5f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kotlin Vs Java : Basic Syntax Differences]]></title>
            <link>https://medium.com/@dharmasai.seerapu/kotlin-vs-java-basic-syntax-differences-2a84c3bd9bc7?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a84c3bd9bc7</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-extension]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Wed, 11 Jul 2018 13:23:42 GMT</pubDate>
            <atom:updated>2018-07-11T13:23:42.882Z</atom:updated>
            <content:encoded><![CDATA[<p>Kotlin is really a promising language and everybody is talking about it and saying it’s cool. But why its so special?</p><p>We will discuss how Kotlin differs from Java when it comes to syntax, usability, UI performance.</p><h3><strong>Syntax Difference</strong></h3><h4>1) You can do more with less code</h4><p>One of the main advantages of Kotlin is its concision. You get more functionality with less code. And the less code you write, the fewer mistakes you make</p><pre><strong>public</strong> <strong>final</strong> <strong>class</strong> <strong>Person</strong> {<br>    <strong>private</strong> String name;<br>    <strong>private</strong> <strong>int</strong> age;<br>    <strong>private</strong> <strong>float</strong> height;<br><br>    <strong>public</strong> <strong>Person</strong>(String name, <strong>int</strong> age, <strong>float</strong> height) {<br>        <strong>this</strong>.name = name;<br>        <strong>this</strong>.age = age;<br>        <strong>this</strong>.height = height;<br>    }<br><br>    <strong>public</strong> <strong>Person</strong>(String name, <strong>int</strong> age) {<br>        <strong>this</strong>.name = name;<br>        <strong>this</strong>.age = age;<br>        <strong>this</strong>.height = 1.8f;<br>    }<br><br>    <strong>public</strong> String <strong>getName</strong>() {<br>        <strong>return</strong> name;<br>    }<br><br>    <strong>public</strong> <strong>void</strong> <strong>setName</strong>(String name) {<br>        <strong>this</strong>.name = name;<br>    }<br><br>    <strong>public</strong> <strong>int</strong> <strong>getAge</strong>() {<br>        <strong>return</strong> age;<br>    }<br><br>    <strong>public</strong> <strong>void</strong> <strong>setAge</strong>(<strong>int</strong> age) {<br>        <strong>this</strong>.age = age;<br>    }<br><br>    <strong>public</strong> <strong>float</strong> <strong>getHeight</strong>() {<br>        <strong>return</strong> height;<br>    }<br><br>    <strong>public</strong> <strong>void</strong> <strong>setHeight</strong>(<strong>float</strong> height) {<br>        <strong>this</strong>.height = height;<br>    }<br><br>    @Override<br>    <strong>public</strong> String <strong>toString</strong>() {<br>        <strong>return</strong> &quot;Person{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, age=&quot; + age +<br>                &quot;, height=&quot; + height +<br>                &#39;}&#39;;<br>    }<br><br>    @Override<br>    <strong>public</strong> <strong>boolean</strong> <strong>equals</strong>(Object o) {<br>        <strong>if</strong> (<strong>this</strong> == o) <strong>return</strong> <strong>true</strong>;<br>        <strong>if</strong> (o == <strong>null</strong> || getClass() != o.getClass()) <strong>return</strong> <strong>false</strong>;<br><br>        Person person = (Person) o;<br><br>        <strong>if</strong> (age != person.age) <strong>return</strong> <strong>false</strong>;<br>        <strong>if</strong> (Float.compare(person.height, height) != 0) <strong>return</strong> <strong>false</strong>;<br>        <strong>return</strong> name != <strong>null</strong> ? name.equals(person.name) : person.name == <strong>null</strong><br>    }<br><br>    @Override<br>    <strong>public</strong> <strong>int</strong> <strong>hashCode</strong>() {<br>        <strong>int</strong> result = name != <strong>null</strong> ? name.hashCode() : 0;<br>        result = 31 * result + age;<br>        result = 31 * result + (height != +0.0f ? Float.floatToIntBits(height) : 0);<br>        <strong>return</strong> result;<br>    }   <br>}</pre><p>Above one is as usual Java class with having setters and getters. Lets look at how can we implement in Kotlin</p><pre>data class <strong>Person</strong>(var name: String,<br>                 var age: Int,<br>                 var height: Float = 1.8f)</pre><p>Yes, you’ll automatically get needed getters, setters, equals(), hashcode(),toString() and copy() functions for your data class! Of course, you can easily override these functions, but in most cases it’s enough just to declare the class and its properties.</p><h4><strong>2) avoid NullPointerException</strong></h4><pre>val person: Person? = <strong>null<br></strong>person?.name = &quot;John&quot;</pre><p>If the variable is nullable, the compiler will not permit you to access it without a proper check. Kotlin forces you to use a ?. operator. This prevents the app from crashing automatically.</p><h4><strong>3) You can get rid of </strong><strong>util classes</strong></h4><p>Every project should have util classes. Have you ever had a project without them?</p><p>Kotlin has a smart solution — <strong>extension functions </strong>— to help you get rid of all your util classes once and for all.</p><blockquote>The extension function is almost a usual Kotlin function. But when you declare it, you need to specify the class whose instances will have the extension function.</blockquote><pre>fun Context.toast(text: String) = Toast.makeText(<strong>this</strong>, text, Toast.LENGTH_SHORT).show()</pre><p>Notice ‘this’ that we pass as a parameter to the makeText() method? It’s not an instance of the class where we declare this function, rather it’s a Context instance. And now you can call this function directly from your Activity or any other Context instance. For example:</p><pre>toast(&quot;Hi&quot;)</pre><h4><strong>4) Forget about view binding</strong></h4><p>Do you remember the findViewById() method()? We’re sure you don’t like it. We don’t either. Also, we don’t like to declare variables and Butterknife annotations for every view we need to access.</p><p>You can forget about view binding with Kotlin Android Extensions. No longer do you need to create variables and bind views. You can access your views directly with their identifiers declared in the xml layout.</p><pre><strong>public</strong> <strong>class</strong> <strong>MainActivity</strong> <strong>extends</strong> <strong>AppCompatActivity</strong> {<br>    @Override<br>    <strong>protected</strong> <strong>void</strong> <strong>onCreate</strong>(@Nullable Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.activity_main);<br><br>        Button button = (Button) findViewById(R.id.button);<br>        <strong>final</strong> TextView text = (TextView) findViewById(R.id.text); <br>        button.setOnClickListener(<strong>new</strong> View.OnClickListener() {<br>            @Override<br>            <strong>public</strong> <strong>void</strong> <strong>onClick</strong>(View v) {<br>                text.setText(&quot;You&#39;ve clicked a button&quot;);<br>            }<br>        });<br>    }<br>}<br><br><strong>class</strong> <strong>MainActivity</strong> : <strong>AppCompatActivity</strong>() {<br><br>    override fun <strong>onCreate</strong>(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {<br>        <strong>super</strong>.onCreate(savedInstanceState, persistentState)<br>        setContentView(R.layout.activity_main)<br><br>        button.setOnClickListener { text.text = &quot;You&#39;ve clicked a button&quot; }<br>    }<br>}</pre><h4><strong>5) Work with collections much more easily</strong></h4><p>Now a days, in each project we need to perform difficult operations with collections of data models.</p><p>For example, we might have a list of students from which we need to retrieve three students with A grades, and two students with B grades.</p><p>Look at the solution in Kotlin:</p><pre>var students = listOf(Student(&quot;John&quot;, 0), Student(&quot;Julia&quot;, 2), Student(&quot;Matt&quot;, 1),<br>                Student(&quot;Katie&quot;, 0), Student(&quot;Dan&quot;, 0))<br><br>var firstList = students.filter { it.mark == 0 }.take(3)<br>var secondList = students.filter { it.mark == 1 }.take(2)</pre><p>Here’s how we would solve the same problem in Java:</p><pre>ArrayList&lt;Student&gt; students = <strong>new</strong> ArrayList&lt;Student&gt;() {{<br>            add(<strong>new</strong> Student(&quot;John&quot;, 0));<br>            add(<strong>new</strong> Student(&quot;Julia&quot;, 2));<br>            add(<strong>new</strong> Student(&quot;Matt&quot;, 1));<br>            add(<strong>new</strong> Student(&quot;Katie&quot;, 0));<br>            add(<strong>new</strong> Student(&quot;Dan&quot;, 0));<br>}};<br><br>ArrayList&lt;Student&gt; firstList = <strong>new</strong> ArrayList&lt;&gt;();<br>ArrayList&lt;Student&gt; secondList = <strong>new</strong> ArrayList&lt;&gt;();<br><br><strong>for</strong> (Student student: students) {<br>            <strong>boolean</strong> isFirstFilled = firstList.size() &gt;= 3;<br>            <strong>boolean</strong> isSecondFilled = secondList.size() &gt;= 2;<br><br>            <strong>if</strong> (isFirstFilled &amp;&amp; isSecondFilled) <strong>break</strong>;<br>            <strong>int</strong> mark = student.getMark();<br>            <strong>if</strong> (mark == 0 &amp;&amp; !isFirstFilled) {<br>                firstList.add(student);<br>            } <strong>else</strong> <strong>if</strong> (mark == 1 &amp;&amp; !isSecondFilled) {<br>                secondList.add(student);<br>            }<br>        }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a84c3bd9bc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Java to Kotlin]]></title>
            <link>https://medium.com/@dharmasai.seerapu/from-java-to-kotlin-e4b1027d6cba?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b1027d6cba</guid>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Wed, 13 Jun 2018 06:31:04 GMT</pubDate>
            <atom:updated>2018-06-13T06:31:04.125Z</atom:updated>
            <content:encoded><![CDATA[<p>Check out the best cheat seat for Kotlin beginners.</p><h3><strong>Constants and Variables</strong></h3><blockquote><em>Java</em></blockquote><pre>String name = &quot;Dharma Sai&quot;;<br>final String name = &quot;Dharma Sai&quot;;</pre><blockquote><em>Kotlin</em></blockquote><pre>var name = &quot;Dharma Sai&quot;<br>val name = &quot;Dharma Sai&quot;</pre><h3>Assigning the null value</h3><blockquote><em>Java</em></blockquote><pre>String otherName;<br>otherName = null;</pre><blockquote><em>Kotlin</em></blockquote><pre>var otherName : String?<br>otherName = null</pre><h3>Verify if value is null</h3><blockquote><em>Java</em></blockquote><pre>if (text != null) {<br>  int length = text.length();<br>}</pre><blockquote><em>Kotlin</em></blockquote><pre>text?.let {<br>    val length = text.length<br>}<br>// or simply<br>val length = text?.length</pre><h3>Check the type and casting</h3><blockquote><em>Java</em></blockquote><pre>if (object instanceof Car) {<br>}<br>Car car = (Car) object;</pre><blockquote><em>Kotlin</em></blockquote><pre>if (object is Car) {<br>}<br>var car = object as Car</pre><pre>// if object is null<br>var car = object as? Car // var car = object as Car?</pre><h3>Check the type and casting (implicit)</h3><blockquote><em>Java</em></blockquote><pre>if (object instanceof Car) {<br>   Car car = (Car) object;<br>}</pre><blockquote><em>Kotlin</em></blockquote><pre>if (object is Car) {<br>   var car = object // smart casting<br>}</pre><pre>// if object is null<br>if (object is Car?) {<br>   var car = object // smart casting, car will be null<br>}</pre><h3>Multiple conditions</h3><blockquote><em>Java</em></blockquote><pre>if (score &gt;= 0 &amp;&amp; score &lt;= 300) { }</pre><blockquote><em>Kotlin</em></blockquote><pre>if (score in 0..300) { }</pre><h3>For-loops</h3><blockquote><em>Java</em></blockquote><pre>for (int i = 1; i &lt;= 10 ; i++) { }</pre><pre>for (int i = 1; i &lt; 10 ; i++) { }</pre><pre>for (int i = 10; i &gt;= 0 ; i--) { }</pre><pre>for (int i = 1; i &lt;= 10 ; i+=2) { }</pre><pre>for (int i = 10; i &gt;= 0 ; i-=2) { }</pre><pre>for (String item : collection) { }</pre><pre>for (Map.Entry&lt;String, String&gt; entry: map.entrySet()) { }</pre><blockquote><em>Kotlin</em></blockquote><pre>for (i in 1..10) { }</pre><pre>for (i in 1 until 10) { }</pre><pre>for (i in 10 downTo 0) { }</pre><pre>for (i in 1..10 step 2) { }</pre><pre>for (i in 10 downTo 1 step 2) { }</pre><pre>for (item in collection) { }</pre><pre>for ((key, value) in map) { }</pre><h3>Collections</h3><blockquote><em>Java</em></blockquote><pre>final List&lt;Integer&gt; listOfNumber = Arrays.asList(1, 2, 3, 4);</pre><pre>final Map&lt;Integer, String&gt; keyValue = new HashMap&lt;Integer, String&gt;();<br>map.put(1, &quot;Dharma&quot;);<br>map.put(2, &quot;Sai&quot;);<br>map.put(3, &quot;Groupify&quot;);</pre><pre>// Java 9<br>final List&lt;Integer&gt; listOfNumber = List.of(1, 2, 3, 4);</pre><pre>final Map&lt;Integer, String&gt; keyValue = Map.of(1, &quot;Dharma&quot;,<br>                                             2, &quot;Sai&quot;,<br>                                             3, &quot;Groupify&quot;);</pre><blockquote><em>Kotlin</em></blockquote><pre>val listOfNumber = listOf(1, 2, 3, 4)<br>val keyValue = mapOf(1 to &quot;Dharma&quot;,<br>                     2 to &quot;Sai&quot;,<br>                     3 to &quot;Groupify&quot;)</pre><h3>for each</h3><blockquote><em>Java</em></blockquote><pre>// Java 7 and below<br>for (Car car : cars) {<br>  System.out.println(car.speed);<br>}</pre><pre>// Java 8+<br>cars.forEach(car -&gt; System.out.println(car.speed));</pre><pre>// Java 7 and below<br>for (Car car : cars) {<br>  if (car.speed &gt; 100) {<br>    System.out.println(car.speed);<br>  }<br>}</pre><pre>// Java 8+<br>cars.stream().filter(car -&gt; car.speed &gt; 100).forEach(car -&gt; System.out.println(car.speed));</pre><blockquote><em>Kotlin</em></blockquote><pre>cars.forEach {<br>    println(it.speed)<br>}</pre><pre>cars.filter { it.speed &gt; 100 }<br>      .forEach { println(it.speed)}</pre><pre>// kotlin 1.1+<br>cars.stream().filter { it.speed &gt; 100 }.forEach { println(it.speed)}<br>cars.parallelStream().filter { it.speed &gt; 100 }.forEach { println(it.speed)}</pre><h3>Defining methods with return</h3><blockquote><em>Java</em></blockquote><pre>int getScore() {<br>   // logic here<br>   return score;<br>}</pre><blockquote><em>Kotlin</em></blockquote><pre>fun getScore(): Int {<br>   // logic here<br>   return score<br>}</pre><pre>// as a single-expression function</pre><pre>fun getScore(): Int = score</pre><pre>// even simpler (type will be determined automatically)</pre><pre>fun getScore() = score // return-type is Int</pre><h3>Returning result of an operation</h3><blockquote><em>Java</em></blockquote><pre>int getScore(int value) {<br>    // logic here<br>    return 2 * value;<br>}</pre><blockquote><em>Kotlin</em></blockquote><pre>fun getScore(value: Int): Int {<br>   // logic here<br>   return 2 * value<br>}</pre><pre>// as a single-expression function<br>fun getScore(value: Int): Int = 2 * value</pre><pre>// even simpler (type will be determined automatically)</pre><pre>fun getScore(value: Int) = 2 * value // return-type is int</pre><h3>Getters and Setters</h3><blockquote><em>Java</em></blockquote><pre>public class Developer {</pre><pre>    private String name;<br>    private int age;</pre><pre>    public Developer(String name, int age) {<br>        this.name = name;<br>        this.age = age;<br>    }</pre><pre>    public String getName() {<br>        return name;<br>    }</pre><pre>    public void setName(String name) {<br>        this.name = name;<br>    }</pre><pre>    public int getAge() {<br>        return age;<br>    }</pre><pre>    public void setAge(int age) {<br>        this.age = age;<br>    }</pre><pre>    @Override<br>    public boolean equals(Object o) {<br>        if (this == o) return true;<br>        if (o == null || getClass() != o.getClass()) return false;</pre><pre>        Developer developer = (Developer) o;</pre><pre>        if (age != developer.age) return false;<br>        return name != null ? name.equals(developer.name) : developer.name == null;</pre><pre>    }</pre><pre>    @Override<br>    public int hashCode() {<br>        int result = name != null ? name.hashCode() : 0;<br>        result = 31 * result + age;<br>        return result;<br>    }</pre><pre>    @Override<br>    public String toString() {<br>        return &quot;Developer{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, age=&quot; + age +<br>                &#39;}&#39;;<br>    }<br>}</pre><blockquote><em>Kotlin</em></blockquote><pre>data class Developer(var name: String, var age: Int)</pre><h3>Class methods</h3><blockquote><em>Java</em></blockquote><pre>public class Utils {</pre><pre>    private Utils() {<br>      // This utility class is not publicly instantiable<br>    }</pre><pre>    public static int triple(int value) {<br>        return 3 * value;<br>    }</pre><pre>}</pre><pre>int result = Utils.triple(3);</pre><blockquote><em>Kotlin</em></blockquote><pre>fun Int.triple(): Int {<br>  return this * 3<br>}</pre><pre>var result = 3.triple()</pre><h3>Defining uninitialized objects</h3><blockquote><em>Java</em></blockquote><pre>Person person;</pre><blockquote><em>Kotlin</em></blockquote><pre>internal lateinit var person: Person</pre><h3>enum</h3><blockquote><em>Java</em></blockquote><pre>public enum Direction {<br>        NORTH(1),<br>        SOUTH(2),<br>        WEST(3),<br>        EAST(4);</pre><pre>        int direction;</pre><pre>        Direction(int direction) {<br>            this.direction = direction;<br>        }</pre><pre>        public int getDirection() {<br>            return direction;<br>        }<br>    }</pre><blockquote><em>Kotlin</em></blockquote><pre>enum class Direction constructor(direction: Int) {<br>    NORTH(1),<br>    SOUTH(2),<br>    WEST(3),<br>    EAST(4);</pre><pre>    var direction: Int = 0<br>        private set</pre><pre>    init {<br>        this.direction = direction<br>    }<br>}</pre><h3>Sorting List</h3><blockquote><em>Java</em></blockquote><pre>List&lt;Profile&gt; profiles = loadProfiles(context);<br>Collections.sort(profiles, new Comparator&lt;Profile&gt;() {<br>    @Override<br>    public int compare(Profile profile1, Profile profile2) {<br>        if (profile1.getAge() &gt; profile2.getAge()) return 1;<br>        if (profile1.getAge() &lt; profile2.getAge()) return -1;<br>        return 0;<br>    }<br>})</pre><blockquote><em>Kotlin</em></blockquote><pre>val profile = loadProfiles(context)<br>profile.sortedWith(Comparator({ profile1, profile2 -&gt;<br>    if (profile1.age &gt; profile2.age) return@Comparator 1<br>    if (profile1.age &lt; profile2.age) return@Comparator -1<br>    return@Comparator 0<br>}))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b1027d6cba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android @ Google I/O 2018]]></title>
            <link>https://medium.com/@dharmasai.seerapu/android-google-i-o-2018-3924636b02bf?source=rss-bd4c0a844456------2</link>
            <guid isPermaLink="false">https://medium.com/p/3924636b02bf</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[paging]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[android-things]]></category>
            <dc:creator><![CDATA[Dharma Sai Seerapu]]></dc:creator>
            <pubDate>Thu, 17 May 2018 09:57:42 GMT</pubDate>
            <atom:updated>2018-05-17T09:59:51.003Z</atom:updated>
            <content:encoded><![CDATA[<h3>Contents</h3><ul><li><strong>Android Jetpack : </strong>Please read it on my previous <a href="https://medium.com/@dharmasai.seerapu/android-jetpack-google-i-o-2018-31ab80ac2dad"><strong>blog</strong></a></li><li><strong>AppCompat / Support Library / AndroidX</strong></li><li><strong>Architecture components</strong></li><li><strong>Navigation</strong></li><li><strong>Paging</strong></li><li><strong>WorkManager</strong></li><li><strong>Slices</strong></li><li><strong>App Bundle</strong></li><li><strong>Android Things</strong></li></ul><h3><strong>AppCompat / Support Library / AndroidX</strong></h3><ul><li><a href="https://developer.android.com/reference/androidx/recyclerview/selection/package-summary">RecyclerView Selection</a> — Allow users to select multiple elements in your RecyclerView. (Like Google Photos)</li><li><a href="https://developer.android.com/reference/android/support/v7/recyclerview/extensions/ListAdapter">RecyclerView ListAdapter</a> — Simpler way to use DiffUtil with animated updates and concurrency support on RecyclerView</li><li>androidx.webkit — Provides access to latest WebView platform APIs</li><li>androidx.browser — Renamed from Chrome custom-tabs.</li><li>HEIF format images support — Coming soon to older versions</li><li><a href="https://github.com/material-components/material-components-android">Material Components</a> — Use components following Material Design guidelines easily in your app.</li></ul><h3>Architecture Components</h3><p>52% Android devs showed interest in using the components</p><p>AppCompatActivity &amp; Fragment implement LifecycleOwner by default now</p><h4>LifecycleOwner</h4><ul><li>When using Fragments and LiveData+ViewModel, change the calls to use the Fragment lifecycle</li></ul><pre>viewmodel.livedata.observe(viewLifeCycleOwner,Observer{ //viewLifeCycleOwner is the lifecycle of the Fragment<br>    //Handle new data<br>})</pre><h4>Data binding</h4><ul><li>Pass the LifecycleOwner to your binding initializer to allow bindings to respect Activity lifecycle</li></ul><pre>val binding: ViewBinding = DatabindingUtil.getBinding(user)<br>binding.setLifecycleOwner(viewLifeCycleOwner)</pre><ul><li>Data binding v2 to support incremental compiling and make multi-modular apps build faster</li></ul><h4>Room</h4><ul><li>Room 1.1 has better support for threading</li><li>Due to threading and WriteAheadLogging (WAL) <strong>queries to different tables would run in parallel rather than serially</strong></li><li>@RawQuery helps you create queries at run-time allowing you to query columns dynamically@RawQuery fun</li></ul><pre>@RawQuery<br>fun getHouses(query:SimpleSQLiteQuery): List&lt;Houses&gt;</pre><h3>Navigation</h3><h4>Description:</h4><ul><li>The Navigation Architecture Component simplifies the implementation of navigation between destinations in your app (A destination is a specific screen in an app)</li><li>By default, the Navigation Architecture Component includes support for Fragments and Activities as destinations, but you can also add support for new types of destinations. A set of destinations compose an app’s “navigation graph.”</li></ul><h4>Implementation:</h4><ul><li>Create a navigation graph (looks like a Wireframe) within XML / Code and link screens with each other (both forward and backward linking if needed)</li><li>Use the NavigationController either</li><li>Set a view’s onClickListener with Navigation.createNavigateOnClickListener(nextScreenId, args) for navigating when clicked</li><li>At the point of navigation, after business logic, call View.findNavController().navigate(R.id.nextScreenId)</li></ul><h4>Bonus: Safe Args</h4><ul><li>Compile-time checking for Navigation arguments to simplify argument passing between Navigation components.</li><li>Ability to specify argument types and default values if some args are optional.</li><li>Internally creates classes to fetch arguments and exposes them as properties via ClassNameArgs.fromBundle(arguments)</li></ul><h4>Article</h4><ul><li><a href="https://willowtreeapps.com/ideas/exploring-androids-navigation-architecture-component">Exploring Android’s Navigation Architecture Component — Nish Tahir</a></li></ul><h3>Paging</h3><p><em>The Paging Library makes it easier for you to load data gradually and gracefully within your app’s RecyclerView.</em></p><ul><li>Allows you to <strong>paginate local results</strong> with <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room</a> database.</li><li>Also allows you to <strong>paginate web requests</strong> with <a href="https://github.com/karntrehan/Android-IO18/blob/master/square.github.io/retrofit">Retrofit</a></li></ul><h4>Code Sample (Non-reactive):</h4><pre>/* In Dao */<br>@Query(&quot;SELECT * FROM users&quot;)<br>fun allUsers(): Datasource.Factory&lt;Int,User&gt;</pre><pre>/* In ViewModel */<br>init{<br>    val factory: Datasource.Factory = database.allUsersFactory()<br>    users = LivePagedListBuilder(factory,30).build() //where 30 is the amount of items to load in one page<br>}<br>val users: Live&lt;PagedList&lt;User&gt;&gt; = userDao.allUsers()</pre><pre>/* In Activity / Fragment */<br>val adapter = MyAdapter()<br>viewmodel.users.observe(this){<br>    adapter.submitList(it)<br>}</pre><pre>/* In Adapter */<br>class MyAdapter():PagedListAdapter&lt;User, UserViewHolder&gt;(<br>    object: DiffUtil.ItemCallback&lt;User&gt;(){<br>        //Override areItemsTheSame and areContentsTheSame<br>}<br>){<br>    override fun onBindViewHolder(holder: UserViewHolder, position: Int){<br>        val user : User? = getItem(position) //User is now nullable<br>    }   <br>}</pre><ul><li><a href="https://developer.android.com/reference/android/arch/paging/PagedList.Config">PagedList.Config</a> can be used to override the page-size ( amount of items to load in one page), initial load size (amount of items to load on the first page), prefetch distance (prefetch distance which defines how far ahead to load) and enable place holders(display null placeholders)</li><li>Placeholders when enabled, send nulls to the adapter when data is yet to be successfully pulled and can be redered to show loading to the user.</li></ul><h4>Code Sample (Reactive):</h4><pre>/* In ViewModel */<br>//Flowable or Observable<br>val concertList: Flowable&lt;PagedList&lt;Concert&gt;&gt; = RxPagedListBuilder(<br>        concertDao.concertsByDate(),<br>        /* page size */ 50<br>).buildFlowable(BackpressureStrategy.LATEST)</pre><pre>/* In activity or fragment */<br>viewModel.concertList.subscribe({flowableList -&gt; <br>    adapter.submitList(flowableList)<br>})</pre><h4>Network Pagination</h4><ul><li>Consider your local cache (database) as the source of truth.</li><li>Whenever you run out of data locally or optionally on first load, ping the server, handle results and insert to database, which in-turn updates the UI.</li><li>Use <a href="https://developer.android.com/reference/android/arch/paging/PagedList.BoundaryCallback">BoundaryCallback</a> to auto trigger network load when the local runs out of data</li></ul><h4>Samples</h4><ul><li><a href="https://github.com/googlesamples/android-architecture-components/tree/master/PagingSample">googlesamples/android-architecture-components/PagingSample/</a></li><li><a href="https://github.com/googlesamples/android-architecture-components/tree/master/PagingWithNetworkSample">googlesamples/android-architecture-components/PagingWithNetworkSample/</a></li></ul><h3>WorkManager</h3><p><em>The WorkManager API makes it easy to specify deferrable, asynchronous tasks and when they should run</em></p><ul><li>The jobs will be <strong>guaranteed</strong> to run in the range as well <strong>constraints</strong> specified.</li><li>Can <strong>chain jobs</strong> to run sequentially based on previous results or parallely.</li><li>doWork() (responsible for performing the intended request) by-default <strong>runs on the background thread</strong>.</li><li>Work can be:</li><li><a href="https://developer.android.com/reference/androidx/work/OneTimeWorkRequest">OneTimeWorkRequest</a> — Request for non-repeating work.</li><li><a href="https://developer.android.com/reference/androidx/work/PeriodicWorkRequest">PeriodicWorkRequest</a> — Request for repeating work.</li><li><a href="https://developer.android.com/reference/androidx/work/Constraints">Constraints</a> can be around — Network, Battery, Idle and Storage on device</li><li>Can observe the status of the work request as a LiveData of <a href="https://developer.android.com/reference/androidx/work/WorkStatus">WorkStatus</a></li><li>In chaining, output of one or more jobs can become the input of another.</li><li>A job can be cancelled by calling the cancelWorkById(id)</li><li>A job can be attached a tag to make debugging easier using addTag() on WorkRequest.</li><li>Tags can also be used cancel all the requests belonging to a particular tag.</li><li><strong>Periodic work can be scheduled only after 15 mins</strong></li><li>Periodic work cannot be chained.</li><li>Under the hood delegates and uses</li><li>JobScheduler (API 23+)</li><li>Firebase JobDispatcher (if app includes Firebase JobDispatcher)</li><li>AlarmManager + Broadcast Receivers</li><li>Provides a TestDriver to test the work and run synchronously</li><li>Currently in 1.0.0-alpha01</li><li>Has an <strong>additional Kotlin extensions</strong> library for Kotlin users</li></ul><h4>Articles</h4><ul><li><a href="https://android.jlelse.eu/exploring-jetpack-scheduling-tasks-with-work-manager-fba20d7c69bf">Exploring Jetpack: Scheduling tasks with Work Manager — Keval Patel</a></li><li><a href="https://android.jlelse.eu/exploring-jetpack-the-power-of-chains-in-the-workmanager-apis-30509ca4b2c">Exploring Jetpack: The power of chains in the WorkManager APIs — Keval Patel</a></li></ul><h3>App Bundle</h3><ul><li>An Android App Bundle is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play.</li><li>It uses Google Play’s new app serving model, called Dynamic Delivery. It will generate apk based on the user’s device configuration such as screen density, CPU architecture, locale etc. Your user downloads only resources required for his/her device.</li><li>There will be three apks:</li><li><strong>Base APK:</strong> This APK contains code and resources that all other split APKs can access and provides the basic functionality of your app.</li><li><strong>Configuration APKs:</strong> It includes resources for diffrent screen density, CPU architecture, locale etc.</li><li><strong>Dynamic feature APKs:</strong> These are the APKs that are not required at the install time but it will be downloaded and installed in real-time when the feature is required.</li></ul><h4>Requirements:</h4><ul><li>Android Studio 3.2 — Canary 14+. Android Studio 3.2 provides an option to <a href="https://developer.android.com/guide/app-bundle/configure">configure your project for Dynamic Delivery</a> while generating signed apk.</li><li>In order to use App Bundle feature, you must enroll in the <a href="https://support.google.com/googleplay/android-developer/answer/7384423?hl=en">App Signing</a> on Google Play console.</li></ul><p>Android Things is Google’s platform to support the development of Internet of Things devices. Which is now in 1.0 production ready version. This section has all Android Things related video what’s new, updates and best practises</p><h3><strong>Android Things</strong></h3><ul><li><a href="https://www.youtube.com/watch?v=e_PI_Npb3-U"><strong>What’s New ?</strong></a> : Learn more about the breadth of hardware reference designs, the operating system, building apps, device management, and support from chip vendors.</li><li><a href="https://www.youtube.com/watch?v=gkjV-TWLkIc&amp;t=875s"><strong>Device Provisioning and Authentication</strong></a> : This talk will discuss how to support authentication, provisioning from a mobile device, and device attestation.</li><li><a href="https://www.youtube.com/watch?v=PDBG9U-oNXY"><strong>Android Things Console</strong></a>: Android Things provides a powerful developer Console that manages your device deployments. Learn more about how to take your APKs and hardware configurations, and build them into system images, which can then be rolled out to all of your devices via over-the-air updates.</li><li><a href="https://www.youtube.com/watch?v=cyphkm5XluA"><strong>System On Modules</strong></a>: How to create your own SOM carrier boards, including creating the design from scratch, working with a fabrication company, assembly and testing, and taking it all the way to production.</li><li><a href="https://www.youtube.com/watch?v=zBpP2kxDa2M"><strong>Build Real Consumer Devices</strong></a> : This talk will walk through the journey of building consumer devices like Smart Displays using Android Things</li><li><a href="https://www.youtube.com/watch?v=dVtYVjGGYmE"><strong>Build effective OEM-level apps</strong></a> : As an Android Things OEM. How should you structure your code? Should you use activities or services? Should the code be running in the foreground or the background? Do you package all the code into one APK, or split components up into modules? Find answers to all of these questions and more with best practices for building OEM-level apps.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3924636b02bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>