<?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 ChandraSaiMohan bhupathi on Medium]]></title>
        <description><![CDATA[Stories by ChandraSaiMohan bhupathi on Medium]]></description>
        <link>https://medium.com/@b-chandrasaimohan?source=rss-3a2df6eb0d48------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZeGNvsHFYSUXAOCX</url>
            <title>Stories by ChandraSaiMohan bhupathi on Medium</title>
            <link>https://medium.com/@b-chandrasaimohan?source=rss-3a2df6eb0d48------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 12:19:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@b-chandrasaimohan/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[Linked List in Kotlin]]></title>
            <link>https://medium.com/swlh/linked-list-in-kotlin-c5ec8a99c9c5?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ec8a99c9c5</guid>
            <category><![CDATA[linked-lists]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Mon, 16 Aug 2021 18:45:30 GMT</pubDate>
            <atom:updated>2021-08-16T18:45:30.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*DyCeFHcdPmFiBwjw.jpg" /></figure><h3>Linked List in Kotlin</h3><h3>1.Before you begin:</h3><p>In this blog we will learn how to implement Linked list in Kotlin and some basic operations that can be performed on Linked List.</p><p><strong>Introduction:</strong></p><p>Linked List is a type of Linear Data Structure that is the second most used data structure after the array, which allocates memory dynamically at run time that is it doesn’t require any size initialization as in the case of an array.</p><p>Linked List stores data in the form of nodes, which is divided into two parts, the first part stores the data and the second part points to the next node by storing the address of that node. In the simplest form, each node is composed of data and a reference to the next node in the sequence.</p><p>Some of the basic operations that can be performed in Linked List are below:</p><p>(1) Add</p><p>(2) Delete</p><p>(3) Find</p><p>The first element in the linked list will be called “Head” and the last element in the linked list will be called “Tail”.</p><p><strong>Prerequisites:</strong></p><ul><li>Experience with Kotlin syntax and basic knowledge of Linked List</li></ul><p><strong>What you’ll do ?</strong></p><p>A sample application that demonstrates a linked list and its basic operations .</p><h3>2.Getting Setup :</h3><p><a href="https://github.com/chandragithub2014/LeetCodeAlgorithms/blob/master/app/src/main/java/colruyt/android/techgig/SingleLinkedLst.kt">LeetCodeAlgorithms/SingleLinkedLst.kt at master · chandragithub2014/LeetCodeAlgorithms</a></p><p><strong>Explanation:</strong></p><p>Step 1: Create a Node to maintain value and reference to next node</p><p>The above step is implemented using data class and overrided toString() method to print the linked list.</p><p>Code Sample:</p><pre>data class Node&lt;T&gt;(var value: T, var next: Node&lt;T&gt;? = null) {<br>    override fun toString(): String {<br><br>        return if (next != null) {<br>            &quot;$value -&gt; ${next.<em>toString</em>()}&quot;<br>        } else {<br>            &quot;$value&quot;<br>        }<br>    }<br>}</pre><p>Step 2: Initialization of Head and Tail nodes</p><p>Every linked list will have a Head and a Tail nodes. If there is a single node, then the node itself will be Head and Tail.</p><p>Initialize the Head and Tail nodes to null and size variable that keeps track of size of linked list.</p><pre>private var head: Node&lt;T&gt;? = null<br>private var tail: Node&lt;T&gt;? = null<br>private var size = 0</pre><p>Step 3: Add a node to Head</p><pre>fun push(value: T) {<br><br>    head = Node(value = value, next = head)<br>    if (tail == null) {<br>        tail = head<br>    }<br>    size++<br>  <br>}</pre><p>The above always adds new node to Head. A new Node is created and assigned to “head” and if tail is null then initialize tail to “head” . Always increment the size variable to keep track of size of linked list.</p><p>Step 4: To add a Node to the Tail</p><p>In this step a node is added to Tail which means appended to the end of the linked list</p><pre>fun addAtTail(value: T) {<br>    if (isEmpty()) {<br>        push(value)<br>        return<br>    }<br>   <br>    tail?.next = Node(value = value)<br><br>   <br>    tail = tail?.next<br><br>    size++<br>}</pre><p>There is an isEmpty() that keeps track of size of list, it checks whether list is empty or not.</p><p>If the list is empty we just create new node which can be created by calling push() method</p><p>If there is already some value to the tail, we will just point “next” of the current tail to newly created node and update the tail to newly created node.</p><p>Always increase the size</p><p>Step 4: Fetch value of linked list based on index</p><p>In this step , we fetch value of linked list based on index provided. We traverse through the entire list till we reach the index and retrieve value from node at that index.</p><p>If the index provided is greater than the size of the list , we return -1 as no node exists with that index.</p><pre>fun get(index: Int): Int? {<br><br>    var currentNode = head<br>    var currentIndex = 0<br>    return if(index &gt;= size) {<br>        -1<br>    } else{<br>    <br>        while (currentNode != null &amp;&amp; currentIndex &lt; index) {<br>            currentNode = currentNode.next<br>            currentIndex++<br><br>        }<br>        currentNode?.value.<em>toString</em>().<em>toInt</em>()<br><br><br>    }<br><br><br>}</pre><p>Step 5: Add a node at specific index in the linked list</p><p>In order to achieve this we traverse the list till we reach the index and just point the next reference of newly created node to next node in that list and the previous node’s (node at given index) next to newly created node.</p><p>If the size of index is greater than size of list , just add node to tail</p><p>If the index is 0, then add the node to the head .</p><pre><strong>fun addAtIndex(index: Int, `val`: T)</strong> {<br>var currentNode = head<br>    var newNode:Node&lt;T&gt;? = null<br>    var previousNode:Node&lt;T&gt;? = null<br>    var currentIndex = 0<br>   if(index &gt;= size){<br>      addAtTail(`val`)<br><br>   }else if(size &gt; 0 &amp;&amp; index == 0){<br>      push(`val`)<br>    }<br>   else {<br>       while (currentNode != null &amp;&amp; currentIndex &lt; index) {<br>           previousNode = currentNode<br>           currentNode = currentNode.next<br>           currentIndex++<br>       }<br>       newNode = Node(value = `val`, next = currentNode)<br>       previousNode?.next = newNode<br>       size++<br>   }<br><br><br>}</pre><p>Step 6: Delete a node at index</p><p>A method will be provided to delete a node at specific index.</p><p>If index is zero:</p><p>We need to check 2 conditions whether there is only one node in list or there are multiple nodes.</p><p>If the size of list is 1 , just make that node as null, probably head</p><p>If the size is greater than 1 and index is 0,we need to point head to next node and make current head to null.</p><p>The other condition is we traverse to that index and change the references of its previous and next nodes by making the node at index to null.</p><p>The last condition , if the index that we need to delete is tail, just set the previous node to tail and make current tail as null.</p><p>Also we decrement the size variableof list as we are deleting a node from the list.</p><pre>fun deleteAtIndex(index: Int) {<br>    // 1<br>    var currentNode = head<br>    var currentIndex = 0<br>    var previousNode: Node&lt;T&gt;? = null<br>    if (index &lt; size) {<br>        if (index == 0) {<br>            if (size &gt; 1) {<br>                head = currentNode?.next<br>                currentNode?.next = null<br>                size--<br>            } else if (size == 1) {<br>                currentNode = null<br>                size--<br>            }<br>        } else {<br>            // 2<br>            while (currentNode != null &amp;&amp; currentIndex &lt; index) {<br>                previousNode = currentNode<br>                currentNode = currentNode.next<br>                currentIndex++<br><br>            }<br>            previousNode?.next = currentNode?.next<br>            currentNode?.next = null<br>            if(previousNode?.next == null){<br>                tail = previousNode<br>            }<br>            size--<br>        }<br><br><br>    }<br>}</pre><p>We create a class called linked list and include all these methods in that class.</p><p><strong>Congratulations:</strong></p><p>In this blog we have covered the basic operations of implementing single linked list in Kotlin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ec8a99c9c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/linked-list-in-kotlin-c5ec8a99c9c5">Linked List in Kotlin</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Runtime permissions with AndroidX RequestPermission contract — simple sample]]></title>
            <link>https://b-chandrasaimohan.medium.com/android-runtime-permissions-with-androidx-requestpermission-contract-simple-sample-52fb83990232?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/52fb83990232</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[runtime-permissions]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 17:35:06 GMT</pubDate>
            <atom:updated>2021-08-11T14:17:57.438Z</atom:updated>
            <content:encoded><![CDATA[<h4>Android Runtime permissions with AndroidX RequestPermission contract — simple sample</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*m043r636-O1gVMGW.jpg" /><figcaption>Android Runtime permissions</figcaption></figure><h3>Android Runtime permissions with AndroidX RequestPermission contract — simple sample</h3><h3>1.Before you begin:</h3><p>In this blog we will learn how to implement Android runtime permissions and how to declare them if app is installed on devices that runs Android 6.0 (API level 23) or higher .</p><p>use the <a href="https://developer.android.com/reference/androidx/activity/result/contract/ActivityResultContracts.RequestPermission"><strong>RequestPermission</strong></a> contract, included in an AndroidX library, where we allow the system to manage the permission request code rather than handling with callbacks.</p><p><strong>Introduction:</strong></p><p>App permissions help support user privacy by protecting access to the following:</p><ul><li><strong>Restricted data</strong>, such as system state and a user’s contact information.</li><li><strong>Restricted actions</strong>, such as connecting to a paired device and recording audio.</li></ul><p><strong>Types of permissions:</strong></p><ol><li>Install-time permissions</li><li>Normal permissions</li><li>Signature permissions</li><li>Runtime permissions</li></ol><p>In this blog we will be discussing on runtime permissions</p><p><strong>What are Runtime permissions?</strong></p><p>Runtime permissions, also known as dangerous permissions, give your app additional access to restricted data, and they allow your app to perform restricted actions that more substantially affect the system and other apps. Therefore, you need to <a href="https://developer.android.com/training/permissions/requesting">request runtime permissions</a> in your app before you can access the restricted data or perform restricted actions. When your app requests a runtime permission, the system presents a runtime permission prompt</p><p>Many runtime permissions access <em>private user data</em>, a special type of restricted data that includes potentially sensitive information. Examples of private user data include location and contact information.</p><p><strong>Prerequisites:</strong></p><ul><li>Experience with Kotlin syntax, including lambdas.</li><li>A basic understanding of Navigation component, permissions, Android Fragments, Activities</li></ul><p><strong>What you’ll do ?</strong></p><p>A sample application with below two screens that demonstrates single/multiple runtime permissions:</p><ol><li><strong>Launch Camera screen : </strong>This Fragment demonstrates providing camera permission at runtime and allows to launch camera when granted permissions. This screen allows to navigate to next screen.</li><li><strong>Contacts Screen: </strong>This Fragment demonstrates accessing multiple permissions at runtime and allows to read/write contacts from device when granted permissions.</li></ol><h3>2.Getting Setup :</h3><p><a href="https://github.com/chandragithub2014/PermissionsExample">GitHub - chandragithub2014/PermissionsExample: Runtime permissions sample</a></p><p>The code is available in the above Github repository.</p><blockquote>gitclone: <a href="https://github.com/chandragithub2014/PermissionsExample.git">https://github.com/chandragithub2014/PermissionsExample.git</a></blockquote><p><strong>3. Run the App:</strong></p><p>Screen shots for different scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OB6UH8OdDFszTzCL5gnR8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qyz5soaQM3MRVv2q6s5ltQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cn31YxEKr5ZgpBmJVYmvjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CmIa1ZDY06jGuHKcRFU0wA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9InbMU1gA6q43_sLCRvqew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_YQYROhm0RloIuMaQ4PdeQ.png" /></figure><p><strong>Explanation:</strong></p><p><strong>PermissionHelper:</strong></p><p>This class contains various methods to handle Runtime permissions. This class is single point of contact for all the runtime permission handling. Activity/Fragment can use this helper class to handle all the runtime permissions.</p><h3>Workflow for requesting permissions:</h3><ol><li><strong>Determine whether app was already granted permission:</strong></li></ol><p><strong>ContextCompat.checkSelfPermission():</strong> Checks if the user has already granted your app a particular permission.</p><p>This method returns either <a href="https://developer.android.com/reference/android/content/pm/PackageManager#PERMISSION_GRANTED">PERMISSION_GRANTED</a> or <a href="https://developer.android.com/reference/android/content/pm/PackageManager#PERMISSION_DENIED">PERMISSION_DENIED</a>, depending on whether your app has the permission.</p><p>This is the first method that needs to be called as part of checking whether particular permission is granted or not.</p><p>Code sample for the above step:</p><pre><strong>context?</strong>.requireContext()?.<em>let </em><strong>{<br>    </strong>ContextCompat.checkSelfPermission(<br>        <strong>it</strong>,<br>        manifestPermission<br>    )<br><strong>} </strong>== PackageManager.<em>PERMISSION_GRANTED </em>-&gt; {<br>    <em>println</em>(&quot;Permission Granted....&quot;)<br>  <br>}</pre><p>Where <strong>context </strong>is fragment’s context and <strong>manifestPermission</strong> is the permission to be checked whether it is granted or not and it should be declared in manifest file.</p><p>In this example “<strong>manifestPermission” is </strong>Manifest.permission.<em>CAMERA.</em></p><p><strong>2.Explain why app needs permission :</strong></p><p>In the above step if the <strong>“ContextCompat.checkSelfPermission()” </strong>method returns PERMISSION_DENIED, then call <strong>shouldShowRequestPermissionRationale().</strong>If this method returns true, show an educational UI to the user. In this UI, describe why the feature, which the user wants to enable, needs a particular permission.</p><p>In this app , I will be displaying an alert dialog that shows purpose of the permission. If users clicks “OK” button in alert dialog, I will be shown system permission dialog to either grant/deny permission.</p><pre>ActivityCompat.shouldShowRequestPermissionRationale(<br>    context?.requireContext() as Activity,<br>    manifestPermission<br>) -&gt; {<br>    <em>println</em>(&quot;Show Request Permission Rationale&quot;)<br>   //Display Alert Dialog.<br><br>}</pre><p><strong>3.Request permissions:</strong></p><p>After the user views an educational UI (Alert Dialog in our case) , if the users clicks “OK” button in Alert Dialog to again request the permission then Users see a system permission dialog, where they can choose whether to grant a particular permission to your app.</p><blockquote><strong>Important Note:</strong></blockquote><blockquote>Traditionally, we can manage a request code ourselves as part of the permission request and include this request code in your permission callback logic.</blockquote><blockquote><strong>Another option is to use the RequestPermission contract, included in an AndroidX library, where you allow the system to manage the permission request code for you. Because using the RequestPermission contract simplifies your logic, it’s recommended that you use it when possible.</strong></blockquote><blockquote><strong>RequestPermission contract :</strong></blockquote><blockquote>RequestPermission contract contains 2 classes:</blockquote><blockquote><strong>RequestPermission:</strong>To request a single permission</blockquote><blockquote><strong>2. RequestMultiplePermissions:</strong>To request multiple permissions at the same time.</blockquote><blockquote>In your activity or fragment’s initialization logic, pass in an implementation of <a href="https://developer.android.com/reference/androidx/activity/result/ActivityResultCallback">ActivityResultCallback</a> into a call to <a href="https://developer.android.com/reference/androidx/activity/result/ActivityResultCaller#registerForActivityResult(androidx.activity.result.contract.ActivityResultContract%3CI,%20O%3E,%20androidx.activity.result.ActivityResultCallback%3CO%3E)">registerForActivityResult()</a>. The ActivityResultCallback defines how your app handles the user&#39;s response to the permission request.</blockquote><blockquote>Keep a reference to the return value of registerForActivityResult(), which is of type <a href="https://developer.android.com/reference/androidx/activity/result/ActivityResultLauncher">ActivityResultLauncher</a>.</blockquote><blockquote>To display the system permissions dialog when necessary, call the <a href="https://developer.android.com/reference/androidx/activity/result/ActivityResultLauncher#launch(I)">launch()</a> method on the instance of ActivityResultLauncher that you saved in the previous step.</blockquote><p>Code sample for the above explained steps:</p><p><strong>RequestPermission:</strong></p><pre>private val <strong>requestPermissionLauncher</strong> =<br>    context.registerForActivityResult(<br>        ActivityResultContracts.<strong>RequestPermission()<br></strong>    ) <strong>{ </strong>isGranted: Boolean <strong>-&gt;<br>        </strong>if (isGranted) {<br>            Log.i(&quot;Permission: &quot;, &quot;Granted&quot;)<br>           <br>        } else {<br>            Log.i(&quot;Permission: &quot;, &quot;Denied&quot;)<br>        }<br>    <strong>}</strong></pre><p><strong>RequestMultiplePermissions</strong></p><pre>private val requestMultiplePermissionsLauncher = context.registerForActivityResult(<br>    ActivityResultContracts.<strong>RequestMultiplePermissions</strong>()<br>) <strong>{ </strong>permissions <strong>-&gt;<br>    </strong>permissions.entries.<em>forEach </em><strong>{<br>        </strong>Log.i(&quot;DEBUG&quot;, &quot;${<strong>it</strong>.key} = ${<strong>it</strong>.value}&quot;)<br>        if(<strong>it</strong>.value){<br>            <em>println</em>(&quot;Successful......&quot;)<br>           <br>        }<br>    <strong>}<br>}</strong></pre><p><strong>Using launch():</strong></p><pre>fun launchPermissionDialogForMultiplePermissions(<strong>manifestPermissions</strong>: Array&lt;String&gt;){<br>    <strong>requestMultiplePermissionsLauncher.launch(manifestPermissions)</strong><br>}</pre><pre> fun launchPermissionDialog(<strong>manifestPermission</strong>: String){<br>    <strong>requestPermissionLauncher.launch(<br>                 manifestPermission<br>             )</strong><br> }</pre><p>Where <strong>manifestPermissions</strong>: Array of Multiple permissions .(In our case it is READ and WRITE contacts)</p><p>where <strong>manifestPermission: </strong>Is the single permission (In our case it is CAMERA)</p><p><strong>PermissionHelper:</strong> Putting all discussed above in a single class</p><pre>class PermissionHelper(<strong>context: Fragment,permissionListener: PermissionListener</strong>) {<br><br>    private var context: Fragment? = null<br>    private var permissionListener : PermissionListener? = null<br><br>    init {<br><br>        this.context = context<br>        this.permissionListener = permissionListener<br><br><br>    }<br><br>    private val requestPermissionLauncher =<br>        context.registerForActivityResult(<br>            ActivityResultContracts.RequestPermission()<br>        ) <strong>{ </strong>isGranted: Boolean <strong>-&gt;<br>            </strong>if (isGranted) {<br>                Log.i(&quot;Permission: &quot;, &quot;Granted&quot;)<br>                <strong>permissionListener?.isPermissionGranted(true)</strong><br>            } else {<br>                Log.i(&quot;Permission: &quot;, &quot;Denied&quot;)<br>            }<br>        <strong>}<br><br>    </strong>private val requestMultiplePermissionsLauncher = context.registerForActivityResult(<br>        ActivityResultContracts.RequestMultiplePermissions()<br>    ) <strong>{ </strong>permissions <strong>-&gt;<br>        </strong>permissions.entries.<em>forEach </em><strong>{<br>            </strong>Log.i(&quot;DEBUG&quot;, &quot;${<strong>it</strong>.key} = ${<strong>it</strong>.value}&quot;)<br>            if(<strong>it</strong>.value){<br>                <em>println</em>(&quot;Successful......&quot;)<br>                <strong>permissionListener?.isPermissionGranted(true)</strong><br>            }<br>        <strong>}<br>    }<br><br>    </strong>fun checkForPermissions(manifestPermission: String) {<br>        when {<br>            context?.requireContext()?.<em>let </em><strong>{<br>                </strong>ContextCompat.checkSelfPermission(<br>                    <strong>it</strong>,<br>                    manifestPermission<br>                )<br>            <strong>} </strong>== PackageManager.<em>PERMISSION_GRANTED </em>-&gt; {<br>                <em>println</em>(&quot;Permission Granted....&quot;)<br>                permissionListener?.isPermissionGranted(true)<br>            }<br><br>            ActivityCompat.shouldShowRequestPermissionRationale(<br>                context?.requireContext() as Activity,<br>                manifestPermission<br>            ) -&gt; {<br>                <em>println</em>(&quot;Show Request Permission Rationale&quot;)<br>                permissionListener?.isPermissionGranted(false)<br>                <strong>permissionListener?.shouldShowRationaleInfo()</strong><br><br>            }<br><br>            else -&gt; {<br>                launchPermissionDialog(manifestPermission)<br>                <em>println</em>(&quot;Final Else....&quot;)<br>            }<br>        }<br>    }<br><br>    private var isDenied : Boolean  = false<br>    fun checkForMultiplePermissions(manifestPermissions: Array&lt;String&gt;) {<br><br>          for (permission in manifestPermissions) {<br>            context?.requireContext()?.<em>let </em><strong>{<br>                </strong>if (ContextCompat.checkSelfPermission(<br>                        <strong>it</strong>,<br>                        permission<br>                    ) == PackageManager.<em>PERMISSION_GRANTED<br>                </em>) {<br>                    <em>println</em>(&quot;Permission Granted....&quot;)<br>                    permissionListener?.isPermissionGranted(true)<br>                } else if (ActivityCompat.shouldShowRequestPermissionRationale(<br>                        context?.requireContext() as Activity,<br>                        permission<br>                    )<br>                ) {<br>                    isDenied = true<br>                //    requestMultiplePermissionsLauncher.launch(manifestPermissions)<br>                } else {<br>                    requestMultiplePermissionsLauncher.launch(manifestPermissions)<br>                }<br>            <strong>}<br>          </strong>}<br>           if(isDenied){<br>               permissionListener?.isPermissionGranted(false)<br>               permissionListener?.shouldShowRationaleInfo()<br>           }<br>    }<br><br><br>   fun launchPermissionDialogForMultiplePermissions(manifestPermissions: Array&lt;String&gt;){<br>       requestMultiplePermissionsLauncher.launch(manifestPermissions)<br>   }<br>    fun launchPermissionDialog(manifestPermission: String){<br>       requestPermissionLauncher.launch(<br>                    manifestPermission<br>                )<br>    }<br>}</pre><p>In the above we have two functions to handle single/multiple permissions as part of explanation purpose:</p><pre>fun checkForMultiplePermissions(manifestPermissions: Array&lt;String&gt;)<br>//Handles Multiple permissions logic</pre><pre>fun checkForPermissions() // To handle single permission logic</pre><p><strong>PermissionListener: </strong>This is the interface implemented in Fragment/Activity to display alert dialog(Display info about importance of permission) or open camera or allow read/write contacts when permission is granted.</p><pre>interface PermissionListener {<br>  fun   shouldShowRationaleInfo()<br>  fun   isPermissionGranted(isGranted : Boolean)<br>}</pre><p><strong>CameraPermissionsFragment:</strong></p><p>This the fragment that allows to access camera if permission is Granted. Also contains a button to navigate to next screen.</p><p>This is the place where we initialize PermissionHelper class and handle callbacks to display AlertDialog and launch camera.</p><p>Initialize Permission Helper:</p><pre>//Initialize PermissionHelper<br>permissionHelper =  PermissionHelper(this,this)</pre><pre>//Make call to singlePermission logic</pre><pre>permissionHelper.checkForPermissions(Manifest.permission.<em>CAMERA</em>)</pre><p><strong>ReadWriteContactsFragment:</strong></p><p>This Fragment demonstrates accessing multiple permissions at runtime and allows to read/write contacts from device when granted permissions.</p><pre>permissionHelper =  PermissionHelper(this, this)</pre><pre>permissionHelper.checkForMultiplePermissions(<br>    <em>arrayOf</em>(<br>        Manifest.permission.<em>READ_CONTACTS</em>,<br>        Manifest.permission.<em>WRITE_CONTACTS<br>    </em>)<br>)<br></pre><p>In the above code sample we initialize PermissionHelper and make a call to checkForMultiplePermissions() method which array of permissions declared in manifest.</p><p><strong>Congratulations:</strong></p><p>In this blogs, we have covered handling Runtime permissions in Android app using <strong>RequestPermission contract, included in an AndroidX library </strong>instead of handling ourselves to simplify permission handling with a simple example.</p><p>PermissionsHelper can be included in any project to handle runtime permissions and customize accordingly as per needs in callbacks.</p><p><strong>References:</strong></p><p><a href="https://developer.android.com/training/permissions/requesting">https://developer.android.com/training/permissions/requesting</a></p><p><a href="https://developer.android.com/guide/topics/permissions/overview#runtime">https://developer.android.com/guide/topics/permissions/overview#runtime</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52fb83990232" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parent Fragment with Navigation Component.]]></title>
            <link>https://b-chandrasaimohan.medium.com/parent-fragment-with-navigation-component-1dbe83f3ae15?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/1dbe83f3ae15</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[fragments]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 19:04:31 GMT</pubDate>
            <atom:updated>2021-07-18T19:04:31.747Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVtJgEH_xr5WrulR2Wf51g.jpeg" /></figure><h3>1.Before you begin:</h3><p>In this blog we will learn how to use Navigation component in a Parent Fragment instead of Activity and navigation within child fragments.</p><p><strong>Introduction:</strong></p><p>Just like an activity contains Fragments using Navigation component, a Fragment can also contain Fragments with Navigation Component.</p><p>In case of using Navigation component in Activity , activity is the parent and all the fragment transactions refer to activity during navigation or Fragments can refer to activity context .</p><p><strong>Situation:</strong></p><p>Imagine we have a situation where we want a Fragment as Parent and to have child fragments with in them so that the child fragment use ParentFragment context instead of activity context and these fragments are independent of activity.</p><p>In this situation, activity will be hosting only Parent Fragment and have no control of Child Fragments.</p><p><strong>Where this is useful?</strong></p><p>This kind of requirement or solution is useful when we want our child Fragments to be independent of Activity.</p><p>This solution is useful when we want to plug and play our app in another activity or we need to host our app in another activity , only parent Fragment will be changed but not any one of its child fragments.</p><p><strong>What will this blog do ?</strong></p><ul><li>Create a simple app that uses concept of Parent Fragment</li><li>Parent Fragment hosts 2 child fragments(LoginFragment and ListFragment) with Navigation Component</li><li>Activity hosts only Parent Fragement</li><li>App is developed using Kotlin with Jet Pack components.</li></ul><p><strong>Prerequisites:</strong></p><ul><li>Experience with Activities, Fragments.</li><li>Familiarity with the Architecture Components ViewModel, LiveData, Repository.</li><li>Experience with Kotlin syntax, including lambdas.</li></ul><h3>2.Getting Setup :</h3><p><a href="https://github.com/chandragithub2014/ParentFragmentSample">chandragithub2014/ParentFragmentSample</a></p><p>The code is available in the above Github repository.</p><blockquote><a href="https://github.com/chandragithub2014/ParentFragmentSample.git">https://github.com/chandragithub2014/ParentFragmentSample.git</a></blockquote><h3>3.Run the app:</h3><p>Once the app is run, we see a login screen followed by list screen. Click back in list screen will navigate to login screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3gUGx-_AHMlFjYwH4H5RQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyvWQnuAy01hu65tlAs0bw.png" /></figure><h3>How is it implemented?</h3><p>The code contains below UI components:</p><p>(1) MainActivity</p><p>(2) ParentFragment</p><p>(3) Login Fragment</p><p>(4) InfinitListFragment</p><ol><li><strong>MainActivity:</strong></li></ol><p>The layout of Main Activity contains a FrameLayout to host the ParentFragment.</p><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>    &lt;FrameLayout<br>        android:id=&quot;@+id/fragment_container&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>In the activity the below code is used to replace framelayout with ParentFragment.</p><pre>val parentFragment = ParentFragment.newInstance(&quot;&quot;,&quot;&quot;)<br><em>supportFragmentManager</em>.beginTransaction().replace(R.id.<em>fragment_container</em>,parentFragment).commit()</pre><p>2. <strong>ParentFragment :</strong></p><p>This is the Fragment that hosts child fragment with Navigation component.</p><p>Also this Fragment hosts common UI components that can be accessed by its child fragments independent of Activity.</p><p>In this example ParentFragment uses ToolBar,which will be used by corresponding child fragments to change the toolbar title during navigation independent of Activity.</p><p>ParentFragment instantiates ViewModel which can be accessed by its childFragment without recreating.</p><p>The Layout is below:</p><pre>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    &gt;<br>    <strong>&lt;include<br>        layout=&quot;@layout/app_bar_layout&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;</strong><br>   <strong> &lt;fragment<br>        android:id=&quot;@+id/nav_host_scanner_fragment&quot;<br>        android:name=&quot;androidx.navigation.fragment.NavHostFragment&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/top_app_bar&quot;<br>        app:navGraph=&quot;@navigation/nav_nested&quot;<br>        app:defaultNavHost=&quot;true&quot;<br>        /&gt;</strong><br><br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>Initializing ViewModel in ParentFragment:</p><pre>private fun initViewModel(){<br>    var infiniteViewModelFactory = InfiniteViewModelFactory()<br>    infiniteListViewModel = ViewModelProvider(this,infiniteViewModelFactory).get(<br>        InfiniteListViewModel::class.<em>java</em>)<br><br>}</pre><p>How to access ParentFragment toolbar view in child Fragments . Below is the code fragment how it’s accessed in LoginFragment to change title.</p><p><strong>LoginFragment:</strong></p><pre>private fun initToolBar(){<br>    <strong>val navHostFragment = <em>parentFragment </em>as NavHostFragment?<br>    navHostFragment?.<em>let </em>{ navHostFragment -&gt;<br>        navHostFragment.<em>parentFragment</em>?.<em>let </em>{ parentFrag -&gt;<br>            var toolbar =   parentFrag.<em>view</em>?.findViewById&lt;MaterialToolbar&gt;(R.id.<em>top_app_bar</em>)<br>            toolbar?.<em>title </em>= &quot;Login Form&quot;<br>        }<br>    }<br></strong>}<br>override fun onResume() {<br>    super.onResume()<br>    initToolBar()<br>}</pre><p>Accessing ParentFragment Viewmodel in childFragment.</p><pre>private fun initViewModel(){<br><br>nfiniteListViewModel =  ViewModelProvider(requireParentFragment().requireParentFragment()).<em>get</em>&lt;InfiniteListViewModel&gt;()<br><br>}</pre><p><strong>BackNavigation in ChildFragment using hardware back button:</strong></p><p>In order to achieve back navigation in childFragment using hardware backbutton , we need to use callback that uses activity instance. This is the only scenario where we use activity instance in child fragment.</p><p>The below code fragment shows how backnavigation happens from list fragment to login screen fragment using <strong>onBackPressedcallback</strong> method :</p><pre>val onBackPressedCallback = object : OnBackPressedCallback(true) {<br>    override fun handleOnBackPressed() {<br>        NavHostFragment.findNavController(this@InfiniteListFragment).navigateUp()<br>    }<br>}<br><strong>requireActivity().</strong><em>onBackPressedDispatcher</em>.addCallback(this, onBackPressedCallback)</pre><p><strong>Conclusion:</strong></p><p>This is how we can use ParentFragment with Navigationcomponent independent of Activity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1dbe83f3ae15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM with Coroutine Flow and Unit Tests in Kotlin — Part 2]]></title>
            <link>https://b-chandrasaimohan.medium.com/mvvm-with-coroutine-flow-and-unit-tests-in-kotlin-part-2-54d4fc679641?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/54d4fc679641</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 19:02:45 GMT</pubDate>
            <atom:updated>2021-07-12T19:02:45.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*Z13pVfHOP9VxYTV5.jpeg" /></figure><h3>MVVM with Coroutine Flow and Unit Tests in Kotlin — Part 2</h3><h3>1.Before you begin:</h3><p>This blog is continuation of the previous blog .In this blog we will learn how to write unit tests for coroutines with flows using MVVM architecture in Kotlin.</p><p>The link to the part 1 is given below:</p><p><a href="https://b-chandrasaimohan.medium.com/mvvm-with-coroutine-flow-and-unit-tests-in-kotlin-part-1-f4e35ec33d2a">MVVM with Coroutine Flow and Unit Tests in Kotlin — Part 1</a></p><p><strong>Prerequisites:</strong></p><ul><li>Familiarity with the Architecture Components ViewModel, LiveData, Repository.</li><li>Experience with Kotlin syntax, including lambdas.</li><li>Familiarity with Mockito and JUnit testing Framework</li></ul><p><strong>What you’ll do ?</strong></p><p>Use Mockito testing framework to unit test ViewModel in developed app .</p><h3>Getting Setup :</h3><p><a href="https://github.com/chandragithub2014/MMVMCoroutineFlows">chandragithub2014/MMVMCoroutineFlows</a></p><p>The code is available in the above Github repository.</p><blockquote><em>git clone </em><a href="https://github.com/chandragithub2014/MMVMCoroutineFlows.git"><em>https://github.com/chandragithub2014/MMVMCoroutineFlows.git</em></a></blockquote><p><strong>Unit Testing Concepts:</strong></p><p><strong>InstantTaskExecutorRule:</strong></p><p>A JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously.</p><p>You can use this rule for your host side tests that use Architecture Components which means when writing unit tests for view model this rule instantly returns the asynchronous task like connecting with Network and so on. It is needed to test code with LiveData.</p><p><strong>TestCoroutineRule:</strong></p><p>It sets the main dispatcher to testCoroutineDispatcher, runs the test then resets and cleanup. It also creates testCoroutineScope in which we can run our tests.</p><pre>@get:Rule<br>val testInstantTaskExecutorRule: TestRule = InstantTaskExecutorRule()<br><br>@get:Rule<br>val testCoroutineRule = TestCoroutineRule()</pre><p><strong>Mocking :</strong></p><p>We mock the required classes of ViewModel using @mock annotation.</p><pre>@Mock<br>private lateinit var apiHelper: EmployeeService<br><br>@Mock<br>private lateinit var employeeRepository: EmployeeRepository</pre><p><strong>Unit Test a method in ViewModel:</strong></p><pre>private val testDispatcher = TestCoroutineDispatcher()<br>@Test<br>fun test_fetchEmployeeList() = testDispatcher.<em>runBlockingTest </em><strong>{<br>    </strong>var data = UserModel.Data(<br>        &quot;https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg&quot;,<br>        &quot;george.bluth@reqres.in&quot;,<br>        &quot;George&quot;,<br>        1,<br>        &quot;Bluth&quot;<br>    )<br>    var ad = UserModel.Support(&quot;StatusCode Weekly&quot;,&quot;http://statuscode.org/&quot;,)<br>    var list = <em>arrayListOf</em>&lt;UserModel.Data&gt;()<br>    list.add(data)<br>    var retroResponse = UserModel(list,2,6,ad,12,12)<br>    val employeeViewModel = EmployeeViewModel(testDispatcher,employeeRepository)<br>    val response = Response.success(retroResponse)<br>    val channel = <em>Channel</em>&lt;Response&lt;UserModel&gt;&gt;()<br>    val flow = channel.<em>consumeAsFlow</em>()<br>    Mockito.`when`(employeeRepository.fetchEmployees()).thenReturn(flow )<br><br>   <em>launch </em><strong>{<br>       </strong>channel.send(response)<br>   <strong>}<br>    </strong>employeeViewModel.fetchEmployeeList()<br>    Assert.assertEquals(1,employeeViewModel.employeeLiveData.<em>value</em>?.data?.size)<br>    Assert.assertEquals(false, employeeViewModel.fetchLoadStatus()?.<em>value</em>)<br><strong>}</strong></pre><p>In the above created a Dummy model class and created a flow out of it which repository returns after it communicates with Network.</p><p>Since we mocked the repository class, we will return the created flow with below code sample:</p><pre>Mockito.`when`(employeeRepository.fetchEmployees()).thenReturn(flow )</pre><p>We initialize viewmodel with mocked Repository class.</p><pre>val employeeViewModel = EmployeeViewModel(testDispatcher,employeeRepository)</pre><p>We verify the value of the mocked response when view model method is called</p><pre>employeeViewModel.fetchEmployeeList()<br>Assert.assertEquals(1,employeeViewModel.employeeLiveData.<em>value</em>?.data?.size)</pre><p><strong>Congratulations:</strong></p><p>In these two blogs, we have covered Coroutines with Flows in MVVM Architecture with unit tests with a simple app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54d4fc679641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM with Coroutine Flow and Unit Tests in Kotlin — Part 1]]></title>
            <link>https://b-chandrasaimohan.medium.com/mvvm-with-coroutine-flow-and-unit-tests-in-kotlin-part-1-f4e35ec33d2a?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4e35ec33d2a</guid>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Mon, 12 Jul 2021 18:25:41 GMT</pubDate>
            <atom:updated>2021-07-12T19:04:04.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*banTN1ZYl9_0DU4g.jpeg" /></figure><h3>MVVM with Coroutine Flow and Unit Tests in Kotlin — Part 1</h3><h3>1.Before you begin:</h3><p>In this blog we will learn how to use Coroutines with Flows and also unit tests with MVVM architecture in Kotlin.</p><p><strong>What is Coroutine ?</strong></p><p>A <em>coroutine</em> is a concurrency design pattern that you can use on Android to simplify code that executes asynchronously.</p><p><strong><em>What is Flow ?</em></strong></p><ul><li>A flow is a stream of values that are asynchronously computed.</li><li>Flows emits values and there is other process/coroutines that receives/process the emitted values.</li></ul><p><strong>Prerequisites:</strong></p><ul><li>Familiarity with the Architecture Components ViewModel, LiveData, Repository.</li><li>Experience with Kotlin syntax, including lambdas.</li><li>A basic understanding of using threads on Android, including the main thread, background threads, and callbacks.</li></ul><p><strong>What you’ll do ?</strong></p><ul><li>Code written with coroutines and flows to fetch data from server and obtain results.</li><li>Use MVVM Architecture.</li><li>Use suspend functions to make async code sequential.</li><li>Use coroutines with Architecture Components.</li><li>Learn best practices for testing coroutines and flows.</li></ul><h3><strong>2.Getting Setup :</strong></h3><p><a href="https://github.com/chandragithub2014/MMVMCoroutineFlows">chandragithub2014/MMVMCoroutineFlows</a></p><p>The code is available in the above Github repository.</p><blockquote>git clone <a href="https://github.com/chandragithub2014/MMVMCoroutineFlows.git">https://github.com/chandragithub2014/MMVMCoroutineFlows.git</a></blockquote><h3>3.Run the app:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*uT6MAj2RnPb_cVV87ySsdw.png" /></figure><p>Architecture Used:</p><p>MVVM architecture is used to build this app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipGmhSFWpyibOZzf1CJYjQ.png" /></figure><p><strong><em>1.MainActivity</em></strong><em> :</em>displays the UI. It observes data from ViewModel through live data and populates the list.</p><p>2. <strong>ViewModel</strong> : ViewModel handles the business logic using Coroutines and collects the data from Repository .</p><p>3. <strong>Repository</strong>: Communicates with Network to fetch the data in the form of flow which ViewModel collects in the coroutine.</p><p>4. <strong>Network</strong> : Handles Network communication.</p><h3>Adding Coroutines to Project:</h3><p>The below are the dependencies to be added to include coroutines in project:</p><pre>implementation &quot;org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutine_version&quot;<br></pre><pre>coroutine_version = &#39;1.3.9&#39;</pre><p><strong>Using Coroutines in ViewModel:</strong></p><pre>class EmployeeViewModel(private val dispatcher: CoroutineDispatcher, private val employeeRepository: EmployeeRepository) : ViewModel(),LifecycleObserver {<br>    var loading: MutableLiveData&lt;Boolean&gt; = MutableLiveData()<br>  private val _employeeMutableLiveDate= MutableLiveData&lt;UserModel&gt;()<br> val  employeeLiveData: LiveData&lt;UserModel&gt; = _employeeMutableLiveDate<br><br>    init {<br>        loading.postValue(true)<br>    }<br>    <em>/**<br>     * Fetch employee list<br>     *<br>     */<br>    </em>fun fetchEmployeeList(){<br><br>       <em>viewModelScope</em>.<em>launch</em>(dispatcher) <strong>{<br>           </strong>loading.postValue(true)<br>           try{<br>            employeeRepository.fetchEmployees().collect <strong>{ </strong>response<strong>-&gt;<br>                  </strong>if(response.<em>isSuccessful</em>){<br>                      loading.postValue(false)<br>                      val employeeInfo = response.body()<br>                      employeeInfo?.<em>let </em><strong>{ </strong>model <strong>-&gt;<br>                          </strong>_employeeMutableLiveDate.<em>value </em>= model<br>                      <strong>}<br><br><br>                  </strong>}else{<br>                      loading.postValue(false)<br>                  }<br><br>              <strong>}<br><br><br>           </strong>}catch (e:Exception){<br>               loading.postValue(false)<br>               e.printStackTrace()<br>           }<br>       <strong>}<br><br>     </strong>}</pre><p><strong>Explanation of above code:</strong></p><p>As mentioned above coroutines help us to simplify that executes Asynchronously.</p><p>It uses suspend functions to avoid blocking the main thread.</p><p>The main thread is a single thread that handles all updates to the UI. It’s also the thread that calls all click handlers and other UI callbacks. As such, it has to run smoothly to guarantee a great user experience.</p><p>All Coroutines run inside a scope called CoroutineScope. A scope controls the lifetime of coroutines.</p><p>Scopes also allow you to specify a default dispatcher. A dispatcher controls which thread runs a coroutine.</p><p>For coroutines started by the UI, it is typically correct to start them on <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html">Dispatchers.Main</a> which is the main thread on Android. A coroutine started on <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-main.html">Dispatchers.Main</a> won&#39;t block the main thread while suspended. Since a ViewModel coroutine almost always updates the UI on the main thread, starting coroutines on the main thread saves you extra thread switches. A coroutine started on the Main thread can switch dispatchers any time after it&#39;s started. For example, it can use another dispatcher to parse a large JSON result off the main thread.</p><blockquote>Libraries like <a href="https://developer.android.com/jetpack/androidx/releases/room"><strong>Room</strong></a> and <a href="https://github.com/square/retrofit"><strong>Retrofit</strong></a> offer main-safety out of the box when using coroutines, so you don&#39;t need to manage threads to make network or database calls.</blockquote><p><strong>Coroutines with JetPack Components:</strong></p><p>With Kotlin coroutines, you can define a <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-scope/">CoroutineScope</a>, which helps you to manage when your coroutines should run. Each asynchronous operation runs within a particular scope.</p><p><a href="https://developer.android.com/topic/libraries/architecture">Architecture components</a> provide first-class support for coroutines for logical scopes in your app along with an interoperability layer with <a href="https://developer.android.com/topic/libraries/architecture/livedata">LiveData</a>.</p><p>Architecture components defines the following built-in scopes that you can use in your app which reduces the code to handle coroutine scopes.</p><h3>ViewModelScope :</h3><p>The above code fragment uses Viewmodelscope which is defined for each viewmodel in your app.</p><p>Any coroutine launched in this scope is automatically canceled if the ViewModel is cleared. Coroutines are useful here for when you have work that needs to be done only if the ViewModel is active.</p><p>For more info on Architecture components scopes please find below link:</p><p><a href="https://developer.android.com/topic/libraries/architecture/coroutines">https://developer.android.com/topic/libraries/architecture/coroutines</a></p><p>The above code fragment collects the data from the repository which returns flow of data received from network.</p><p><strong>Code Fragment for Repository class that uses flow:</strong></p><pre>class EmployeeRepository(private  val apiServiceAPI: EmployeeService) {<br><br>    suspend fun fetchEmployees() : Flow&lt;Response&lt;UserModel&gt;&gt; {<br>        return  <em>flow </em><strong>{<br>            </strong>val employeeInfo = apiServiceAPI.fetchEmployee()<br>            emit(employeeInfo)<br>        <strong>}<br>    </strong>}<br>}</pre><p>The above code uses suspend function to fetch data from network and returns the data as flow by emit() function.</p><p><strong>Network layer:</strong></p><p>Its an interface that contains Retrofit methods.</p><pre>interface EmployeeService {<br>//https://reqres.in/api/users<br>    @GET(&quot;/api/users&quot;)<br>    suspend fun fetchEmployee(): Response&lt;UserModel&gt;<br>}</pre><p>The next part of this blog will explain how to unit test Flows</p><p><a href="https://b-chandrasaimohan.medium.com/mvvm-with-coroutine-flow-and-unit-tests-in-kotlin-part-2-54d4fc679641">https://b-chandrasaimohan.medium.com/mvvm-with-coroutine-flow-and-unit-tests-in-kotlin-part-2-54d4fc679641</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4e35ec33d2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MVVM with Flows in Kotlin]]></title>
            <link>https://b-chandrasaimohan.medium.com/mvvm-with-flows-in-kotlin-d2013fe2daff?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2013fe2daff</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin-flow]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Mon, 05 Jul 2021 18:21:46 GMT</pubDate>
            <atom:updated>2021-07-05T18:21:46.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/963/0*KcX-nVrPiXMiab2u.jpeg" /></figure><p>This story describes creating a simple Android application that uses MVVM architecture along with Flows .</p><p><strong>Basics of Flow:</strong></p><blockquote><strong>What is Flow ?</strong></blockquote><ul><li>A flow is a stream of values that are asynchronously computed.</li><li>Flows emits values and there is other process/coroutines that receives/process the emitted values.</li></ul><blockquote><strong>Creating Flows</strong></blockquote><p>Ways to Create Flow:</p><p>(1) Generate values by emitting each value</p><pre>fun emitNumbers(): Flow&lt;Int&gt; = <em>flow</em><strong>{<br>    </strong>val numList = <em>listOf</em>&lt;Int&gt;(1,2,3,4,5,6,7)<br>    numList.<em>forEach </em><strong>{<br>        </strong>delay(<strong>it</strong>*100L)<br>        emit(<strong>it</strong>)<br>    <strong>}<br>}</strong></pre><p>(2)A collection can be directly converted into a flow.</p><pre>fun convertingCollectionInToFlow() = <em>listOf</em>&lt;Int&gt;(1,2,3,4,5,6,7,8,9,10).<em>asFlow</em>()</pre><p>(3)A flow can be generated from a number of parameters of any type.</p><pre>fun creatingFlowWithNumberOfParameters()= <em>flowOf</em>(&quot;one&quot;,&quot;two&quot;,&quot;three&quot;)</pre><p><strong>Using Flows in Android with MVVM Architecture:</strong></p><p>The example explained in this story is a very basic example.</p><blockquote><strong>What this example does?</strong></blockquote><p>This example fetch list of data from network and displays in the list.</p><blockquote><strong>Architecture</strong></blockquote><p><strong>Model:</strong></p><p>Created a data class that represents the model of the API response</p><pre>class PostsModel : ArrayList&lt;PostsModel.PostsModelItem&gt;(){<br>    data class PostsModelItem(<br>        val body: String, // cupiditate quo est a modi nesciunt soluta ipsa voluptas error itaque dicta in autem qui minus magnam et distinctio eum accusamus ratione error aut<br>        val id: Int, // 100<br>        val title: String, // at nam consequatur ea labore ea harum<br>        val userId: Int // 10<br>    )<br>}</pre><p><strong>API service Interface:</strong></p><p>This interface contains the retrofit methods to fetch data from network</p><pre>interface PostsService {<br>    @GET(&quot;/posts&quot;)<br>    suspend fun  fetchPosts(): List&lt;PostsModel.PostsModelItem&gt;<br>}</pre><p><strong>Repository :</strong></p><p>We need a repository to communicate with PostsService to fetch data.</p><p>This is the place where we use flow .</p><pre>fun getPosts(): Flow&lt;PostsModel.PostsModelItem&gt;{<br>   <strong> return  <em>flow </em>{<br>        val postList = postsService.fetchPosts()<br>        <em>println</em>(&quot;PostsList is $postList&quot;)<br>        postList.<em>forEach </em>{<br>            emit(it)<br>            delay(NEWS_DELAY)<br>        }<br>    }<br></strong>}</pre><p><strong>Explanation:</strong></p><p>The getPosts() method returns flow of model item.</p><p>This method calls a method from postsService and emit each item in the list to the viewModel with some delay.</p><p><strong>ViewModel:</strong></p><p>View model will have one method that returns live data. A flow can be converted to live data using method <strong>.<em>asLiveData</em>()</strong></p><pre>class ListViewModel: ViewModel() {<br><br>    val posts = PostRepository().getPosts().<em>asLiveData</em>()<br><br>}</pre><p>The received live data from view model will be observed in view as below:</p><p><strong>View:</strong></p><pre>private fun observeViewModel() {<br>    viewModel.posts.observe(this, <em>Observer </em><strong>{ </strong>post <strong>-&gt;<br>        </strong>loading_view.<em>visibility </em>= View.<em>GONE<br>        </em>newsList.<em>visibility </em>= View.<em>VISIBLE<br>        </em>newsListAdapter.onAddPostsItem(post)<br>        newsList.smoothScrollToPosition(0)<br>    <strong>}</strong>)<br>}</pre><p>Each item emitted from flow will be added to the top of the list and position is scrolled to the added position as above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*UNTtWb-JjIONJ0031tJWyQ.jpeg" /></figure><p>Github link for Code:</p><p><a href="https://github.com/chandragithub2014/AndroidFlows">chandragithub2014/AndroidFlows</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2013fe2daff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Product Flavors — Simple Sample]]></title>
            <link>https://medium.com/codex/product-flavors-simple-sample-11541374a433?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/11541374a433</guid>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[productflavor]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Thu, 20 May 2021 09:53:48 GMT</pubDate>
            <atom:updated>2021-05-31T13:00:34.622Z</atom:updated>
            <content:encoded><![CDATA[<h3>Product Flavors — Simple Sample</h3><h4>This story explains Android Product flavors with a simple Sample Application.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*_VzyjT63GL6b8pF2rAc7AA.jpeg" /><figcaption>Product Flavors</figcaption></figure><h4><strong>Use Case:</strong></h4><p>I have a requirement where I need to fetch data from the backend using retrofit/any other network API and populate my user interface.</p><h4><strong>Challenges:</strong></h4><p>The backend is not yet ready and I will not be able to fetch data from the back end and populate my user interface.</p><p>Though my development is ready, I can’t test my user interface.</p><h4><strong>One of the Solution :</strong></h4><p>Rather than waiting till backend development is done, it is better to test the app with mock JSON without any network interaction.</p><p>This helps to test the user interface flow and also helps to fix the defects that encounter.</p><p>Once the back end is ready, we need to replace the mock JSON code with real API code.</p><p><strong>Problem with the above approach:</strong></p><p>The problem with the above approach is we need to replace the code that contains mock JSON with API interaction code. Also if after some time if the backend is down and API does not work again we need to modify the code related to API interaction and replace it with mock JSON code to proceed with app development.</p><p><strong>Solution 1: Maintain two codebases</strong></p><p>Maintain 2 codebases, one for mock JSON and another with API interaction.</p><p>The problem with this approach is difficulty in maintenance. If there is some change in the UI layer, we need to modify both the very difficult codebases.</p><p><strong>Solution 2: Product flavors</strong></p><p>Android Product Flavors are used to create different app versions from a single code base. App versions can be free or paid. They can have different themes and texts. They can use different environments or APIs similar to our requirements.</p><p>Simply put, a product flavor is a variant of your app. It is very useful when you want to create multiple versions of your app. This means you can generate different versions or variants of your app using a single codebase.</p><p>Product flavors are a powerful feature of the Gradle plugin from Android Studio to create customized versions of products. They form part of what we call <strong>Build Variants</strong>.</p><p>Build variants are the result of Gradle using a <a href="https://developer.android.com/studio/build/build-variants?authuser=1#sourceset-build">specific set of rules</a> to combine settings, code, and resources configured in your build types and product flavors. Although you do not configure build variants directly, you do configure the build types and product flavors that form them.</p><p><strong>Configure Product for the use case:</strong></p><p>We need to configure product flavors for the above use case, which means we create two build variants one to fetch data from real API and other build variants to fetch data from mock JSON.</p><p>The Architecture that will be used is MVVM, in which ViewModel interacts with the repository which in turn interacts with real API or mock JSON to return data to viewmodel which will be observed by activity/fragment to populate UI.</p><p>So, we need to need to have a repository class in each of the product flavors with the same name, same package(I am using the same package). When a particular build variant is selected, the repository is picked from that particular flavor and data will be fetched accordingly.</p><p><strong>Steps to implement product flavor:</strong></p><p>Step 1: Add the below block of code in app-level Gradle in android block</p><pre>flavorDimensions &quot;fetchdata&quot;<br>productFlavors <strong>{<br>    </strong>real <strong>{<br>        </strong>dimension &quot;fetchdata&quot;<br>        applicationIdSuffix &quot;.real&quot;<br>    <strong>}<br>    </strong>mock <strong>{<br>        </strong>dimension &quot;fetchdata&quot;<br>        applicationIdSuffix &quot;.mock&quot;<br>    <strong>}<br>}</strong></pre><p>The above code block contains 2 product flavors <strong>real </strong>and <strong>mock</strong>, <strong>real </strong>fetches data from the back end whereas <strong>mock </strong>fetches data from the mock JSON file present in the assets folder.</p><p>All flavors must belong to a named flavor dimension, which is a group of product flavors. You must assign all flavors to a flavor dimension; otherwise, you will get the build error. If a given module specifies only one flavor dimension, the Android Gradle plugin automatically assigns all of the module’s flavors to that dimension.</p><p>application suffix: It specifies the package name for each flavor. Suppose if the application has applicationId as “com.android.productflavorsdemo” under default config, then for each of the product flavor a suffix is added as below :</p><p>when ‘real’ product flavor is selected we see the package as com.android.productflavorsdemo.real and if <strong>mock </strong>flavor is selected “com.android.productflavorsdemo.mock”</p><p>Step2: After completion of step1, perform Gradle sync:</p><p>In Android Studio: Build -&gt; Select Build Variant, we should be able to see like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*-lGwSr0Yl0-JT8mnbDGxEA.png" /></figure><p>Each product flavor generates 2 build variants, one for Debug and the other for Release build types. So a total of 4 build variants.</p><p>Step 3: Source code structure.</p><p>Create 2 directories/folders under src directory as below so that we can see 2 new directories with name <strong>real </strong>and <strong>mock </strong>along with <strong>main </strong>as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*M67ecu6EdZh_IjdrOjSIRA.png" /></figure><p>Step 3: The package structure for the <strong>main </strong>is as below. Observe “Repository” folder is empty since we use product flavors to fetch data from different sources based on selected build variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*psLLbhxAgkQ2RzATRGLn6Q.png" /></figure><p>Step 4: Structure for mock product flavor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*dq1sLTGznNsRUdxGQDpQoQ.png" /></figure><p>The assets folder contains mock JSON and the utils folder contains JSONHelper that reads data from JSON.</p><p>The PlaceHolderRepository class fetches data from JSonHelper. Please find below the code sample for the repository class:</p><pre>class PlaceHolderRepository(private  val apiServiceAPI: PlaceHolderServiceAPI) {<br>     init {<br>        <strong> <em>println</em>(&quot;From Mock &quot;)  //Debug stmt that is displayed when mock flavor repository is executed.</strong><br>     }<br>     <br>     suspend fun fetchPosts(): Response&lt;PlaceHolderPostsDataModel&gt; =  JSONHelper.fetchParsedJSONForPosts()<br>     suspend fun fetchComments(): Response&lt;PlaceHolderCommentsModel&gt; = JSONHelper.fetchParsedJSONForComments()<br>}</pre><p>Step 4: Structure for real product flavor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*3j5ZophcPAQgtHrIg-qMCg.png" /></figure><p>Observe in the above screenshot the real product contains only the Repository class.</p><p>The source code will be as below as it fetches data from real service:</p><pre>class PlaceHolderRepository(private  val apiServiceAPI: PlaceHolderServiceAPI){<br>    init {<br>        <em>println</em>(&quot;From Real &quot;)<br>    }<br>    fun  displayInfo() = &quot;From Real&quot;<br>    suspend fun fetchPosts(): Response&lt;PlaceHolderPostsDataModel&gt; = <strong>apiServiceAPI.fetchPlaceHolderPosts()</strong><br>    suspend fun fetchComments(): Response&lt;PlaceHolderCommentsModel&gt; = <strong>apiServiceAPI.fetchPlaceHolderComments()</strong><br>}<br>//Fetches data from backend using  Retrofit library</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4j0TmsCb1SGhe1SooNwvTQ.png" /></figure><p>When a specific build variant is selected, data is fetched accordingly. Can check-in logcat whether data is received from mock or real when build variant is selected as log statement is executed in the init block of Repository class?</p><p>Note: Similarly if we want a build variant to fetch data from prod server/syst server or white labeling, paid / free versions of the app create different product flavors and move flavor specific code to corresponding product flavor directories.</p><p><strong>Source for the above sample -&gt; Available in Github:</strong></p><p><a href="https://github.com/chandragithub2014/ProductFlavorsDemo">chandragithub2014/ProductFlavorsDemo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11541374a433" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/product-flavors-simple-sample-11541374a433">Product Flavors — Simple Sample</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fire Base with Kotlin MVVM]]></title>
            <link>https://medium.com/codex/fire-base-with-kotlin-mvvm-799fd954dea6?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/799fd954dea6</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Fri, 02 Apr 2021 08:38:28 GMT</pubDate>
            <atom:updated>2021-04-08T06:06:38.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Using FireBase with MVVM" src="https://cdn-images-1.medium.com/max/180/1*RLMbVEuco8c2eIIAtP0SDQ.png" /><figcaption>FireBase with MVVM using Kotlin</figcaption></figure><p>This story demonstrates a sample android application for using FireBase Database with MVVM using Kotlin.</p><p>The application uses below features of firebase:</p><p>(1) Authentication</p><p>(2) Real time Database</p><p>(3) Storage</p><p><strong>Brief introduction of Sample app:</strong></p><p>The sample that is used as part of demonstration contains below screens:</p><p>(1) <strong>Login Screen :</strong> Authenticates the logged user with email/password provided</p><p>(2)<strong>Registration screen :</strong> This screen allows user to register with email/password over firebase.</p><p>For the above 2 screens we use firebase “Authentication” feature.</p><p>(3)<strong> Tax Info Entry screen: </strong>In this screen user will be provided UI to enter info about Tax bills and submit that data. Allows user to upload pdf docs as proof for bills.</p><p>This screen uses firebase “Realtime Database” and “storage” features.</p><p>(4)<strong>Tax List: </strong>This screen displays list of Tax details entered by user based on email ID</p><p>This screen uses firebase “Realtime Database”.</p><p><strong>App Implementation Details:</strong></p><p>Step 1 : Registered my app over firebase console and below screen shoot for the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rldqwwXV4Ou2vJLGyna8Kg.png" /></figure><p>To register my app I followed the steps as described below in firebase documentation .</p><p><a href="https://firebase.google.com/docs/android/setup">Add Firebase to your Android project | Firebase for Android</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdRYnm_k3w1w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdRYnm_k3w1w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdRYnm_k3w1w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4325f69cf35d2c0a76159e8c8db197e5/href">https://medium.com/media/4325f69cf35d2c0a76159e8c8db197e5/href</a></iframe><p>Step2:</p><p>Enabled the features required for my app as below:</p><p>(a) <strong>Authentication</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rjrQbdvSFV1IcuNDbfouIA.png" /><figcaption>Authentication</figcaption></figure><p>Enabled Email/Password as authentication mechanism for this app. We can enable any of the Authentication mechanisms based on app requirement .</p><p>Click on users tab we can view list of registered users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lA5osc50vWJc3_2i6Pxp9w.png" /></figure><p>(b) <strong>Realtime Database:</strong> Enabled real time database feature to save my app’s data.</p><p>I have table named “taxInfo”. The table data is represented as nodes as FireBase use NOSQL as underlying DataBase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQdQUkgbnfAKYidAf3fetg.png" /></figure><p>© <strong>FireBase Cloud storage:</strong></p><p>The pdf docs or any type of files can be saved in FireBase by enabling “storage” feature. When a file is uploaded in FireBase we receive in response URL of that file which is easy to maintain in DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRX0OHWc1E12Iasj1rGblw.png" /></figure><p><strong>App project structure:</strong></p><p>Used MVVM design pattern. Handled all the interaction with FireBase in the ViewModel and providing required data to be consumed by Views</p><p>In the ViewModel initialized all the required FireBase features in the init block as below:</p><pre>private var  auth: FirebaseAuth? = null<br>private var storage: FirebaseStorage<br>private var storageReference: StorageReference<br>private  var rootNode: FirebaseDatabase<br>private  var reference: DatabaseReference<br>var loading: MutableLiveData&lt;Boolean&gt; = MutableLiveData()<br>init {<br><br>    auth = FirebaseAuth.getInstance()    //Authentication<br>    storage = FirebaseStorage.getInstance()   //File/image uploads<br>    storageReference = storage.<em>reference    //Reference to the storage <br>    </em>rootNode = FirebaseDatabase.getInstance()   // Realtime DB<br>    reference = rootNode.getReference(&quot;taxInfo&quot;) //Reference to DBTable<br>    loading.postValue(false)<br><br>}</pre><p>Authentication:</p><p>To register an user firebase provides below API :</p><pre>authentication.createUserWithEmailAndPassword(email,password)<br>    .addOnCompleteListener <strong>{</strong>task: Task&lt;AuthResult&gt; <strong>-&gt;<br>        </strong>if(!task.<em>isSuccessful</em>){<br>            <em>println</em>(&quot;Registration Failed with ${task.<em>exception</em>}&quot;)<br>            _registrationStatus.postValue(ResultOf.Success(&quot;Registration Failed with ${task.<em>exception</em>}&quot;))<br>        }else{<br>            _registrationStatus.postValue(ResultOf.Success(&quot;UserCreated&quot;))<br><br>        }<br>        loading.postValue(false)<br>    <strong>}</strong></pre><p>Authenticate User:</p><pre>auth?.<em>let</em><strong>{ </strong>login<strong>-&gt;<br>    </strong>login.signInWithEmailAndPassword(email,password)<br>        .addOnCompleteListener <strong>{</strong>task: Task&lt;AuthResult&gt; <strong>-&gt;<br><br>            </strong>if(!task.<em>isSuccessful</em>){<br>                <em>println</em>(&quot;Login Failed with ${task.<em>exception</em>}&quot;)<br>                _signInStatus.postValue(ResultOf.Success(&quot;Login Failed with ${task.<em>exception</em>}&quot;))<br>            }else{<br>                _signInStatus.postValue(ResultOf.Success(&quot;Login Successful&quot;))<br><br>            }<br>            loading.postValue(false)<br>        <strong>}<br><br>}</strong></pre><p>sign out:</p><pre>auth?.<em>let </em><strong>{</strong>authentation <strong>-&gt;<br>    </strong>authentation.signOut()<br>    _signOutStatus.postValue(ResultOf.Success(&quot;Signout Successful&quot;))<br>    loading.postValue(false)<br><strong>}</strong></pre><p>Upload doc:</p><pre>val ref = storageReference<br>    .child(&quot;/uploadedDocs/&quot;<br>            + UUID.randomUUID().toString())<br>val uploadTask = ref.putFile(selectedImageUri)<br>val urlTask = uploadTask.continueWithTask(<em>Continuation</em>&lt;UploadTask.TaskSnapshot, Task&lt;Uri&gt;&gt; <strong>{ </strong>task <strong>-&gt;<br>    </strong>if (!task.<em>isSuccessful</em>) {<br>        task.<em>exception</em>?.<em>let </em><strong>{<br>            </strong>throw <strong>it<br>        }<br>    </strong>}<br>    return@Continuation ref.<em>downloadUrl<br></em><strong>}</strong>)?.addOnCompleteListener <strong>{ </strong>task <strong>-&gt;<br>    </strong>if (task.<em>isSuccessful</em>) {<br>        val downloadUri = task.<em>result<br>        println</em>(&quot;Downloaded URL: is ${downloadUri.<em>toString</em>()}&quot;)<br>       <strong> var downloadUrl = downloadUri.<em>toString</em>() //Return URL of uploaded doc</strong><br>        _uploadDocResult.postValue(ResultOf.Success(downloadUrl))<br>        loading.postValue(false)<br>        // addUploadRecordToDb(downloadUri.toString())<br>    } else {<br>        _uploadDocResult.postValue(ResultOf.Success(&quot;Upload Failed&quot;))<br>        loading.postValue(false)<br>    }<br><strong>}</strong>?.addOnFailureListener<strong>{<br>    </strong>_uploadDocResult.postValue(ResultOf.Success(&quot;Upload Failed&quot;))<br>    loading.postValue(false)<br><strong>}</strong></pre><p>Save Single row of Data to Realtime DB:</p><pre><strong>val id: String? = reference.push().<em>key   //Creates unique ID to represent a row</em></strong><em><br><br><br></em>reference.addValueEventListener(object : ValueEventListener {<br>    override fun onDataChange(@NonNull snapshot: DataSnapshot) {<br>        // inside the method of on Data change we are setting<br>        // our object class to our database reference.<br>        // data base reference will sends data to firebase.<br>        if (id != null) {<br>           <strong> reference.child(id).setValue(taxInfo) //Set the Dataclass object to save the data</strong><br>        }<br><br>        _saveResult.postValue(ResultOf.Success(&quot;Data Saved Successfully&quot;))<br>        loading.postValue(false)<br>    }<br><br>    override fun onCancelled(@NonNull error: DatabaseError) {<br>        // if the data is not added or it is cancelled then<br>        // we are displaying a failure toast message.<br>        _saveResult.postValue(ResultOf.Success(&quot;Data Save Failed&quot;))<br>        loading.postValue(false)<br>    }<br>})</pre><p>Read Data From DB:</p><pre><strong>var checkUser: Query = reference.orderByChild(&quot;employeeEmail&quot;).equalTo(email)</strong><br><br>checkUser.addValueEventListener(object : ValueEventListener {<br>    override fun onDataChange(dataSnapshot: DataSnapshot) {<br>        for (postSnapshot in dataSnapshot.<em>children</em>) {<br>            val taxInfo= postSnapshot.getValue(TaxInfo::class.<em>java</em>)<br>            if (taxInfo != null) {<br>                taxInfoList.add(taxInfo)<br>            }<br>        }<br>        _taxInfoMutableLiveDataList.postValue(ResultOf.Success(taxInfoList))<br><br>    }</pre><p>DataModel:</p><pre>data class TaxInfo(val employeeEmail : String = &quot;&quot;,val taxDetailType:String = &quot;&quot;,val taxDetailAmount:String = &quot;&quot;,val uploadUrl:String =&quot;&quot;)</pre><p>Note: FireBase requires us to intialize dataclass variables with default values in Kotlin. Otherwise it throws an error. Make sure to initialize variables in data class to default values.</p><p><strong>Github link for source code:</strong></p><p><a href="https://github.com/chandragithub2014/MyReferenceProject/tree/master/features/firebaseoprs">chandragithub2014/MyReferenceProject</a></p><p>Dependencies:</p><p><a href="https://github.com/chandragithub2014/MyReferenceProject/blob/master/features/firebaseoprs/build.gradle">chandragithub2014/MyReferenceProject</a></p><pre>implementation platform(&#39;com.google.firebase:firebase-bom:26.5.0&#39;)<br><br>// Declare the dependency for the Firebase Authentication library<br>// When using the BoM, you don&#39;t specify versions in Firebase library dependencies<br>implementation &#39;com.google.firebase:firebase-auth-ktx&#39;<br>implementation &#39;com.google.firebase:firebase-storage:19.2.1&#39;<br>// Declare the dependency for the Realtime Database library<br>// When using the BoM, you don&#39;t specify versions in Firebase library dependencies<br>implementation &#39;com.google.firebase:firebase-database-ktx&#39;</pre><p><a href="https://github.com/chandragithub2014/MyReferenceProject/blob/master/build.gradle">chandragithub2014/MyReferenceProject</a></p><p>Google play services dependency:</p><pre>classpath &#39;com.google.gms:google-services:4.3.5&#39;</pre><p>Screen shots for App:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Sv0v1p3cyVUV_o_UEREblg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*49j6cXVW0RxI0QzrfhaKRQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*3niRLnS0NdPn6OFZJpR4pA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*fofRhO92f2OIij_bYgSmJQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*f-drm2R53WsGX7MlRTL5JA.jpeg" /></figure><p><strong>Brief Introduction of FireBase:</strong></p><p>Firebase is a backend platform for building Web, Android and IOS applications. It offers real time database, different APIs, multiple authentication types and hosting platform.</p><p>Firebase is a Backend-as-a-Service, and it is a real-time database which is basically designed for mobile applications.</p><p>In the era of rapid prototyping, we can get bright ideas, but sometimes they are not applicable if they take too much work. Often, the back-end is the limiting factor — many considerations never apply to server-side coding due to lack of knowledge or time.</p><p>Firebase is a Backend-as-a-Service(BaaS) which started as a YC11 startup. It grew up into a next-generation app-development platform on Google Cloud Platform. Firebase (a NoSQLjSON database) is a real-time database that allows storing a list of objects in the form of a tree. We can synchronize data between different devices.</p><p>The below are the features provided by Firebase</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*gLRhbuUfJ2VrOGpmzCU3Aw.png" /><figcaption>FireBase features</figcaption></figure><p>We can use any of these services with the help of the Firebase Android SDK to create android apps without writing any server code.</p><p>The most important of the above services are Authentication, Realtime Data Base which are basic .</p><p>Advantages of FireBase:</p><ul><li>Firebase manages real-time data in the database. So, it easily and quickly exchanges the data to and from the database. Hence, for developing mobile apps such as live streaming, chat messaging, etc., we can use Firebase.</li><li>Firebase allows syncing real-time data across all devices — iOS, Android, and Web — without refreshing the screen.</li><li>Firebase provides integration to Google Advertising, AdMob, Data Studio, BigQuery DoubleClick, Play Store, and Slack to develop our apps with efficient and accurate management and maintenance.</li><li>Everything from databases, analytics to crash reports are included in Firebase. So, the app development team can stay focused on improving the user experience.</li><li>Firebase applications can be deployed over a secured connection to the firebase server.</li><li>Firebase offers a simple control dashboard.</li><li>It offers a number of useful services to choose from.</li><li>There is no server infrastructure required to power apps with data.</li><li>It has JSON storage, which means no barrier between data and objects.</li><li>Firebase is serverless.</li></ul><h3>Add Firebase to your Android project:</h3><p><strong>You can connect your Android app to Firebase using one of the following options:</strong></p><ul><li><a href="https://firebase.google.com/docs/android/setup#console"><strong>Option 1</strong></a>: <em>(recommended)</em> Use the Firebase console setup workflow.</li><li><a href="https://firebase.google.com/docs/android/setup#assistant"><strong>Option 2</strong></a>: Use the Android Studio Firebase Assistant (may require additional configuration).</li></ul><p>More info in the below link:</p><p><a href="https://firebase.google.com/docs/android/setup">Add Firebase to your Android project | Firebase for Android</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdRYnm_k3w1w%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdRYnm_k3w1w&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdRYnm_k3w1w%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4325f69cf35d2c0a76159e8c8db197e5/href">https://medium.com/media/4325f69cf35d2c0a76159e8c8db197e5/href</a></iframe><p><a href="https://github.com/chandragithub2014/MyReferenceProject/tree/master/features/firebaseoprs">chandragithub2014/MyReferenceProject</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=799fd954dea6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/fire-base-with-kotlin-mvvm-799fd954dea6">Fire Base with Kotlin MVVM</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infinite List using Kotlin]]></title>
            <link>https://medium.com/swlh/infinite-list-using-kotlin-e90d553d30a4?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/e90d553d30a4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 10:46:44 GMT</pubDate>
            <atom:updated>2021-03-03T10:46:44.300Z</atom:updated>
            <content:encoded><![CDATA[<p>This story describes about infinite list functionality using Kotlin.</p><p><strong>Use case:</strong> For instance we are making an webservice call from mobile application to fetch data to be displayed in a RecyclerView. The back end webservice sends 300 or more rows at a time and pagination functionality is not implemented in backend.</p><p><strong>Problems with the above use case: </strong>The problem with the above use case is we have to populate recyclerview with 300 rows using Adapter which is bad practice as all the elements are not visible at a time on Adapter .It’s not a good practice to populate adapter with 300 rows when user at a time can view maximum of 10 to 20 rows based on available screen height.</p><p><strong>Solution for above use case:</strong> The above problem can be solved by implementing “Pagination” functionality with in the app .</p><p><strong>Steps for Pagination implementation:</strong></p><p>(1) Fetch all the rows from backend server using retrofit.</p><p>(2) Prepare data from the received data to display only 10 elements at a time on Recycler View.</p><p>(3) Implement ViewType functionality in recyclerview adapter : one view type displays 10rows and 11th row is displayed as “Loadmore”</p><p>(4) When clicked on “Loadmore” next set of elements are displayed which means 11 to 20 rows with 21st row as “Loadmore”.</p><p>(5) The above process is continued till we reach end of all the elements from the data received from webservice .</p><p><strong>Sample Screen shots for the above implementation:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCrAJe_avvcjfgKfbYQToA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFCZNWDoW_n6xhh62D9MRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qo_h4I1xFB7iqSVpJXUHsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cMay9_INmHUgTHd35LHqfg.png" /></figure><p><strong>Implementation details:</strong></p><p>Step 1: Create a data class that represents JSON response from backend. For demo purpose , the data is read from .json file of assets folder that contains 204 records of data.</p><pre>class InfiniteModel : ArrayList&lt;InfiniteModel.InfiniteModelItem&gt;(){<br>    data class InfiniteModelItem(<br>        val completed: Boolean, // false<br>        val id: Int, // 200<br>        val title: String, // ipsam aperiam voluptates qui<br>        val userId: Int // 10<br>    )<br>}</pre><p>Step 2: Prepare another model class with ViewTypes to be display data in with RecyclerView Adapter.</p><pre>class InfiniteAdapterModel {<br>    companion object{<br>        const val VIEW_TYPE_DATA  = 0<br>        const val VIEW_TYPE_PROGRESS  =1<br><br>    }<br><br>    var infiniteModelItem: InfiniteModel.InfiniteModelItem<br>    var type : Int<br><br>    constructor( type : Int, infiniteModelItem: InfiniteModel.InfiniteModelItem){<br>        this.type = type<br>        this.infiniteModelItem = infiniteModelItem<br>    }<br>}</pre><p>Step 3: Prepare data for adapter</p><pre><strong>fun prepareDataForAdapter(infiniteModel: InfiniteModel,startPosition:Int,size:Int): MutableList&lt;InfiniteAdapterModel&gt;{<br>    var adapterModel = <em>mutableListOf</em>&lt;InfiniteAdapterModel&gt;()<br>    for (item in startPosition <em>until </em>size) {<br>        adapterModel.add(InfiniteAdapterModel(InfiniteAdapterModel.VIEW_TYPE_DATA,infiniteModel[item]))</strong><br>    }<br>    adapterModel.add(InfiniteAdapterModel(InfiniteAdapterModel.VIEW_TYPE_PROGRESS,InfiniteModel.InfiniteModelItem(false,0,&quot;&quot;,0)))<br>    return adapterModel<br>}</pre><pre><strong>Note: startPositon is 0 and size is 10 to display initial list of 10 items</strong></pre><p>Step4: Create an interface to be implemented in fragment to fetch subsequent list items when clicked on “Loadmore” button in Adapter.</p><pre>interface LoadMore {<br>    fun loadMore(startPosition:Int,endPosition:Int,previousList:MutableList&lt;InfiniteAdapterModel&gt;, originalModel: InfiniteModel)<br>}</pre><p>Step 5: ViewModel: Contains methods to fetch data from backend (in the sample using .json file located under assets folder ) and prepare data to be displayed in Adapter</p><pre>class InfiniteListViewModel(private val dispatcher: CoroutineDispatcher, private val infiniteRepository: InfiniteRepository) : ViewModel(),<br>    LifecycleObserver  {<br>    private val LOG_TAG = &quot;InfiniteListViewModel&quot;<br>    var loading: MutableLiveData&lt;Boolean&gt; = MutableLiveData()<br>    private val _obtainInfiniteListResponse= MutableLiveData&lt;ResultOf&lt;InfiniteModel&gt;&gt;()<br>    val  obtainInfiniteListResponse: LiveData&lt;ResultOf&lt;InfiniteModel&gt;&gt; = _obtainInfiniteListResponse<br><br>    <strong>fun obtainInfiniteList(){</strong><br>        loading.postValue(true)<br>        <em>viewModelScope</em>.<em>launch</em>(dispatcher)<strong>{<br>            </strong>try{<br>                val infiniteListResponse = infiniteRepository.fetchInfiniteList()<br>                if(infiniteListResponse.<em>isSuccessful</em>){<br>                    loading.postValue(false)<br>                    val response = infiniteListResponse.body()<br>                    response?.<em>let </em><strong>{<br>                        </strong>_obtainInfiniteListResponse.postValue(ResultOf.Success(<strong>it</strong>))<br>                    <strong>}<br>                </strong>}else{<br>                    loading.postValue(false)<br>                    _obtainInfiniteListResponse.postValue(ResultOf.Failure(&quot;Failed with Exception &quot;, null))<br>                }<br>            }catch (e:Exception) {<br>                e.printStackTrace()<br>                _obtainInfiniteListResponse.postValue(ResultOf.Failure(&quot;Failed with Exception ${e.message} &quot;, e))<br>            }<br><br>        <strong>}<br>    }</strong><br><br>   <strong> fun prepareDataForAdapter(infiniteModel: InfiniteModel,startPosition:Int,size:Int): MutableList&lt;InfiniteAdapterModel&gt;{</strong><br>        var adapterModel = <em>mutableListOf</em>&lt;InfiniteAdapterModel&gt;()<br>        for (item in startPosition <em>until </em>size) {<br>            adapterModel.add(InfiniteAdapterModel(InfiniteAdapterModel.VIEW_TYPE_DATA,infiniteModel[item]))<br>        }<br>        adapterModel.add(InfiniteAdapterModel(InfiniteAdapterModel.VIEW_TYPE_PROGRESS,InfiniteModel.InfiniteModelItem(false,0,&quot;&quot;,0)))<br>        return adapterModel<br>    <strong>}</strong></pre><p>Step 6: Adapter -&gt; contains implementation to display data based on view type .</p><pre>override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>    return when (viewType)<br>    {<br>        <strong>VIEW_TYPE_DATA -&gt;</strong><br>        {//inflates row layout<br>            val view = LayoutInflater.from(parent.<em>context</em>).inflate(R.layout.<em>infinite_list_item</em>,parent,false)<br>            InfiniteListViewHolder(view)<br>        }<br>       <strong> VIEW_TYPE_PROGRESS -&gt;</strong><br>        {//inflates progressbar layout<br>            val view = LayoutInflater.from(parent.<em>context</em>).inflate(R.layout.<em>infinite_loading</em>,parent,false)<br>            InfiniteLoadingViewHolder(view)<br>        }<br>        else -&gt; throw IllegalArgumentException(&quot;Different View type&quot;)<br>    }<br>}<br><br>override fun getItemCount(): Int  = infiniteList.size<br><br>override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>    val row = infiniteList[position]<br>    when(row.type){<br>        <strong>VIEW_TYPE_DATA -&gt;</strong>{<br>            if (holder is InfiniteListViewHolder)<br>            {<br>                holder.bind(infiniteList[position].infiniteModelItem)<br>            }<br>        }<br>       <strong> VIEW_TYPE_PROGRESS -&gt; </strong>{<br>            if (holder is InfiniteLoadingViewHolder){<br>                holder.loadingItem.setOnClickListener <strong>{<br>                    </strong>originalModel?.<em>let </em><strong>{ </strong>it1 <strong>-&gt;<br>                        </strong>loadMore.loadMore(<br>                            startPosition as Int,<br>                            endPosition as Int,infiniteList, it1<br>                        )<br>                    <strong>}<br>                }<br>            </strong>}<br>        }<br>    }<br><br>}<br><br>override fun getItemViewType(position: Int): Int {<br>    var viewtype = infiniteList[position].type<br>    return when(viewtype)<br>    {<br>        1  -&gt; VIEW_TYPE_PROGRESS<br>        else -&gt; VIEW_TYPE_DATA<br>    }<br>}</pre><pre><strong>Note: VIEW_TYPE_PROGRESS -&gt; Display row with &quot;Loadmore&quot; button<br>      VIEW_TYPE_DATA -&gt; Display 10 row data  </strong></pre><p>Step 7: Logic to handle upper limit and lower limit of original data list to display 10 rows at a time.</p><pre>previousList.removeAt(previousList.size -1) // Remove &quot;Loadmore&quot; button from last position<br>val scrollPosition = previousList.size<br>infiniteAdapter?.<em>let </em><strong>{<br>    it</strong>.notifyItemRemoved(scrollPosition)<br>    var currentSize = scrollPosition<br>    var nextLimit = currentSize+10<br>    <strong>if(nextLimit&lt;=originalModel.size) {</strong><br>        val preparedData = infiniteListViewModel.prepareDataForAdapter(<br>            originalModel, currentSize,<br>            nextLimit<br>                  //  it.setFiniteList(startPosition,endPosition,infiniteAdapterModelList,originalModel,this)<br>        )<br>        previousList.addAll(preparedData)<br>        <strong>it</strong>.setFiniteList(currentSize,nextLimit,previousList,originalModel,this)<br>        <strong>it</strong>.notifyDataSetChanged()<br>    }<br><strong>else if(currentSize&lt;originalModel.size){</strong><br>        nextLimit =  originalModel.size<br>        val preparedData = infiniteListViewModel.prepareDataForAdapter(<br>            originalModel, currentSize,<br>            nextLimit<br>            //  it.setFiniteList(startPosition,endPosition,infiniteAdapterModelList,originalModel,this)<br>        )<br>        previousList.addAll(preparedData)<br>        currentSize = originalModel.size<br>        <strong>it</strong>.setFiniteList(currentSize,nextLimit,previousList,originalModel,this)<br>        <strong>it</strong>.notifyDataSetChanged()<br>    }</pre><pre><strong>Note : else if condition handles the situation to handle remaining data from original data list .</strong></pre><p><strong>Source code for the above functionality over GitHub:</strong></p><p><a href="https://github.com/chandragithub2014/MyReferenceProject/tree/master/features/listtypes/src/main/java/com/ref/listtypes/infinite">chandragithub2014/MyReferenceProject</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e90d553d30a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/infinite-list-using-kotlin-e90d553d30a4">Infinite List using Kotlin</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sectioned RecyclerView — Kotlin]]></title>
            <link>https://b-chandrasaimohan.medium.com/sectioned-recyclerview-kotlin-e27606d265?source=rss-3a2df6eb0d48------2</link>
            <guid isPermaLink="false">https://medium.com/p/e27606d265</guid>
            <category><![CDATA[jetpack-navigation]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack]]></category>
            <category><![CDATA[sectionedlist]]></category>
            <dc:creator><![CDATA[ChandraSaiMohan bhupathi]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 07:54:57 GMT</pubDate>
            <atom:updated>2021-01-02T18:05:35.551Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sectioned RecyclerView — Kotlin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nt4le6FQhYLB1erPbWbf0w.jpeg" /></figure><p><strong>Introduction: </strong>This story describes about sectioned RecyclerView in Android using Kotlin in combination with JetPack components.</p><p><strong>What is SectionedList? </strong>A sectioned list displays items in a list based on section. For instance displays list of state capitals for each country. Where country is category under which all its related state/capital info is displayed.</p><p><strong>Screen shots: </strong>The working example that implemented section list will have final output as below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_gBKZDOrZsTHjEEUqE6GQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCU3L33q8ks8yGbjP7UqDw.png" /></figure><p>The above example displays section wise State/capitals of a country .</p><p><strong>Steps to implement :</strong></p><p>To implement sectioned list we need to process received data from Server/DB in such a way that ,it is categorized as sections.</p><p>Step 1:</p><p>Create a model as below:</p><pre>data class StateCapital(<br>    val countries: List&lt;Country&gt;<br>) {<br>    data class Country(<br>        val country: String, // India<br>        val states: List&lt;State&gt;<br>    ) {<br>        data class State(<br>            val capital: String, // Hyderabad<br>            val name: String // Telangana<br>        )<br>    }<br>}</pre><p>Step 2: Prepare another model that categorizes data in to Parent (section header) and child (Parent’s corresponding child info)</p><pre>class ExpandableCountryModel {<br>    companion object{<br>        const val PARENT = 1<br>        const val CHILD = 2<br>       <br>    }<br>   lateinit var countryParent: StateCapital.Country<br>    var type : Int<br>    lateinit var countryChild : StateCapital.Country.State<br>    var isExpanded : Boolean<br>    private var isCloseShown : Boolean<br>   <br>    constructor( type : Int, countryParent: StateCapital.Country, isExpanded : Boolean = false,isCloseShown : Boolean = false ){<br>        this.type = type<br>        this.countryParent = countryParent<br>        this.isExpanded = isExpanded<br>        this.isCloseShown = isCloseShown<br><br>    }<br><br><br>    constructor(type : Int, countryChild : StateCapital.Country.State, isExpanded : Boolean = false,isCloseShown : Boolean = false){<br>        this.type = type<br>        this.countryChild = countryChild<br>        this.isExpanded = isExpanded<br>        this.isCloseShown = isCloseShown<br><br><br>    }<br>}</pre><p>Step 3: Process data to achieve sectioned view:</p><pre>fun prepareDataForSectionedAdapter(stateCapital: StateCapital) : MutableList&lt;ExpandableCountryModel&gt;{<br>    var expandableCountryModel = <em>mutableListOf</em>&lt;ExpandableCountryModel&gt;()<br>    for (states in stateCapital.countries) {<br>        expandableCountryModel.add(ExpandableCountryModel(ExpandableCountryModel.PARENT,states))<br>         for(capitals in states.states){<br>             expandableCountryModel.add(ExpandableCountryModel(ExpandableCountryModel.CHILD,capitals))<br>         }<br>    }<br>    return expandableCountryModel<br>}</pre><p>Step 4: Create a adapter to populate the view as below:</p><pre>class CountryStateSectionedAdapter(var countryClickedListener: CountryClickedListener, var countryStateModelList:MutableList&lt;ExpandableCountryModel&gt;) :  RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt;() {<br>    private var isFirstItemExpanded : Boolean = true<br>    private var actionLock = false<br>    lateinit var countryName:String<br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {<br>       return when(viewType) {<br>           ExpandableCountryModel.PARENT -&gt; {CountryStateParentViewHolder(LayoutInflater.from(parent.<em>context</em>).inflate(<br>               R.layout.<em>expandable_parent_item</em>, parent, false))}<br><br>            ExpandableCountryModel.CHILD -&gt; { CountryStateChildViewHolder(LayoutInflater.from(parent.<em>context</em>).inflate(<br>                R.layout.<em>expandable_child_item</em>, parent, false))  }<br><br>           else -&gt; {CountryStateParentViewHolder(LayoutInflater.from(parent.<em>context</em>).inflate(<br>               R.layout.<em>expandable_parent_item</em>, parent, false))}<br>       }<br>    }<br><br>    override fun getItemCount(): Int = countryStateModelList.size<br><br>    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {<br>       val row = countryStateModelList[position]<br>        when(row.type){<br>            ExpandableCountryModel.PARENT -&gt; {<br>                (holder as CountryStateParentViewHolder).countryName.<em>text </em>= row.countryParent.country<br>                countryName = row.countryParent.country<br>                holder.closeImage.<em>visibility </em>= View.<em>GONE<br>                </em>holder.upArrowImg.<em>visibility </em>= View.<em>GONE<br><br>            </em>}<br><br><br>            ExpandableCountryModel.CHILD -&gt; {<br>                (holder as CountryStateChildViewHolder).stateName.<em>text </em>= row.countryChild.name<br>                holder.capitalImage.<em>text </em>= row.countryChild.capital<br>                countryName?.<em>let </em><strong>{<br>                    </strong>holder.layout.<em>tag </em>= <strong>it<br>                }<br>                </strong>holder.stateName.<em>tag </em>= row.countryChild<br>                holder.layout.setOnClickListener <strong>{<br>                    </strong>var countryInfo =   holder.stateName.<em>tag<br>                    </em>countryClickedListener.onItemClick(holder.layout.<em>tag</em>.toString(),<br>                        countryInfo as StateCapital.Country.State<br>                    )<br>                <strong>}<br>            </strong>}<br>        }<br><br>    }<br><br><br>    override fun getItemViewType(position: Int): Int = countryStateModelList[position].type<br><br><br><br><br>    class CountryStateParentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>        internal var layout = itemView.country_item_parent_container<br>        internal var countryName : TextView = itemView.country_name<br>        internal var closeImage = itemView.close_arrow<br>        internal var upArrowImg = itemView.up_arrow<br><br>    }<br><br>    class CountryStateChildViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {<br>        internal var layout = itemView.country_item_child_container<br>        internal var stateName : TextView = itemView.state_name<br>        internal var capitalImage = itemView.capital_name<br><br>    }<br>}</pre><p>The code for the above sectioned list is available in the below Github link for reference:</p><ul><li><a href="https://github.com/chandragithub2014/MyReferenceProject/tree/master/features/listtypes/src/main/java/com/ref/listtypes/sectioned">chandragithub2014/MyReferenceProject</a></li><li><a href="https://github.com/chandragithub2014/MyReferenceProject/tree/master/features/listtypes/src/main/java/com/ref/listtypes/sectioned">chandragithub2014/MyReferenceProject</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e27606d265" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>