<?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 Sumeet Devidan on Medium]]></title>
        <description><![CDATA[Stories by Sumeet Devidan on Medium]]></description>
        <link>https://medium.com/@smdevidan?source=rss-7b87cf286075------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YCgWQNEWBJ0dn0F_N0TJDw.jpeg</url>
            <title>Stories by Sumeet Devidan on Medium</title>
            <link>https://medium.com/@smdevidan?source=rss-7b87cf286075------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 17:00:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smdevidan/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[Being a Minimalist when it comes to code]]></title>
            <link>https://medium.com/helpshift-engineering/being-a-minimalist-when-it-comes-to-code-ffcc807886ea?source=rss-7b87cf286075------2</link>
            <guid isPermaLink="false">https://medium.com/p/ffcc807886ea</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sumeet Devidan]]></dc:creator>
            <pubDate>Sun, 03 Apr 2022 16:09:56 GMT</pubDate>
            <atom:updated>2022-08-05T04:29:05.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*6aD1QwEO-GoxiRPiwypzTQ.jpeg" /></figure><p>Minimal and efficient code is concise, to the point, less noisy, easier to maintain, debug, and onboard.</p><p>Developing a knack to delete/shrink code and still maintain the feature set sounds so intriguing. Aiming for minimal and concise code should be every software developer’s effort.</p><h3>How minimal code helps</h3><p>Being an Android library developer @ <a href="https://www.helpshift.com/">Helpshift</a> has made me realize that aiming for minimal and concise code helps us achieve solutions to many pain points:</p><ol><li><strong><em>Keeping library size to the minimum.</em></strong></li></ol><p>One of the parameters for clients to adopt our library is how much of an impact we cause on their app. This impact can be size, memory, CPU usage, network usage, etc.</p><p>Since we aim to achieve whatever functionality we want in the least amount of code, it helps us with having less impact on the client application size.</p><p>Aiming for least amount of code helps us in better designing and architecting the library code. It forces us to rethink and re-evaluate our design and architecture choices.</p><p>2. <strong><em>No dependency on other libraries.</em></strong></p><p>This is sounds counterintuitive, since having no dependency on any 3rd party library means implementing those features in-house and developing them from scratch. This actually helps us implement features to the bare minimum that we want and not deal with the verbosity of the feature set offered by any other 3rd party library. We may want a tiny set of features from a 3rd party library. But for that, we would have to import the entire library, understand its functioning, keep its memory and CPU usage in check, follow its updates and deal with breaking changes in the future. To shrink its usages, we would have to write ProGuard rules on top of everything.</p><p>Adding 3rd party dependencies also enforces our client applications to maintain those dependencies, which is a nightmare when any of the libraries clash around version requirements.</p><p>Developing these features in-house helps us avoid the dependency handling and version management nightmare altogether. It also helps us better understand internal concepts of Android and how to develop things from scratch. We can fine tune the feature implementation as and when we need. It ultimately helps us become better software developers.</p><p>3. <strong><em>Keeping performance/memory in check.</em></strong></p><p>Since we develop everything in-house, keeping performance/memory in check has become pretty easy. We can test every piece of code and fix it in which ever way we like. We don’t have to worry how a certain dependent 3rd party library is performing since we have none!</p><p>4. <strong><em>Easy maintenance and debugging.</em></strong></p><p>A concise and well-written codebase is easier to maintain and develop on.</p><p>Debugging also becomes easy. We know exactly what is happening since we don’t have any 3rd party dependency, the code is well modularized and well architected.</p><p>5. <strong><em>Method count limitations in Android.</em></strong></p><p>Android limits method reference count in a single “dex” file to 64k.</p><p>Android build systems have now developed elegant solutions to this problem, but we should anyway try to avoid hitting this limit and we, being a library, should take extra care for it.</p><p>6. <strong><em>Easier for new members in the team to onboard</em></strong>.</p><p>Imagine a new member in your team quickly catching up to the codebase and starts contributing at the earliest, wouldn’t that be the best use of everyone’s time :)</p><h3>How to achieve it</h3><p>A few tips:</p><ol><li>After designing/architecting a solution for any feature, ask yourself, is there a better way?<br>Iterating on design helps to get to a better solution but do ensure to stop yourself at some point in the iteration.</li><li>Do I really need that 3rd party library to implement a feature?<br>If you have minimal requirements, for example fetching an image and showing it on UI, ask yourself, can you implement this in-house? Will it be worth it? How hard can it be?</li><li>Modularize your code.<br>Have a “utility” module, first and foremost! That will ensure you reuse the utility functions and never rewrite/duplicate them. <br>Modularization also helps to better segregate the code in separate verticals, independent of each other. They can be tested and maintained isolated.</li><li>Use static code inspection tools.<br>Sonarqube, for example, reports the code duplicity you have across your codebase, critical/blocker code issues etc. It enforces you to follow some standard code practices.</li><li>Leave things better than you found them.<br>When you touch any part of the code, act like an owner and resolve any issues that you find. It is subject to many other things like timelines and side effects, but it is always good practice to know those side effects. It makes you better acquainted with the codebase.</li><li>Don’t overcomplicate stuff (unless required).<br>Simple things work just fine if it satisfies your use cases. Just because you read some article somewhere, don’t start implementing it. :)</li></ol><h3>A few examples</h3><p><strong><em>Core network code</em></strong></p><p>The below code handles our network calls entirely, no fancy stuff is needed in and around it. Easy to maintain, understand, and satisfies all our use cases. The caller takes care of concurrency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67c9eefd0cfd3c19d0acf9b9f400f042/href">https://medium.com/media/67c9eefd0cfd3c19d0acf9b9f400f042/href</a></iframe><p><strong><em>Key-Value store:</em></strong></p><ul><li>Can easily encapsulate around SharedPreferences in Android.</li></ul><p><strong><em>SQLite Databases:</em></strong></p><ul><li>Only implement CRUD operations in the database class.</li><li>Handle filtering/conditional logic and data manipulation outside database classes, say in business logic layer. We try to avoid complicated SQLite queries.</li><li>With Kotlin higher-order functions, we can also wrap transactions and error handling in a common class.</li></ul><p><strong><em>File downloading:</em></strong></p><p>The below code handles file downloading in the simplest way. No fancy stuff in/around it. The caller takes care of concurrency.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc13d2c7e69878937f3826a038eb8a1c/href">https://medium.com/media/dc13d2c7e69878937f3826a038eb8a1c/href</a></iframe><p><strong><em>Image caching:</em></strong></p><ul><li>A simple combination of the file downloader above with LRU cache and storing URL key/image file path in our Key-Value store.</li><li>Lazy load the in-mem LRU cache.</li><li>Show a placeholder image until it is downloaded.</li></ul><p><strong><em>Queuing public events/APIs:</em></strong></p><ul><li>As a library, we work almost entirely off the main thread. Only on our UI component do we access the main thread.</li><li>The below code helps us queue all public APIs and events that we expose in the library on a serial executor. This ensures serial execution of APIs/events, as intended by the client application, but completely off the main thread.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/730d2145405f5aa05f5d0bc4a21b3960/href">https://medium.com/media/730d2145405f5aa05f5d0bc4a21b3960/href</a></iframe><p>The above examples of in-house implementation of some common features helped us save adding dependency on 3rd party libraries, figure out a minimal viable solution, maintain simplicity in code and modularize as per our needs.</p><p>Always keep looking to delete unnecessary code!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ffcc807886ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/being-a-minimalist-when-it-comes-to-code-ffcc807886ea">Being a Minimalist when it comes to code</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing WebView load time in Helpshift’s SDK X]]></title>
            <link>https://medium.com/helpshift-engineering/optimizing-webview-load-time-in-helpshifts-sdk-x-99dde646d026?source=rss-7b87cf286075------2</link>
            <guid isPermaLink="false">https://medium.com/p/99dde646d026</guid>
            <category><![CDATA[webview]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sumeet Devidan]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 09:16:15 GMT</pubDate>
            <atom:updated>2021-12-22T09:16:15.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*yN5SLjQxqedhmnFeiD1gdQ.jpeg" /></figure><p>WebViews in Android can be quite a pain when measured on performance and speed. It often takes a lot of time to fetch, cache and load the web content. To top it off, the caching mechanism provided by Android does not work consistently across OS versions and different device manufacturers.</p><p>With SDK X, we moved the Help Center and Chat sections to WebViews, to update features over the air. We also wanted to ensure optimal performance in terms of speed and smooth UX. That required us to develop our own caching mechanism to load static web content instantly after the first fetch.</p><h3>Why do we need to write custom cache in WebView ?</h3><p>The default caching options in Android do not work consistently across OS versions and various device OEMs.</p><p>Our testing with <em>Websettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK). </em>did not give us satisfactory results across device/OS range.</p><p>We were hitting many inconsistencies regarding content being loaded, cache expiry and fetching expired/updated content.</p><p>Given these problems, we decided to write our own caching mechanism to suite our needs.</p><h3>Caching Mechanism</h3><p>A good caching mechanism needs crisp answers to the following questions:</p><ol><li>What to cache?</li><li>How to cache?</li><li>How to invalidate the cache?</li></ol><p><strong>What to cache?</strong></p><p>Since we have decided to develop our own caching mechanism, why not take it to the next step and dynamically update what is to be cached?</p><p>We fetch a configuration from our backend to dictate which web urls can be cached and the corresponding expiry time as well.</p><p>This configuration itself is updated every 24 hours, this allows us to update the web urls to be cached over the air. That essentially means that we can tune caching mechanism from backend.</p><p>Config example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6292dee1e49ca89642fc239985c6ad8/href">https://medium.com/media/c6292dee1e49ca89642fc239985c6ad8/href</a></iframe><p><strong>How to cache?</strong></p><p>All network requests made by a webview in Android can be intercepted by registering a <em>WebViewClient</em>.</p><p>Overriding the “<em>shouldInterceptRequest</em>” method gives us an interception point for all outgoing network requests. We hook in this place to check if the request urls match the patterns provided in the configuration file. <em>Note that all the invocations of “shouldInterceptRequest” method are on non-UI thread, meaning we can do a synchronous network call on this thread.</em></p><p>We only intercept GET requests, all other request go through without any manipulation.</p><p>Following gist helps understand the caching mechanism:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbaa9d4aca6a23dfd889ecbbc1feac5f/href">https://medium.com/media/bbaa9d4aca6a23dfd889ecbbc1feac5f/href</a></iframe><p>Following is the caching algorithm in brief:</p><ol><li>Read config file from disk, if available. Fetch the config again and store on disk if it is expired.</li><li>When we intercept “shouldInterceptRequest”, check if it is a GET request and the url path exists in our config.</li><li>Check if the file against this url path is already available on disk and the cache interval is not expired. If not expired, then serve this cached file as the response. We are done !</li><li>If cache is expired or file isnt available then download this file. While downloading this file, also store the mimeType and the headers in the response. These will be used later to create a WebResourceResponse object.</li><li>Update the corresponding ttl values for the matched url if the file is successfully fetched and stored.</li><li><em>Always fallback to network if anything during this process fails. This way we make sure to load webview with correct content, no matter what.</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*Mw9eJfFYhimL9_UUsDpFsQ.png" /></figure><p><strong>How to invalidate the cache ?</strong></p><p>Invalidating cache is quite tricky sometimes.</p><p>For us, invalidation works in 3 stages:</p><ol><li>The file itself is deleted from app’s sandbox.</li></ol><p>— The user could delete the app’s cache manually to save space. This means that the cached file is deleted and we need to refetch it.</p><p>2. The ttl for that cache resource has expired.</p><p>— Each cached resource also has a ttl, which means at some point of time the resource will expire and we will fetch it again, for sure.</p><p>3. The request url has upgraded wrt path/query params.</p><p>— It could also happen that a new version of that cached resource is available. For this case, we store the ttl for a given url against its entire path including the query params. That helps us invalidate the cache as soon as the version for the url changes.</p><p>For example:</p><p>Cache entry “/content/abc.js?v=1.1” expires when we get “/content/abc.js?v=1.2” in the url path to be loaded in the webview.</p><p>This is because we will not have any cache entry for “/content/abc.js?v=1.2” and hence we will have to fetch it mandatorily.</p><p><strong>How to clean up invalidated cached files?</strong></p><p>On Application start, delete files from the cache folder which ever are not modified in last 1 month. Keeping it simple.</p><p>Keeps cached files from accumulating over time!</p><h3>Results</h3><p>Without caching: Loads in ~6 seconds</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1KsGQ7Fk_TDKZTvfAjXN_Q.gif" /></figure><p>With caching: Loads in ~2 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Nxrk_IR3TKVcHPVYGWcjMQ.gif" /></figure><p>Simple caching techniques gives us 65–70% better loading time !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99dde646d026" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/optimizing-webview-load-time-in-helpshifts-sdk-x-99dde646d026">Optimizing WebView load time in Helpshift’s SDK X</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping File Descriptors (FD’s) in check on Android]]></title>
            <link>https://medium.com/helpshift-engineering/keeping-file-descriptors-fds-in-check-on-android-24778973a173?source=rss-7b87cf286075------2</link>
            <guid isPermaLink="false">https://medium.com/p/24778973a173</guid>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[lake]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[file-descriptor]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sumeet Devidan]]></dc:creator>
            <pubDate>Mon, 13 Jul 2020 13:17:55 GMT</pubDate>
            <atom:updated>2021-09-28T11:53:18.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gHMBYAlf7SX6eltDUi6gDw.jpeg" /><figcaption>Keeping it in limits</figcaption></figure><h4>What is a FileDescriptor?</h4><p><em>A file descriptor is an abstract indicator used to access a file or other input/output resource, such as a pipe or network socket.</em></p><p>Any I/O connection is channeled via a FileDescriptor object.</p><p>In Android, all I/O operations like Files/Sockets/Database connections/network connections/Handlers/Loopers/Resources open a FileDescriptor and keep it open until this connection is explicitly or implicitly closed.</p><h4>Why should we be concerned?</h4><p>Each Android app runs in its own sandboxed process. An app can spawn multiple processes, but they are also sandboxed, meaning, 2 processes spawned from the same app would need to use IPC to communicate with each other.</p><p>Android allows maximum <strong>1024</strong> FDs open for a single process. Some devices may even lower this threshold to 512. Any process exceeding this limit is immediately killed with:</p><pre>java.lang.RuntimeException: Too many open files</pre><p>If we keep file streams open, use too many sockets without closing them, create too many Handlers etc., some or the other day we might run into this problem.</p><p>The weird part is, this error can lead to many other seemingly unrelated errors. For example:</p><pre>android.database.cursorwindowAllocationException:CursorWindow could not create cursorwindow from binder</pre><pre>java.lang.OutOfMemoryError: pthread_create (1040KB stack) failed: Try again</pre><pre><br>sqlite::Exception: unable to open database file</pre><p>Many of these errors are non-intuitive and seem remotely impossible to relate/connect with Too many files open error but they are sometimes a direct result of too many FD’s being kept open.</p><p>These errors are hard to debug, specially when they are observed in production only. With crash reports only indicating an unrelated error (as shown above), the underlying cause might as well be<em> too many open FDs</em>. It is better to be safe in development stage itself rather than scratching our heads with errors in production.</p><h4>What can we do?</h4><p>For starters, let us make it a habit to <em>always</em> close any resource that we use. We should not be dependent on <em>Garbage Collector</em> to recycle/close open FD connections as it may not always work out. Why take any chance when simple habits can prevent it?</p><ul><li>Use Kotlin’s use function to ensure streams are closed after use.</li><li>Use Java’s try-with-resources to ensure streams are closed properly.</li><li>Always disconnect a HttpURLConnection object after network calls are completed.</li><li>Use limited Handler/Looper threads. Each Looper.prepare() opens a FileDescriptor.</li><li>Always keep number of running threads in check. Put an upper limit on threads spawned via ExecutorServices.</li><li>Close WebSockets after use.</li><li>Ensure SQLiteDatabaseHelper connections are singleton objects. Each helper object holds an open FD to the underlying sqlite db file.</li><li>Ensure no memory leaks in any workflow of your app.</li></ul><h4>Simple process to follow</h4><ul><li>Include a test case for open FD limits in your QA checklist. Follow checklists religiously.</li><li>Use the app for some time, run through various work flows of your app.</li><li>After some time, check for open FD count as described below.</li><li>A count of 100–150 is acceptable, anything above 300 is definitely a resource/FD leak.</li><li>Unfortunately, this check has to be done manually since we need root permissions to run shell commands on android device/emulator.</li></ul><p>Open FileDescriptors can be checked via simple commands in adb shell</p><blockquote>adb shell</blockquote><blockquote>su</blockquote><blockquote>ls -l /proc/${YOUR_APP_PID}/fd | wc -l</blockquote><p>I would have loved to automate this in an automation suite of tests as a <em>TestRule, </em>but unfortunately running these shell commands from an app requires setting up a rooted device or emulator.</p><p>Keep those open FD’s in check and stay safe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24778973a173" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/keeping-file-descriptors-fds-in-check-on-android-24778973a173">Keeping File Descriptors (FD’s) in check on Android</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Selectable Pills on Android]]></title>
            <link>https://medium.com/helpshift-engineering/dynamic-selectable-pills-on-android-f7a64bb15f61?source=rss-7b87cf286075------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7a64bb15f61</guid>
            <category><![CDATA[adjustable]]></category>
            <category><![CDATA[android-ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dynamics]]></category>
            <category><![CDATA[programatically]]></category>
            <dc:creator><![CDATA[Sumeet Devidan]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 09:13:22 GMT</pubDate>
            <atom:updated>2021-12-07T07:43:56.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHJdVbF_gW0RfrqFwejbQQ.jpeg" /><figcaption>Adjusting in available space</figcaption></figure><p>With server-driven content, there is a need to render content dynamically. Static or pre-defined layouts just act as a placeholder but do not help for achieving adaptable UI/UX.</p><p>A small part of dynamically inflating layouts is to adapt to user’s device specs for adjusting the content gracefully in the available space on screen. The attempt is to not make user look out for available options when we can adapt our data into available space.</p><p>In this article, we are going to see how to render an array of variable length clickable pills adapting to device specs.</p><p>First, let us see what we are going to make:</p><ul><li>Clickable pills with variable length text as dictated by our <em>server.</em></li><li>Adjusting the pills on UI based on available screen width.</li><li>Moving the overflowing pills in vertically available space to keep content scrollable.</li><li>Adapting to screen width based on device orientation</li></ul><p>Observe the pill titled “Green”, which adjusts below or on the same line depending on width available for the component to expand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*SgB7tu4exXhaY-biu2376g.gif" /></figure><h3>The Pill</h3><p>The pill is a drawable 9 patch PNG image. It is just a hollow/transparent outline image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/1*mpyOqH2iDorZC1kV3jmSnA.png" /><figcaption>Pill 9 patch png</figcaption></figure><p>This PNG will be used as a background to our dynamic text content.</p><h3>Text Content</h3><p>The backend dictates the text content. It can be any length text. We will be generating pills at runtime and adjusting them based on available screen width.</p><h3>Per Pill layout</h3><p>We will need a container layout to hold per pill item. This layout will contain the text and the background as the pill PNG drawable. We will essentially inflate this pill multiple times depending on the number of items we want to display.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b67882bb2b1e1bce78a8e79953ee06ce/href">https://medium.com/media/b67882bb2b1e1bce78a8e79953ee06ce/href</a></iframe><h3>Adjusting with the available width</h3><p>The core requirement here is to adjust all the pills on the visible screen with graceful UX. The user wouldn’t need a carousel to scroll through.</p><p>We will need certain elements in-hand to work this:</p><ul><li><em>Context</em> to get device metrics.</li><li>Max available screen width scale factor to indicate what percentage of screen width we can expand into. Ex. 80% of screen width.</li><li>A container layout containerView to inflate all our items into.</li><li>Per pill item layout to inflate.</li><li>Text view Id in the per pill layout to fill in the text.</li><li>List of titles for the pills as given by our <em>server</em>.</li><li>A click listener for pills.</li></ul><p>Algorithm to adjust pills based on available width:</p><ol><li>Get device metrics, figure out how much width we can occupy, taking into consideration the scale factor provided.</li><li>Maintain a list of LinearLayout layouts. This list will hold all the LinearLayouts we create programmatically.</li><li>Start a loop to inflate pills layouts and measure the elements that we will add programmatically.</li><li>Make a LinearLayout oriented horizontally horizontalLayout. This will be used to add pills one by one until we occupy the maximum space allowed.</li><li>Inflate pill layout for each item and set title string in the text view.</li><li>Add this layout to the horizontalLayout we created above.</li><li>Measure horizontalLayout after each addition of pill. Measure gives us a good idea for how much this element is going to occupy on screen.</li><li>If measure exceeds the max available width, then remove the last item added and add horizontalLayout to layouts .</li><li>Continue the loop until all items are accounted for.</li><li>Add layouts to containerView .</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1587c8dcf7abcd62ac6bffa53de0c409/href">https://medium.com/media/1587c8dcf7abcd62ac6bffa53de0c409/href</a></iframe><p>This process will adjust horizontal addition of pills till we reach the max available width, create a new horizontal layout for remaining items until all items are added and finally add the whole programmatically created layout to a container that we specify.</p><p>The key here is to measure the layout for how much space the items will occupy.</p><p>And that&#39;s it!<br>We have an adjustable layout that can render server-driven data and adapt gracefully to the available screen size.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7a64bb15f61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/dynamic-selectable-pills-on-android-f7a64bb15f61">Dynamic Selectable Pills on Android</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android : Fixing unexpected SQLite Exceptions]]></title>
            <link>https://medium.com/helpshift-engineering/android-fixing-weird-sqlite-exceptions-f9bc9e36fbbe?source=rss-7b87cf286075------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9bc9e36fbbe</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[crash]]></category>
            <category><![CDATA[sqlitediskio]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[sqlitediskioexception]]></category>
            <dc:creator><![CDATA[Sumeet Devidan]]></dc:creator>
            <pubDate>Mon, 09 Oct 2017 09:44:12 GMT</pubDate>
            <atom:updated>2021-09-23T10:29:10.741Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2A-PkoEZb1Q0pBeRG5N3Q.jpeg" /></figure><p>SQLite exceptions can be tricky to debug and difficult to fix, especially when it only happens in live production apps (as always is the case :) ). SQLite for Android involves a lot of complexity behind the scenes, and it does an impressive job of exposing minimal API’s for a developer to work with. Most of the time, we get away with using these APIs’s and making it work as expected.</p><p>I recently came across some weird issues in SQLite database operations. The code is live on millions of devices as an SDK, it is battle tested and extra safe guarded whereever required for a seamless UX, but such issues cannot be foreseen.</p><h3><strong>SQLiteDiskIOException</strong></h3><p>With a new stable release, SQLite Database started throwing SQLiteDiskIOException in production. As generally is the case, we never encountered this in our QA nor did the developers who integrated it. Luckily, we had our own crash reporting in place exactly for such a scenario.</p><p>This error was a known issue for Android 4.x devices and was fixed with 4.2.2 update (I think). After going through the error reports thousands of times, I had no clue for what could be wrong. The reported errors were from all OS versions and all kinds of devices. This error reporting essentially led us no where but did help in getting the essence of the issue. So, I started looking at the code for what changed between the latest release and previous stable releases.</p><p>Even after a line by line code inspection, I found no good indication that could point to a probable SQLite error. I started hitting arrows in the dark by guessing what could go wrong at the system level from the code that we had added/modified. And finally, I hit this piece of code, with all my gut feeling I knew something had to be wrong here since this was the only place where our latest code used system level APIs/functions.</p><blockquote>Thread retryThread = new Thread(new Runnable() {<br> @Override<br> public void run() {<br> Looper.<em>prepare</em>();<br> // Code <br> Looper.<em>loop</em>();<br> }<br>}, &quot;RetryThread&quot;);<br><br>retryThread.start();</blockquote><p>The error seems trivial and with no side effects here, i.e, not calling “<strong>Looper.myLooper().quit()</strong>” after the thread is done doing its business, but it has a huge impact if this piece of code runs frequently. Each <strong>Looper.prepare()</strong> invocation holds a file descriptor and keeps the thread alive. Meaning unless we call <strong>Looper.myLooper().quit()</strong>, the thread as well as the file descriptor are held by it. Here is the catch, each process in Android (essentially Linux) gets a maximum limit of holding 256 file descriptors alive at any point of time. Some systems may extend it upto 1024.</p><p>We can check these stats from the device at app runtime via ADB with following commands:</p><p>Check the number of open file descriptors:</p><blockquote>ls -l proc/&lt;pid of app&gt;/fd</blockquote><p>App stats like threads, FDs, memory:</p><blockquote>cat proc/&lt;pid of app&gt;/status</blockquote><p>If we observe this data, we can see the max FD limits, the number of threads alive and the memory usages.</p><p>I confirmed my gut feeling by observing these stats every time I invoked the said piece of code above. With every invocation the FD’s count increased by one and the alive thread count increased by one. With this finding, if the process runs out of out available FD’s limit then SQLite cannot get an FD to write to the disk with any CRUD operation and hence all SQLite operations fail after some point of time.</p><p>Just by calling “<strong>quit</strong>” on the Looper instance fixed this !</p><p>So, a seemingly non-critical code change some where else affected completely independent SQLite operations. Interesting !</p><p>Always make sure to close streams, files, sockets, threads, HandlerThreads, Loopers, SQLite transactions, SQLite cursors, HTTP connections etc.</p><p>When hit with native code/OS level errors, always go back to the basics.</p><p>I hope I save hours/days/weeks of debugging for some one out there :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9bc9e36fbbe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/helpshift-engineering/android-fixing-weird-sqlite-exceptions-f9bc9e36fbbe">Android : Fixing unexpected SQLite Exceptions</a> was originally published in <a href="https://medium.com/helpshift-engineering">helpshift-engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>