<?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 Mayank Bhatnagar on Medium]]></title>
        <description><![CDATA[Stories by Mayank Bhatnagar on Medium]]></description>
        <link>https://medium.com/@bhatnagarm?source=rss-604b6ffa5795------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7iAa8f65Vv1ZxhUXGJeI7A.jpeg</url>
            <title>Stories by Mayank Bhatnagar on Medium</title>
            <link>https://medium.com/@bhatnagarm?source=rss-604b6ffa5795------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:43:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhatnagarm/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[Key Updates in Android Fragments — AndroidDevSummit 2019]]></title>
            <link>https://proandroiddev.com/key-updates-in-android-fragments-androiddevsummit-2019-7a1e4215e44b?source=rss-604b6ffa5795------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a1e4215e44b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[devsummit2019]]></category>
            <category><![CDATA[androidx]]></category>
            <category><![CDATA[fragments]]></category>
            <dc:creator><![CDATA[Mayank Bhatnagar]]></dc:creator>
            <pubDate>Sat, 01 Feb 2020 20:50:32 GMT</pubDate>
            <atom:updated>2020-02-11T15:10:33.119Z</atom:updated>
            <content:encoded><![CDATA[<h3>Key Updates in Android Fragments — AndroidDevSummit 2019</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3qjOedE1NuKE7aXTn2nf3w.png" /></figure><p>Below are some key takeaways from Android Dev Summit 2019. Google brought us updates in almost all areas of Android Development.</p><p>Many of us have had a bad experience using Fragments. Almost all of us would have used Fragments in their applications extensively being the key component in Android. At the same time there have been many issues related to them starting from lifecycle, animations. Fortunately, the Android team addressed some of these areas which were showcased in Android Dev Summit held last year.</p><p>And in this story, I will share the recap for the session <a href="https://www.youtube.com/watch?v=RS1IACnZLy4&amp;list=PLWz5rJ2EKKc_xXXubDti2eRnIKU0p7wHd&amp;index=5"><strong>Fragments: Past, Present, and Future</strong></a></p><h3>Fragment testing artifact — FragmentScenario</h3><p><a href="https://developer.android.com/reference/androidx/fragment/app/testing/FragmentScenario">FragmentScenario</a> API from AndroidX allows developers to test a given Fragment in isolation of the parent activity as well as it provides methods to drive the Fragment’s lifecycle states for testing.</p><blockquote>Since it is built on top of ActivityScenario so it works for both Instrumentation and Roboelectric tests.</blockquote><p>It includes methods for launching the following types of fragments:</p><ul><li><strong><em>Graphical fragments</em></strong>, which contain a user interface.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65c4cd2dd7f5a9e2a3cbfdf20ca78cd5/href">https://medium.com/media/65c4cd2dd7f5a9e2a3cbfdf20ca78cd5/href</a></iframe><ul><li><strong><em>Non-graphical fragments</em></strong> (sometimes referred to as <em>headless fragments</em>), which store or perform short-term processing on information included in several activities.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0feb0fc66a0a4220f1853d68022e8fe7/href">https://medium.com/media/0feb0fc66a0a4220f1853d68022e8fe7/href</a></iframe><p>More information on this can be found below:</p><p><a href="https://developer.android.com/training/basics/fragments/testing">Test your app&#39;s fragments | Android Developers</a></p><h3><strong>FragmentFactory</strong></h3><p>You can now set a <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentFactory">FragmentFactory</a> on any <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentManager">FragmentManager </a>to control how new Fragment instances are instantiated.</p><p>Previously, Fragments required a no-arg default constructor so that an <em>Activity </em>would be able to re-create the Fragment<em> </em>after an orientation change or process death. The new <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentFactory">FragmentFactory </a>functionality will allow developers to fine-tune the creation (and re-creation) of their Fragment<em> </em>instances, opening up the possibility for constructor injection using a library like <a href="https://github.com/google/dagger">Dagger</a>.</p><p>To start working with <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentFactory">FragmentFactory </a>you need to create a class which will create an instance of fragments based on their class name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cf938991991f4bc9ec0935d47f64549/href">https://medium.com/media/2cf938991991f4bc9ec0935d47f64549/href</a></iframe><p>Then, in your Activity class update the <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentManager">FragmentManager</a> to use this factory when building fragments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/669f5b489e0a3bad840e4503365ef56c/href">https://medium.com/media/669f5b489e0a3bad840e4503365ef56c/href</a></iframe><blockquote>By supplying a custom <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentFactory"><em>FragmentFactory </em></a>to our <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentManager"><em>FragmentManager</em> </a>we will be able to take advantage of constructor injection with Dagger to create our Fragments and inject the relevant dependencies — no more need for field dependency injection!</blockquote><p>Now whenever you want to replace or add Fragments, you can directly use class name, rather than its instance.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4699b384ca9bbbe17b14a1494d93851/href">https://medium.com/media/a4699b384ca9bbbe17b14a1494d93851/href</a></iframe><h3>FragmentContainerView</h3><p>It’s a customized Layout designed specifically for Fragments. It extends <a href="https://developer.android.com/reference/android/widget/FrameLayout.html">FrameLayout</a>, so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.</p><p>The <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView">FragmentContainerView</a> is the strongly recommended container for dynamically added Fragments, replacing usage of <a href="https://developer.android.com/reference/android/widget/FrameLayout.html">FrameLayout </a>or other layouts.</p><h3>Ian Lake on Twitter</h3><p>Fragment 1.2.0 stable introduces FragmentContainerView as the recommended container for fragments, integrates in Lifecycle ViewModel SavedState, and fixes timing issues with onDestroyView() when using animations/transitions. Oh, and Lint checks :) https://t.co/RL50ssyqYd</p><p><a href="https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView">FragmentContainerView </a>should be used as a container for Fragments, commonly set in the xml layout of an activity, e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aedb687361ac3ccdb5fb983daa364ac/href">https://medium.com/media/6aedb687361ac3ccdb5fb983daa364ac/href</a></iframe><p>And then in the activity class fragment can be added to <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView">FragmentContainerView</a> the same way as we do when using <a href="https://developer.android.com/reference/android/widget/FrameLayout.html">FrameLayout</a>, eg:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8233d94ccde19450ba7aad26c369a476/href">https://medium.com/media/8233d94ccde19450ba7aad26c369a476/href</a></iframe><p><a href="https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView">FragmentContainerView </a>can also be used to add a Fragment by using the <strong><em>android:name</em></strong><em> or </em><strong><em>class</em></strong><em> </em>attribute. It will perform a one time operation that:</p><ul><li>Creates a new instance of the Fragment</li><li>Calls <a href="https://developer.android.com/reference/androidx/fragment/app/Fragment.html#onInflate(android.content.Context,%20android.util.AttributeSet,%20android.os.Bundle)">Fragment.onInflate(Context, AttributeSet, Bundle)</a></li><li>Executes a <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentTransaction">FragmentTransaction </a>to add the Fragment to the appropriate <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentManager">FragmentManager</a></li></ul><p>Optionally you can also include <strong><em>android:tag </em></strong>which can then be used to retrieve the fragment using <a href="https://developer.android.com/reference/androidx/fragment/app/FragmentManager.html#findFragmentByTag(java.lang.String)">FragmentManager.findFragmentByTag(String)</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7796adf6e8d86955a33dafad2db33068/href">https://medium.com/media/7796adf6e8d86955a33dafad2db33068/href</a></iframe><blockquote><a href="https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView">FragmentContainerView </a>should not be used as a replacement for other ViewGroups (FrameLayout, LinearLayout, etc) outside of Fragment use cases. It will only allow views to returned by a Fragment’s <a href="https://androidx.de/androidx/fragment/app/Fragment.html#onCreateView(LayoutInflater,%20ViewGroup,%20Bundle)">Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle)</a>. Attempting to add any other view will result in an <a href="https://developer.android.com/reference/java/lang/IllegalStateException.html">IllegalStateException</a>.</blockquote><p>Previously, attempting to customize the enter and exit animations of Fragments caused an <a href="https://b.corp.google.com/issues/37036000">issue</a> where the entering Fragment would be underneath the exiting Fragment until it completely exited the screen. This resulted in unpleasant -and erroneous- animations when transitioning between Fragments.</p><p><a href="https://developer.android.com/reference/androidx/fragment/app/FragmentContainerView">FragmentContainerView </a>fixes this Fragments <strong>z-ordering</strong> issue by ensuring that Fragments with exit animations are drawn first, which results in Fragments with entering animations to be drawn on top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwzvNOxeqyA44kvLLQwXVw.gif" /><figcaption><strong>layout with&lt;fragment&gt; tag</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ce6JyvUytCe9hHvdZ19SkA.gif" /><figcaption><strong>layout with&lt;fragmentContainerView&gt; tag</strong></figcaption></figure><p>It can be clearly seen that transition with FragmentContainerView tag looks and works much better when compared to the one with Fragment tag in xml.</p><h3>OnBackPressedDispatcher</h3><p><strong>Old Approach</strong>:- In order to notify fragments when the back button has been pressed, first of all you need a base fragment which all other fragments inherit from. This base fragment implements the following interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5fbfd82fe9b293f9392b230870f43ac/href">https://medium.com/media/b5fbfd82fe9b293f9392b230870f43ac/href</a></iframe><p>And then implementing the above interface in BaseFragment</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93bd106e1a6afa67925306cdb4d096e9/href">https://medium.com/media/93bd106e1a6afa67925306cdb4d096e9/href</a></iframe><p>Now finally in your hosting Activity, calling any implementations of the interface to notify fragment for the back pressed event:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb2495142a50f35ec6fed45c74e83947/href">https://medium.com/media/cb2495142a50f35ec6fed45c74e83947/href</a></iframe><p><strong>New Approach:</strong> Using <a href="https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher">OnBackPressedDispatcher </a>that can be used to register <a href="https://developer.android.com/reference/androidx/activity/OnBackPressedCallback.html">OnBackPressedCallback </a>instances for handling the ComponentActivity.onBackPressed() callback via composition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaaaf0f2842b81581b89d33ac6a24b22/href">https://medium.com/media/eaaaf0f2842b81581b89d33ac6a24b22/href</a></iframe><blockquote>Also, you can inject the <a href="https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher">OnBackPressedDispatcher </a>from Activity to Fragment. A similar example was showcased in <a href="https://www.youtube.com/watch?v=RS1IACnZLy4&amp;feature=youtu.be&amp;t=608">Android Dev Summit 2019</a>.</blockquote><h3>Summary</h3><p>This update is a big step forward when dealing with Fragments in Android applications. Finally developers have a dedicated view to store Fragments, and finally, they can inject variables in its constructor.</p><p>In case you missed the Android Dev Summit, check it out below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLWz5rJ2EKKc_xXXubDti2eRnIKU0p7wHd&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fplaylist%3Flist%3DPLWz5rJ2EKKc_xXXubDti2eRnIKU0p7wHd&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5jJ-e278BFY%2Fhqdefault.jpg%3Fsqp%3D-oaymwEWCKgBEF5IWvKriqkDCQgBFQAAiEIYAQ%3D%3D%26rs%3DAOn4CLDC7BPxWaQVhioT4G2JyD9ndahqcw&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="853" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/396967ecb13bf637cdb37cd035b4810b/href">https://medium.com/media/396967ecb13bf637cdb37cd035b4810b/href</a></iframe><p>Sandbox project to demonstrate all the above experience will be added a bit later. Also, share your thoughts about other pitfalls in comments below.</p><p>Stay tuned for more updates on Java, Kotlin and Android. <a href="https://medium.com/@bhatnagarm">Follow me</a> to get notified when I write new posts.</p><p><em>Problems or suggestions? You know what to do :)</em></p><p>Happy Coding! Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a1e4215e44b" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/key-updates-in-android-fragments-androiddevsummit-2019-7a1e4215e44b">Key Updates in Android Fragments — AndroidDevSummit 2019</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dive deep into Android’s ViewModel — Android Architecture Components]]></title>
            <link>https://medium.com/android-news/dive-deep-into-androids-viewmodel-android-architecture-components-e0a7ded26f70?source=rss-604b6ffa5795------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0a7ded26f70</guid>
            <category><![CDATA[architecture-components]]></category>
            <category><![CDATA[viewmodel]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android-architecture]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mayank Bhatnagar]]></dc:creator>
            <pubDate>Mon, 15 Oct 2018 06:34:07 GMT</pubDate>
            <atom:updated>2018-10-15T06:34:07.092Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dive deep into Android’s ViewModel — Android Architecture Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41h6EIkQ7dcNcPruu8j5Ow.png" /><figcaption><a href="https://developer.android.com/jetpack/arch/">Android Architecture Components</a></figcaption></figure><h3>Brief overview of Android Architecture Components</h3><p><a href="https://developer.android.com/topic/libraries/architecture/">Architecture components</a> are part of <a href="https://developer.android.com/jetpack">Android Jetpack</a> that persist data, manage lifecycle, make your app modular, help you avoid memory leaks, and prevent you from having to write boring boilerplate code.</p><ol><li><a href="https://developer.android.com/topic/libraries/architecture/viewmodel"><strong>ViewModel</strong></a> stores UI-related data that isn’t destroyed on app rotations.</li><li><a href="https://developer.android.com/topic/libraries/architecture/lifecycle"><strong>Lifecycle-Aware Components</strong></a><strong> </strong>perform actions in response to a change in the lifecycle status of another component, such as activities and fragments.</li><li><a href="https://developer.android.com/topic/libraries/architecture/livedata"><strong>LiveData</strong></a> is an observable data holder. It notifies observers when data changes so that you can update the UI. It is also lifecycle aware.</li><li><a href="https://developer.android.com/topic/libraries/architecture/room"><strong>Room</strong></a> is a robust SQLite object mapping library. Using it avoids boilerplate code and easily convert SQLite table data to Java objects.</li></ol><h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/166/1*mcw3Bc6X2z7Hmr1cVJr7ow.gif" /><figcaption>Screen Rotation</figcaption></figure><p>Most of us have would have faced a issue — while we <strong>rotate the phone,</strong> the UI looses it’s state or in some cases even the app crashes.</p><p>The quickest way to handle this would be :</p><ul><li>Saving the data into bundle during onSaveInstanceState and retaining the same data within onCreate, but in case of complex data it is easy to hit the limit size of a Parcelable.</li><li>Process configuration changes on our own.</li><li>Fixing the Activity orientation to portrait mode, but it wouldn’t be correct in case the application needs to run both in portrait as well as landscape mode.</li></ul><p>During Google I/O 2017, Android Team released ViewModel during Google I/O 2017 that can handle such scenarios.</p><h3>What is ViewModel?</h3><p>As per <a href="https://developer.android.com/topic/libraries/architecture/viewmodel">Android’s Official documentation</a>, ViewModel class is designed to</p><blockquote>Store and manage UI-related data in a lifecycle conscious way. It allows data to survive configuration changes such as screen rotations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*kWwjlkOEyTV6M7W7tZrs1w.png" /></figure><p>A ViewModel is always created in association with a scope (a fragment or an activity) and will be retained until its associated Activity or Fragment is disposed of forever — that means view data survives events like a Fragment / Activity being recreated due to rotation.</p><p>Mainly a ViewModel is responsible for : —</p><ul><li>preparing and managing the data for an <a href="https://developer.android.com/reference/android/app/Activity"><strong>Activity</strong></a><strong> </strong>or a <a href="https://developer.android.com/reference/android/support/v4/app/Fragment"><strong>Fragment</strong></a>.</li><li>retains the data during configuration changes, e.g. — Rotation</li><li>handles the communication of the Activity / Fragment with the rest of the application (e.g. calling the business logic classes).</li></ul><p><a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html">ViewModel</a> separates ownership of view data and logic from lifecycle-bound entities like Activities and Fragments. ViewModels not only eliminate common lifecycle issues, they also help build UIs that are more modular and easier to test.</p><p>The Activity or the Fragment are able to observe changes in the ViewModel via LiveData or Android Data Binding.</p><blockquote>Note : — ViewModel’s only responsibility is to manage the data for the UI. It <strong>should never</strong> access your view hierarchy or hold a reference back to the Activity or the Fragment.</blockquote><p>The following diagram shows the life cycle of ViewModel component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*Ls1GAobtqGc8G7fXUjdZ0g.png" /><figcaption>Lifecycle of a ViewModel</figcaption></figure><h3>How does a ViewModel survive configuration changes?</h3><p>First, let’s visit the Android documentation to see how the ViewModel is consumed. The following code is the example of how an Activity uses the SDK in order to provide a ViewModel that is retained on configuration changes.</p><h4>Get the instance of ViewModel</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02bbb44fee944c8fe774fbc2bd515927/href">https://medium.com/media/02bbb44fee944c8fe774fbc2bd515927/href</a></iframe><h4>Writing your ViewModel class</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/749b670e32e34a8051fee3ea2718f7e4/href">https://medium.com/media/749b670e32e34a8051fee3ea2718f7e4/href</a></iframe><blockquote>ViewModelProviders.of(this).get(MyViewModel.class);</blockquote><p>From the above snippet, we can infer that it’s retrieving a ViewModel of type <strong><em>MyViewModel</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBBGFhy5r4avSF9gZ9BGbQ.png" /><figcaption>UML diagram for ViewModel Creation</figcaption></figure><p>Let’s dig deeper into how each of these classes and it’s methods, starting with <strong>ViewModelProviders.of </strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/372181e66fb589f7c24c1a4914518a14/href">https://medium.com/media/372181e66fb589f7c24c1a4914518a14/href</a></iframe><blockquote>It seems like <strong><em>ViewModelProviders.of</em></strong> is just a factory of <strong><em>ViewModelProvider</em></strong>, which depends upon <strong><em>ViewModelFactory</em></strong> and a <strong><em>ViewModelStore</em></strong>.</blockquote><h4>ViewModelFactory</h4><p>It is a class which uses reflection to instantiate the ViewModel class which was passed to <strong><em>ViewModelProviders.of(this).get(MyViewModel.class)</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b68fb54b3ad7bd3461952d2b976d265/href">https://medium.com/media/0b68fb54b3ad7bd3461952d2b976d265/href</a></iframe><p>If the ViewModel class is of type <strong><em>AndroidViewModel</em></strong>, then it will create a new instance passing the <strong><em>Application </em></strong>instance as a single parameter in the constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f243672e23309e38467f0f998d5fc4c7/href">https://medium.com/media/f243672e23309e38467f0f998d5fc4c7/href</a></iframe><h4><strong>Creating a custom ViewModelProviderFactory</strong></h4><p>You can also create a custom Factory class that overrides a generic ViewModelFactory to initialize your ViewModel class and passing the data (if needed) to initialize your ViewModel class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0640ad3a0b443536b6289153763e16ac/href">https://medium.com/media/0640ad3a0b443536b6289153763e16ac/href</a></iframe><p>The factory created above can then be passed to <strong><em>ViewModelProviders</em></strong> class while requesting the ViewModel instance</p><pre>//initializing the custom factory class <br>MyViewModelFactory factory = new MyViewModelFactory(data1, data2);</pre><pre>ViewModelProviders.<em>of</em>(this, factory).get(MyViewModel.class);</pre><blockquote>Note: — If the ViewModel class is of type AndroidViewModel, then it will create a new instance passing the application as a single parameter in the constructor, otherwise, it calls the parent implementation.</blockquote><h4>ViewModelStores</h4><p>This class job is of abstracting the call to the <strong><em>holderFragmentOf (Activity/Fragment) </em></strong>static method inside the HolderFragmentManager. This method will be responsible for returning a ViewModelStoreOwner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5308ac7b4e1bf2b6a9eff814f30202c6/href">https://medium.com/media/5308ac7b4e1bf2b6a9eff814f30202c6/href</a></iframe><blockquote><strong><em>ViewModelStores.of </em></strong>seems to be similar method to <strong><em>ViewModelProviders.of</em></strong>, creating new instances of the <strong><em>ViewModelStore </em></strong>when required.</blockquote><h4>ViewModelStore</h4><p>It seems to be a simple store with a HashMap&lt;String, ViewModel&gt;, where the key is the classname of the view model and the Object the ViewModel itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94484d6bfb3ff6d9782372ee3046c77c/href">https://medium.com/media/94484d6bfb3ff6d9782372ee3046c77c/href</a></iframe><h4>ViewModelStoreOwner</h4><p>It is an <strong><em>Functional Interface</em></strong> and as the name implies is the owner of a ViewModelStore. This can be any class that implements the getViewModelStore() defined by this interface.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3f9070a1c6cdda249ff1fc4f3c53873/href">https://medium.com/media/e3f9070a1c6cdda249ff1fc4f3c53873/href</a></iframe><p>In the library, the <strong><em>ViewModelStoreOwner</em></strong> is the <strong><em>HolderFragment</em></strong> class. This class has a ViewModelStore variable that can be accessed by the getViewModelStore() method.</p><h4>HolderFragment</h4><p>HolderFragment is a regular <strong><em>Android Headless Fragment</em></strong>. It is the scope where all ViewModels inside the ViewModelStore will live.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb93a9d4b8f75cf833e11d67528bbc0b/href">https://medium.com/media/eb93a9d4b8f75cf833e11d67528bbc0b/href</a></iframe><h3>Who owns the HolderFragment?</h3><h4>HolderFragmentManager</h4><p>The HolderFragment has an inner static class named <strong><em>HolderFragmentManager</em></strong>. The HolderFragmentManager creates and manages HolderFragment instances.</p><p>After creating the instances it associates them with an Activity or Fragment.<br>The whole process is done using the methods <strong><em>holderFragmentFor(Activity)</em></strong> and <strong><em>holderFragmentFor(Fragment)</em></strong>.</p><p>These methods will behave in two different ways if there is or not an instance of the HolderFragment.</p><p>For the case when there is no instance of the HolderFragment, these methods will:</p><ul><li>Create an instance of HolderFragment.</li><li>Add the new instance to the parent(Activity/Fragment) FragmentManager. This will result in the expansion of the scope of the ViewModels inside the HolderFragment .</li><li>Register a callback to the Activity/Fragment lifecycle onDestroy() callback method. BecauseHolderFragment is inside an Activity/Fragment FragmentManager, so when the Activity/Fragment is destroyed its onDestroy() method will be called and the ViewModelStore will be cleared. Lastly, the HolderFragment instance will be removed from the HolderFragmentManager HashMap that associated it with an Activity/Fragment when the registered callback is invoked.</li><li>Add the holder Fragment to a HashMap where it’s key is an Activity/Fragment.</li><li>Return the HolderFragment instance.</li></ul><p>When there is already an instance of the HolderFragment these methods will look up and return the instance already in the HashMap.</p><h4>How does HolderFragment retains the state ?</h4><p>By setting retain instance to true and not providing a view, the HolderFragment becomes essentially a headless Fragment that is retained for as long as the Activity is not destroyed.</p><pre>public HolderFragment() {<br>   <strong>setRetainInstance(true);</strong><br>}</pre><blockquote><strong><em>public void setRetainInstance (boolean retain)</em></strong></blockquote><p>Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:</p><ul><li><strong><em>onDestroy()</em></strong> will not be called (but <strong><em>onDetach()</em></strong> still will be, because the fragment is being detached from its current activity).</li><li><strong><em>onCreate(Bundle)</em></strong> will not be called since the fragment is not being re-created.</li><li><strong><em>onAttach(Activity)</em></strong> and <strong><em>onActivityCreated(Bundle)</em></strong> will still be called.</li></ul><h4>Retrieving ViewModel instance</h4><p>Since we have a basic understanding of ViewModelProvider creation and its dependencies, we will now look into how it creates and retrieves theViewModel instances, retaining them throughout configuration changes. Let’s look into the method call : —</p><pre>get(MyViewModel.class)</pre><p>It tries to retrieve a <strong><em>MyViewModel</em></strong> instance from the store. If none is there, it uses the factory to create it and then stores it into <strong><em>HashMap&lt;String, ViewModel&gt;</em></strong>. In order to retrieve the already created ViewModel, it generates a key from the class qualified name.</p><h3>Summary</h3><p>In this post, I explored the very basics of the new ViewModel class. The key takeaways are:</p><ul><li>The <a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModel.html">ViewModel</a> class is designed to hold and manage UI-related data in a life-cycle conscious way. This allows data to survive configuration changes such as screen rotations.</li><li>ViewModels separate UI implementation from your app’s data.</li><li>The lifecycle of a ViewModel extends since the time when associated UI controller is first created, till it is completely destroyed.</li><li>Never store a UI controller or Context directly or indirectly in a ViewModel. This includes storing a View in a ViewModel. Direct or indirect references to UI controllers defeat the purpose of separating the UI from the data and can lead to memory leaks.</li><li>A HolderFragment is a headless Fragment (without UI) that is added to the Fragment stack with setRetainInstance(true).</li></ul><p>If you feel like something was not clear, have any suggestions or something to add up, please drop your comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0a7ded26f70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/dive-deep-into-androids-viewmodel-android-architecture-components-e0a7ded26f70">Dive deep into Android’s ViewModel — Android Architecture Components</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Magic lies here - Statically vs Dynamically Typed Languages]]></title>
            <link>https://medium.com/android-news/magic-lies-here-statically-typed-vs-dynamically-typed-languages-d151c7f95e2b?source=rss-604b6ffa5795------2</link>
            <guid isPermaLink="false">https://medium.com/p/d151c7f95e2b</guid>
            <category><![CDATA[typing]]></category>
            <category><![CDATA[static-vs-dynamic-typing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[static-typing]]></category>
            <category><![CDATA[dynamic-typing]]></category>
            <dc:creator><![CDATA[Mayank Bhatnagar]]></dc:creator>
            <pubDate>Sun, 09 Sep 2018 14:35:34 GMT</pubDate>
            <atom:updated>2018-09-24T09:07:35.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>Type Checking</h3><p>The process of verifying and enforcing the constraints of types . <strong>Type Checking </strong>may occur either at <a href="https://en.wikipedia.org/wiki/Compile-time">compile-time</a> <em>(a static check)</em> or at <a href="https://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase)">run-time</a><em> (dynamic check)</em>.</p><p>If a language specification requires its typing rules strongly (i.e., more or less allowing only those automatic type conversions that do not lose information), one can refer to the process as <strong>S<em>trongly </em></strong>typed, if not, as <strong>We<em>akly</em></strong><em> </em>typed.</p><blockquote>Type checking is all about ensuring that the program is type-safe, minimizing the possibility of type errors. For eg — type error could be a situation where an operation is performed on a data of type integer with the intent that it is a float, or even something such as adding a string and an integer together</blockquote><pre>a = “5” + 2;</pre><p>Despite of the fact that in many languages both strings and integers can make use of the + operator, this would often result in a type error because this expression is usually not meant to handle multiple data types.</p><p>When a program is considered not to be type-safe, there is no single standard course of action that happens upon encountering a type error. Many Programming languages throw type errors which halts the run-time or compilation of the program, depending on the language type — static or dynamically typed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BddwVWW6hFU0miT9DCbUWQ.png" /></figure><p>Now since we have a basic understanding of what types are and how type checking works, we can start with the two primary methods of type checking: <strong>statically </strong>and <strong>dynamically typed languages</strong>.</p><h3>Static typed languages</h3><p>A language is <strong>statically-typed</strong> if the type of a variable is known at <strong>compile-time</strong> instead of at run-time. Common examples of statically-typed languages include Java, C, C++, FORTRAN, Pascal and Scala.</p><p>In Statically typed languages, once a variable has been declared with a type, it cannot ever be assigned to some other variable of different type and doing so will raise a type error at compile-time(some IDE’s generally shows a Red Cross mark denoting the error).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*75q760EAOyR9egJCEODu1w.png" /><figcaption>Type declaration constraints</figcaption></figure><h4><strong>Java Example</strong></h4><p>Statically-typed languages require you to declare the data types of your variables before you use them</p><pre>int data;<br>data = 50;<br>data = “Hello World!”; // causes an compilation error</pre><p>Note: the statement above (which binds an integer value, and then binds a string value to the same variable name <strong>data</strong>) is illegal. But in a dynamically-typed language this sequence of statements is perfectly fine.</p><h4>Advantages:</h4><ul><li>A large class of errors are caught in the early stage of development process.</li><li>Static typing usually results in compiled code that executes more quickly because when the compiler knows the exact data types that are in use, it can produce optimized machine code (i.e. faster and/or using less memory).</li></ul><p>For a list of languages with static type checking, see the <a href="https://en.wikipedia.org/wiki/Category:Statically_typed_programming_languages">category for statically typed languages.</a></p><h3>Dynamically typed languages</h3><p>A language is <strong>dynamically-typed</strong> if the type of a variable is checked during <strong>run-time</strong>. Common examples of dynamically-typed languages includes JavaScript, Objective-C, PHP, Python, Ruby, Lisp, and Tcl.</p><p>In Dynamically typed languages, variables are bound to objects at run-time by means of assignment statements, and it is possible to bind the same variables to objects of different types during the execution of the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*YlHmP3TaXSvdnGK-Gn5z3Q.png" /><figcaption>Type declaration constraints</figcaption></figure><p>Dynamic type checking typically results in less optimized code than static type checking. It also includes the possibility of run time type errors and forces run time checks to occur for every execution of the program (instead of just at compile-time).</p><h4>Python Example</h4><p>Dynamically-typed languages do not require you to declare the data types of your variables before you use them</p><pre>data = 10;<br>data = “Hello World!”; // no error caused</pre><p>The above statement assigns a new value to the same variable <strong>data </strong>of different data type than the one assigned earlier. The program will execute successfully without any error. This is characteristic to dynamic-typed programming languages.</p><h4>Advantages:</h4><ul><li>Implementations of dynamically type-checked languages generally associate each run time object with a type tag (i.e., a reference to a type) containing its type information. This run-time type information (RTTI) can also be used to implement dynamic dispatch, late binding, down-casting, reflection, and similar features.</li><li>The absence of a separate compilation step means that you don’t have to wait for the compiler to finish before you can test your code changes. This makes the debug cycle much shorter and less cumbersome.</li></ul><p>For a list of such languages, see the category for <a href="https://en.wikipedia.org/wiki/Category:Dynamically_typed_programming_languages">dynamically typed programming languages.</a></p><h3>Strongly typed languages</h3><p>A <strong>strongly-typed</strong> language is one in which variables are bound to specific data types, and will result in type errors if types do not match up as expected in the expression — regardless of when type checking occurs.</p><blockquote><strong><em>Python </em></strong><em>is strong-typed, and so is </em><strong><em>Java</em></strong><em>.</em></blockquote><h4>Python Example</h4><pre>temp = “Hello World!”<br>temp = temp + 10; // program terminates with below stated error</pre><blockquote>Traceback (most recent call last):<br>File “…\Test.py”, line 48, in NFG<br> temp = temp + 10; <br>TypeError: cannot concatenate ‘str’ and ‘int’ objects</blockquote><p>In the above example, temp is of str type. In the second line, we tried attempting to add 10 (an int) to a variable of str type. As we can see, a TypeError is returned, indicating that a str object cannot be concatenated with an int object. This is what characterizes strong typed languages: variables are bound to a particular data type.</p><h3>Weakly typed languages</h3><p>A <strong>weakly-typed </strong>language on the other hand is a language in which variables are not bound to a specific data type; they still have a type, but type safety constraints are lower compared to strongly-typed languages.</p><blockquote><strong>PHP </strong>is weakly-typed, and so is <strong>C</strong>.</blockquote><h4>PHP Example</h4><pre>$temp = “Hello World!”;<br>$temp = $temp + 10; // no error caused<br>echo $temp;</pre><p>In this example, variable <strong>temp</strong> is initially a string type. In the second line, we add this string variable to 10, an integer. This is permitted in PHP, and is characteristic of all weakly-typed languages.</p><h3>Conclusion</h3><p>In this post, I answered few questions regarding Statically and Dynamically typed languages. I also covered Strongly-typed and Weakly-typed languages.</p><p>Just as the assumption that all Strongly-typed languages are Statically-typed, not all Weakly-typed languages are Dynamically-typed; PHP is a dynamically-typed language, but C — also a weakly-typed language — is indeed statically-typed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d151c7f95e2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/android-news/magic-lies-here-statically-typed-vs-dynamically-typed-languages-d151c7f95e2b">Magic lies here - Statically vs Dynamically Typed Languages</a> was originally published in <a href="https://medium.com/android-news">AndroidPub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>