<?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 Sumit Mishra on Medium]]></title>
        <description><![CDATA[Stories by Sumit Mishra on Medium]]></description>
        <link>https://medium.com/@extra_space?source=rss-f2ea94bbbcd3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*kpC8QTLWe4mvYCYvUS6lOw.jpeg</url>
            <title>Stories by Sumit Mishra on Medium</title>
            <link>https://medium.com/@extra_space?source=rss-f2ea94bbbcd3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 18:23:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@extra_space/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[Practical Guide To Solve OutOfMemoryError in Android Application]]></title>
            <link>https://medium.com/mindorks/practical-guide-to-solve-outofmemoryerror-in-android-application-8cccfdc5c60c?source=rss-f2ea94bbbcd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cccfdc5c60c</guid>
            <category><![CDATA[mindorks]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Sumit Mishra]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 04:31:04 GMT</pubDate>
            <atom:updated>2020-06-10T04:31:04.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZXn34Vq4-OAWnhRD.jpg" /></figure><p>OutOfMemoryError or simply OOM is something that every Android developer must have encountered with. If you haven’t seen any OOM in your Android application, then you are going to have one in future. The OutOfMemoryError comes in Android due to memory leaks. So, in order to remove the OutOfMemoryError, you need to remove memory leaks from your Android application.</p><p><strong>Originally published at </strong><a href="https://blog.mindorks.com/practical-guide-to-solve-out-of-memory-error-in-android-application"><strong>blog.mindorks.com</strong></a></p><p>In this blog, we will solve the OutOfMemoryError in Android with the help of some practical examples. So, let’s get started with the basics of Memory Leak in Android.</p><h4>What is a Memory Leak?</h4><p>When you run some applications on the Android device, then the Android system will provide some memory to your application for its working. All the variable creation, function creation, activity creation, etc takes place in that memory only.</p><p><strong><em>For example</em></strong>, if the Android System allocates 100MB for your application, then your application can use 100MB max at one particular time. With due course of time, if space allocated to the application gets reduced or very few amounts of space is left, then the Garbage Collector(GC) will release the memory that is being held by those variables and activities that are of no use. In this way, the application will again gain some space.</p><p><strong>NOTE:</strong> The Garbage Collector performs the task of releasing the memory automatically and you don’t have to do anything for this.</p><p>But sometimes, when you write the code in a bad manner such that your code holds the references of objects that are not required anymore, then in this situation, the Garbage Collector is unable to release the unused space and no space will be left for the application for its further working. This is called a <strong>Memory Leak</strong>.</p><p>Due to the phenomenon of Memory Leak in Android, we encounter with the OutOfMemoryError in Android because your code is holding the references of the objects that are not required anymore and the Garbage Collector is unable to perform its job and your application uses all the space allocated to it by the Android System and is demanding for more.</p><h4>What may be the reasons for OutOfMemoryError?</h4><p>There are various reasons that can lead to OutOfMemoryError in Android. Some of the common reason for Memory Leaks that results in OutOfMemoryError are:</p><ul><li>Use of Static view/context/activity</li><li>Register and unregister listeners</li><li>Non-Static inner class</li><li>Wrong use of getContext() and getApplicationContext()</li></ul><p>Let’s learn one by one in detail.</p><h4>Use of static views/context/activity</h4><p>If you are using some static views/context/activity then you are going to have OutOfMemoryError(if your activities are dealing with lots of space). This is because the view or the context or the activity will be held by the application until the application is alive and due to this the memory taken by these will not be released by the Garbage Collector.</p><p><strong><em>For example</em></strong>, In your application, you are having 4 activities i.e. <em>A</em>, <em>B</em>, <em>C</em>, and <em>D</em>. Activity “<em>A</em>” is your main activity and you can open the activity <em>B</em>, <em>C</em>, and <em>D</em> from <em>A</em>. Now, suppose the activities <em>B</em>, <em>C</em>, and <em>D</em> are holding static reference to its context and each activity is using 2MB and total memory allocated to the application by the Android System is 4MB. So, when activity “<em>B</em>” will be started then the memory used by the application will be 2MB. Now, come back to the activity “<em>A</em>” and start activity “<em>C</em>”. Now, the memory used by the application will be 4MB(2MB for Activity <em>B</em> and 2MB for Activity <em>C</em>). Again come back to activity “<em>A</em>” and start activity “<em>D</em>”. Now, your app will require 6MB(2MB for <em>B</em>, 2MB for <em>C</em> and 2MB for <em>D</em>), but the allocated memory is 4MB. So, here while opening the activity “<em>D</em>”, you will get OutOfMemoryError because the allotted memory is 4MB and you are demanding for 6MB.</p><p>Let’s look at one practical implementation. Here in this example, I am using Bitmap. By using more than 5 images of size 1MB each, my application will encounter OutOfMemoryError on my mobile device. In your case, the number of images that can result in OutOfMemoryError can be more than or less than 5. You can find the limit by adding images to the BitmapArray one by one and whenever you get the OOM, that is the limit of your device.</p><p>So, my application is having one <em>MainActivity</em> and from this activity, I can go to “<em>ActivityB</em>” and “<em>ActivityC</em>”. Both these activities i.e. “<em>ActivityB</em>” and “<em>ActivityC</em>” are having static reference of their context. So, space used by these activities will not be deleted by Garbage Collector.</p><p>Following is the code for <em>ActivityB</em>:</p><pre>class ActivityB : AppCompatActivity() {<br>    // static context<br>    companion object {<br>        lateinit var context: Context<br>    }<br>    val bitmapArray = ArrayList&lt;Bitmap&gt;()<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_b)<br>        context = this<br>        Thread(Runnable {<br>            try {<br>                // adding 3 images to bitmapArray<br>                val bitmap1: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1)<br>                val bitmap2: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image2)<br>                val bitmap3: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image3)<br>                bitmapArray.add(bitmap1)<br>                bitmapArray.add(bitmap2)<br>                bitmapArray.add(bitmap3)<br>            } catch (e: Exception){<br>                Logger.getLogger(ActivityB::class.java.name).warning(e.toString())<br>            }<br>        }).start()<br>    }<br>}</pre><p>Following is the code for the <em>ActivityC</em>:</p><pre>class ActivityC : AppCompatActivity() {<br>    companion object {<br>        lateinit var context: Context<br>    }<br>    val bitmapArray = ArrayList&lt;Bitmap&gt;()<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_c)<br>        context = this<br>        Thread(Runnable {<br>            try {</pre><pre>                val bitmap1: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1)<br>                val bitmap2: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image2)<br>                val bitmap3: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image3)<br>                bitmapArray.add(bitmap1)<br>                bitmapArray.add(bitmap2)<br>                bitmapArray.add(bitmap3)<br>            } catch (e: Exception){<br>                Logger.getLogger(ActivityC::class.java.name).warning(e.toString())<br>            }</pre><pre>        }).start()<br>    }<br>}</pre><p>So, if you launch the <em>ActivityB</em> from <em>MainActivity</em>, then there will no OutOfMemoryError because the limit for my mobile device is 5 images and in the <em>ActivityB</em>, I am using only 3 images.</p><p>Now, come back to the <em>MainActivity</em> and launch <em>ActivityC</em> and you will get OutOfMemoryError because here in the <em>ActivityC</em>, we are using 3 images and since we are using the static context in both <em>ActivityB</em> and <em>ActivityC</em>, the reference of <em>ActivityB</em> is still with us and overall we have 6 images(3 from <em>ActivityB</em> and 3 from <em>ActivityC</em>) and the limit for my mobile device is 5 images. So, OutOfMemoryError will occur.</p><p>To remove this error, make the context or view or activity, Non-Static.</p><pre>class ActivityB : AppCompatActivity() {<br>    <br>    lateinit var context: Context<br>    val bitmapArray = ArrayList&lt;Bitmap&gt;()</pre><pre>    override fun onCreate(savedInstanceState: Bundle?) {<br>        ...<br>    }<br>}</pre><h4>Register and unregister listeners</h4><p>In Android, we use various kind of listeners to listen to the changes like the location change. So, never forgot to unregister your listener when you are done using that listener. If you are not unregistering the listeners, then the listener will be present in the background and the space taken by the listener will not be deleted by the Garbage Collector even when the listener is of no use. So, it is better to unregister the listener if not in use. Let’s look at one practical example.</p><p>In this example, we are having one Singleton class named “<em>SomeListener</em>” that will be having two functions i.e. <em>register()</em> and <em>unregister()</em>. The <em>register()</em> function is used to add the activity in an activity array and the <em>unregister()</em> function is used to remove the activity from the activity array. Following is the code for the Singleton class:</p><pre>object SomeListener {<br>    private val activityArray = ArrayList&lt;Activity&gt;()</pre><pre>    fun register(activity: Activity) {<br>        activityArray.add(activity)<br>    }<br>    fun unregister(activity: Activity) {<br>        activityArray.remove(activity)<br>    }<br>}</pre><p>In my mobile device, if I am adding more than 5 images, then the application will give OutOfMemoryError. So, in this example, we will be having three activities i.e. <em>MainActivity</em>, <em>ActivityB</em>, and <em>ActivityC</em>. The <em>ActivityB</em> and <em>ActivityC</em> will be called from <em>MainActivity</em> and in the <em>onCreate()</em> function of both these activities, we will call the <em>register()</em> method of the Singleton class to add the activities in the activity array.</p><p>Following is the code of <em>ActivityB</em>:</p><pre>class ActivityB : AppCompatActivity() {<br>    <br>    val bitmapArray = ArrayList&lt;Bitmap&gt;()<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_b)<br>        Thread(Runnable {<br>            try {<br>                // adding 3 images to bitmapArray<br>                val bitmap1: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1)<br>                val bitmap2: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image2)<br>                val bitmap3: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image3)<br>                bitmapArray.add(bitmap1)<br>                bitmapArray.add(bitmap2)<br>                bitmapArray.add(bitmap3)<br>            } catch (e: Exception){<br>                Logger.getLogger(ActivityB::class.java.name).warning(e.toString())<br>            }<br>        }).start()<br>        // calling the register() function<br>        SomeListener.register(this)<br>    }<br>}</pre><p>Following is the code of <em>ActivityC</em>:</p><pre>class ActivityC : AppCompatActivity() {<br>    <br>    val bitmapArray = ArrayList&lt;Bitmap&gt;()<br>    <br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_c)<br>        Thread(Runnable {<br>            try {<br>                // adding 3 images to bitmapArray<br>                val bitmap1: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1)<br>                val bitmap2: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image2)<br>                val bitmap3: Bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image3)<br>                bitmapArray.add(bitmap1)<br>                bitmapArray.add(bitmap2)<br>                bitmapArray.add(bitmap3)<br>            } catch (e: Exception){<br>                Logger.getLogger(ActivityC::class.java.name).warning(e.toString())<br>            }<br>        }).start()<br>        // calling the register() function<br>        SomeListener.register(this)<br>    }<br>}</pre><p>If we call the <em>ActivityB</em> from <em>MainActivity</em>, then the reference of 3 images will be stored(as we are storing in the Singleton class). Here, no OutOfMemoryError will be shown because our limit is of 5 images. Now, if we come back to the <em>MainActivity</em> and call the <em>ActivityC</em>, then we will get OutOfMemoryError because initially, we are having reference to 3 images and when <em>ActivityC</em> is launched, then 3 more images came and overall we have reference to 6 images(as we are using the same Singleton class) and our limit is of 5 images. So, we will encounter MemoryOutOfBoundError.</p><p>To remove this error, you have to deregister the listener when the activity is closed or of no use. So, add the below lines of code to unregister the listener when the activity is stopped:</p><pre>override fun onStop() {<br>    SomeListener.unregister(this)<br>    super.onStop()<br>}</pre><h4>The nested class must be Static:</h4><p>If you are having some nested class in the application, then make it a static class because the static class does not need the outer class implicit reference. So, if you are using the inner class as non-static then it makes the outer class alive until the application is alive. So, this can lead to OutOfMemoryError if your class is using a lot of memory. So, it is better to make the inner class Static.</p><p>In Java, you have to make the inner class static by your own but in Kotlin, the inner class is by default static in nature. So, you need not worry about static inner class in Kotlin.</p><h4>Wrong use of getContext() and getApplicationContext() in third party libraries</h4><p>We use many third-party libraries in our application and most of them use Singleton class. So, if you are passing some context to a third-party library and that third-party library is beyond the scope of the current activity, then use <em>getApplicationContext()</em> and not <em>getContext()</em>.</p><p>Generally, we do the below thing in our application:</p><pre>SomeThirdPartyLibrary.initialize(this)</pre><p>Here, initialize is some static function in that library and it uses the context something like this:</p><pre>SomeThirdPartyLibrary {<br>  object companion {<br>    initialize(Content context) {<br>       this.context = context.getApplicationContext()<br>    }<br>  }<br>}</pre><p>But some of the libraries don’t use the above notation. So, in that case, it will use the context of the current activity and due to this, the reference of the current activity will be held until the application is alive and this can result in OutOfMemoryError(as the initialize function is static).</p><p>So, it is better to use the <em>getApplicationContext()</em> in your code explicitly and don’t depend on third-party libraries to do that.</p><p>These are some of the techniques that can be used to remove OutOfMemoryError from our application. It is better to write the code that doesn’t give any OutOfMemoryError. Still, if your project is very big and you are getting it harder to find the class that is responsible for OutOfMemoryError, then you can use the memory profiler of Android Studio to find the classes responsible for OutOfMemoryError.</p><p><a href="https://www.youtube.com/watch?v=FxDa2td6Ej8"><strong>Learn how to use Android Studio Memory Profiler</strong></a></p><p>Also, there is one library called <strong>LeakCanary</strong>, that tells you about the class that is responsible for memory leaks in your Android application(if any).</p><p><a href="https://square.github.io/leakcanary/"><strong>Learn more about LeakCanary</strong></a></p><h4>Conclusion</h4><p>In this blog, we learned how to remove OutOfMemoryError in Android. This can be removed by using a non-static reference of views/context/activity, by registering and unregistering the listeners, by using a static inner class. So, in the future, if you are writing some code in Android, then I am sure that you are going to use these to avoid OutOfMemoryError.</p><p>That’s it for this blog. Hope you learned something new today.</p><p>If you are preparing for your next Android Interview, <a href="https://mindorks.com/android-app-development-online-course-for-professionals"><strong>Join our Android Professional Course</strong></a> to learn the latest in Android and land job at top tech companies.</p><p>Happy Learning :)</p><p><strong>Team MindOrks!</strong></p><p><strong>Also, Let’s connect on</strong> <a href="https://twitter.com/hiii_sumit"><strong>Twitter</strong></a><strong>,</strong> <a href="https://www.linkedin.com/in/mishra3452/"><strong>Linkedin</strong></a><strong>,</strong> <a href="https://github.com/mishra3452"><strong>Github</strong></a><strong>, and</strong> <a href="https://www.facebook.com/mishra3452"><strong>Facebook</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cccfdc5c60c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/practical-guide-to-solve-outofmemoryerror-in-android-application-8cccfdc5c60c">Practical Guide To Solve OutOfMemoryError in Android Application</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Design Patterns in Android with Kotlin]]></title>
            <link>https://medium.com/mindorks/mastering-design-patterns-in-android-with-kotlin-a6d83b24c363?source=rss-f2ea94bbbcd3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6d83b24c363</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Sumit Mishra]]></dc:creator>
            <pubDate>Tue, 09 Jun 2020 05:32:03 GMT</pubDate>
            <atom:updated>2020-06-09T05:46:30.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p0vSf-yeFAAnXfhX.png" /></figure><p>Before starting this blog, I would like to ask one question. What makes your code good? Is it the code size or something else? Just think over it for a while and then continue reading this blog.</p><p><strong>Originally published at </strong><a href="https://blog.mindorks.com/mastering-design-patterns-in-android-with-kotlin"><strong>blog.mindorks.com</strong></a></p><p>There are certain factors that are used to differentiate between a good Android code and a bad Android code. It may be the code structure or the comments used or the variable names or something else. So, in Android, every developer should follow some <strong>Design Pattern</strong> while writing the code of an Android application. The following are some of the benefits of using Design Pattern in Android:</p><ul><li><strong>Understandable code:</strong> By using Design Pattern, you can make your code understandable to everyone i.e. for writing code, you can follow certain guidelines and anyone can understand why you have written that code. <strong><em>For example</em></strong>, if you are using singleton pattern, then anyone viewing your code can understand that here you want to make only one object of a class and you want to access the same object throughout the application.</li><li><strong>Code reusability:</strong> By following the Design Pattern, you can make your code reusable i.e. for performing a certain task at more than one place, you need not write the same code again and again at various places.</li><li><strong>Cleaner code:</strong> You can make your code cleaner by decoupling the code and it will make the code easier to understand by using Design Pattern.</li></ul><p>So, in order to achieve the above-mentioned things, certain Design Patterns are defined that every Android Developer or every developer should follow while writing any code. In this blog, we will be learning about these Design Patterns in Android. So, let’s get started.</p><h3>What is a Design Pattern?</h3><p>As Wikipedia says:</p><blockquote>A Design Pattern is a general, reusable solution to a commonly occurring problem within a given context.</blockquote><p>So, it is basically a pattern that can be followed to solve a particular feature. These are the best practices that can be used by any programmer to build an application.</p><p>In Android also, we use some Design Pattern that is used to make our code easier to understand and more reusable.</p><p>There are a number of Design Patterns that can be used in Software Development and all these can be classified into the following three categories:</p><ul><li>Creational Pattern</li><li>Structural Pattern</li><li>Behavioural Pattern</li></ul><p>Let’s understand one by one.</p><h3>Creational Pattern</h3><p>The Creational Pattern is used to create some object without showing the logic or the steps that are involved in creating the object. So, every time you want an object, <strong>you need not instantiate the object by using the new operator</strong>. So, this makes the creation of object easier and can be easily created again and again. Some of the examples of Creational Pattern are Builder, Singleton, and Dependency Injection.</p><blockquote><strong>Builder pattern</strong></blockquote><p>In a builder pattern, you are only concerned about what you need from a class and not everything that a class has. <strong><em>For example</em></strong>, when you go to buy some laptop, then you have a list of important features that you want in your laptop like processors, ram, storage, etc. Apart from these features, all the other features like the speaker, battery, etc are some of the optional features for you. So, based on the important features, the shopkeeper will provide you with a laptop that contains all your important features.</p><p>Similarly, when we have a model class and that class is having a number of parameter out of which some are important and some are not important then we can use the Builder pattern. By using the Builder pattern, the user need not call all the methods(as in the case of constructors) present in the class. The user can call only the required methods and even the order of calling of the method is not fixed i.e you can call any method before and after any method. <strong>There is no need for new keyword here(for java)</strong>. Let’s understand this with the help of an example.</p><p>In this example, we will be having one Laptop class with four properties i.e. processor, ram, battery, and screen size. The processor is important, so you need to pass it every time and the rest of the properties are not important. So, if you are not setting the value then the default value will be used. Our model class for Laptop looks like:</p><pre>class Laptop(builder: Builder) {<br>    private val processor: String = builder.processor<br>    private val ram: String = builder.ram<br>    private val battery: String = builder.battery<br>    private val screenSize: String = builder.screenSize</pre><pre>    // Builder class<br>    class Builder(processor: String) {<br>        var processor: String = processor // this is necessary</pre><pre>        // optional features<br>        var ram: String = &quot;2GB&quot;<br>        var battery: String = &quot;5000MAH&quot;<br>        var screenSize: String = &quot;15inch&quot;</pre><pre>        fun setRam(ram: String): Builder {<br>            this.ram = ram<br>            return this<br>        }</pre><pre>        fun setBattery(battery: String): Builder {<br>            this.battery = battery<br>            return this<br>        }</pre><pre>        fun setScreenSize(screenSize: String): Builder {<br>            this.screenSize = screenSize<br>            return this<br>        }</pre><pre>        fun create(): Laptop {<br>            return Laptop(this)<br>        }<br>    }<br>}</pre><p>Now, <strong>you need not create the object every time</strong>. Just use the below code:</p><pre>Laptop.Builder(&quot;i7&quot;) // processor is compulsory<br>    .setRam(&quot;8GB&quot;)            // this is optional<br>    .setBattery(&quot;6000MAH&quot;)    // this is optional<br>    .create()</pre><p>In the above code, we have to pass the processor because this is a necessary component and rest are optional. Here, we are not passing the screen size, so the default value of the screen size will be used.</p><p>One of the common examples of Builder pattern that we all use in our daily life is that of AlertDialog. In AleartDialog, we call only the required methods like:</p><pre>AlertDialog.Builder(this)<br>    .setTitle(&quot;This is a title&quot;)<br>    .setMessage(&quot;This is some message&quot;)<br>    .show()</pre><p>There are other methods available in AlertDialog, but you can use it according to your need.</p><blockquote><strong>Singleton pattern</strong></blockquote><p>There are cases when you need <strong>only one instance of a class</strong>. So, whenever you call the object of the class, then the new object should not be created(only one-time object creation will be there). This design pattern provides a global point of access to a class. <strong><em>For example</em></strong>, the network connection in an application should be done once and not every time because it is a very expensive process. So in these cases, we can use a singleton.</p><p>Following is an example of a singleton class in Kotlin:</p><pre>object DataManager{<br>    init {<br>        println(&quot;Singleton class invoked.&quot;)<br>    }<br>    fun getUserData(): User{<br>        // some code<br>    }</pre><pre>}<br>// to user singleton class<br>fun main(args: Array&lt;String&gt;) {     <br>    DataManager.getUserData()<br>    // more code<br>}</pre><p>In Kotlin, there is no need for using private construction or static method to create a singleton class. <a href="https://blog.mindorks.com/how-to-create-a-singleton-class-in-kotlin">Learn more about a singleton class in Kotin</a>.</p><blockquote><strong>Dependency Injection pattern</strong></blockquote><p>Most of the classes have some dependency that is needed for the proper functioning of the class. In the general case, we hard-code all the dependencies needed in the class inside the class itself. But this is a very wrong way of providing dependency to a class because in future if the class requires some more dependency or you want to add more dependency, then you have to update the new dependency in all the classes that will be using that dependency. You have to update the code at many places and you should avoid this in your project.</p><p><strong><em>For example</em></strong>, a car needs an engine to run. So, instead of providing the engine inside the same car class, we should provide the engine from outside the car class.</p><p><strong>So, in the Dependency Injection pattern, we provide the dependency of a class from outside the class and no dependency will be provided in the same class</strong>.</p><p><strong><em>For example</em></strong>, if a class “DataManager” is dependent on “DatabaseHelper” and “NetworkHelper” then we should not provide these two dependencies in the same “DataManager” class because there may be cases when these two dependencies are the dependencies of some other classes also. So, if there is a change in these dependencies, then you have to change the code of these two dependencies in all the classes that are dependent on these two.</p><p>Let’s understand how to implement Dependency Injection in our code.</p><p>If we don’t use the concept of Dependency Injection in our code, then our code will look like:</p><pre>class DataManager {<br>    private val databaseHelper: DatabaseHelper = DatabaseHelper() // dependent on DatabaseHelper<br>    private val networkHelper: NetworkHelper = NetworkHelper()    // dependent on NetworkHelper<br>    <br>    fun someTask() {<br>        // do some operation with DatabaseHelper and NetworkHelper<br>    }<br>}</pre><p>To use the dependency you have to use the below code:</p><pre>val dataManager: DataManager = DataManager()<br>dataManager.someTask()</pre><p>But here, it is very difficult to test each class separately and also if there is a change in dependency, then you have to change the code of the DataManager class again and again.</p><p>So, if we provide dependency from outside the class then the code looks something like this:</p><pre>class DataManager(databaseHelper: DatabaseHelper, networkHelper: NetworkHelper) {<br>    private val databaseHelper: DatabaseHelper = databaseHelper<br>    private val networkHelper: NetworkHelper = networkHelper</pre><pre>    fun someTask() {<br>         // do some operation with DatabaseHelper and NetworkHelper<br>    }<br>}</pre><p>Now, you can use the DatabaseHelper and NetworkHelper by using the below code:</p><pre>val databaseHelper: DatabaseHelper = DatabaseHelper()<br>val networkHelper: NetworkHelper = NetworkHelper()<br>val dataManager: DataManager = DataManager(databaseHelper, networkHelper)<br>dataManager.someTask()</pre><p>So by using the DependencyInjection pattern, you will get the ability to test each class in isolation. But every time you want to use the DatabaseHelper and NetworkHelper, you need to write all these codes. So, to make things easier, we make use of a framework called <strong>Dagger</strong>. The Dagger will do all these things for you and make your coding life easier :)</p><p><a href="https://blog.mindorks.com/a-complete-guide-to-learn-dagger-2-b4c7a570d99c"><strong>Learn more about Dagger.</strong></a></p><h3>Structural Pattern</h3><p>In this Design Pattern, we are concerned about the structure of the code. Here we follow some particular structural pattern that will help in understanding the code and the working of code just by looking at the structure of the code. Some of the common Structural Pattern used are Adapter, Bridge, Facade, Proxy, etc.</p><blockquote><strong>Adapter pattern</strong></blockquote><p>An Adapter is something like a connector that is used to connect two or more incompatible interface. This pattern lets the classes work together. Let’s look at one example:</p><p>Consider that you are having an airline app that shows the flight details. This application is used in India. So, all the details such as flight price and flight time are according to Indian currency and Indian time respectively. So, for this, you can have one view class called “<strong><em>FlightView</em></strong>” that is having the view that shows the flight time and flight price. In this class, you can have a “<strong><em>ShowDetails()</em></strong>” methods that provide the flight time and flight price and then sets these value on some textview.</p><p>The problem arises when we have the details of two airlines of different countries let’s say AirIndia and UnitedAirlines. The time and price of the AirIndia will be shown correctly because it is according to Indian standards. But the UnitedAirlines will be having timings and pricing according to the American time and currency. Both the classes have different time zone and currency. So, these two classes i.e. the “AirIndia” and “UnitedAirlines” are totally incompatible and here we need one Adapter to have communication between these two otherwise, we will end up having the price of UnitedAirlines in rupees(without any conversion from the dollar).</p><p>So let’s create an interface Adapter named “<strong><em>FlightDetailAdapter</em></strong>”. This interface is having two methods that will return the time according to IST(Indian Standard Time) and the price will be in INR(i.e. Indian currency). The basic idea is we will implement this interface in various Airlines to get the details according to Indian standards. By using these methods we can have the timings and price of all the airlines according to the Indian time and Indian currency.</p><pre>interface FlightDetailAdapter {<br>    // get price in indian rupees<br>    fun getPriceInINR()<br>    <br>    // get time in Indian Standard Time<br>    fun getTimeInIST()<br>}</pre><p>After creating the interface, now we have to make two classes i.e. “<strong><em>AirIndiaFlightDetailAdapter</em></strong>” and “<strong><em>UnitedAirlinesFlightDetailAdapter</em></strong>”. Both of these classes will implement the same interface i.e. “FlightDetailAdapter”.</p><p>The code for the “AirIndiaFlightDetailAdapter” will be:</p><pre>class AirIndiaFlightDetailsAdapter: FlightDetailAdapter {</pre><pre>    // some AirIndiaApi that gives the time and price according to Indian standards<br>    var api:AirIndianApi = AirIndiaAPI()</pre><pre>    override fun getPriceInINR(): Int {<br>        // returns the price in INR<br>        return api.price<br>    }</pre><pre>    override fun getTimeInIST(): String {<br>        //returns the time in IST<br>        return api.time<br>    }<br>}</pre><p>The code for the “UnitedAirlinesFlightDetailAdapter” will be:</p><pre>class UnitedAirlinesFlightDetailAdapter: FlightDetailAdapter {<br>    // some UnitedAirlinesAPI that gives the time and price according to American standards<br>    var api:UnitedAirlinesAPI = UnitedAirlinesAPI()</pre><pre>    override fun getPriceInINR(): Int {<br>        // returns the price in INR<br>        return convertUSDToINR(api.price)<br>    }</pre><pre>    override fun getTimeInIST(): String {<br>        //returns the time in IST<br>        return convertESTToIST(api.time)<br>    }</pre><pre>    fun convertUSDToINR(price: Int): Int {<br>        // some logic<br>    }</pre><pre>    fun convertESTToIST(time: String): String {<br>        // some logic<br>    }<br>}</pre><p>Now, we can write the code of our “FlightView” class that will show the time and price of the flights on the application:</p><pre>class FlightView(context: Context) : View(context) {<br>    // showing flight details according to Indian time and price<br>    fun showFlightData(fda: FlightDetailAdapter) {<br>        priceTextView.text = fda.getPriceInINR()<br>        timeTextView.text = fda.getTimeInIST()<br>    }<br>}</pre><p>Finally, you can call for the desired flight details i.e. you can call the AirIndia classes and the UnitedAirlines classes according to your need and show the correct output in the view. For showing the AirIndia flight details, just use:</p><pre>val flightView: FlightView = FlightView()</pre><pre>// for showing AirIndia flight details<br>flightView.showFlightData(AirIndiaFlightDetailsAdapter())</pre><p>And for showing the UnitedAirlines flight details, just use:</p><pre>val flightView: FlightView = FlightView()</pre><pre>// for showing UnitedAirlines flight details<br>flightView.showFlightData(UnitedAirlinesFlightDetailAdapter())</pre><p>In Android, RecyclerView and PagerAdapter are some of the good examples of the Adapter pattern.</p><p>This is how we can use the Adapter in Android that will help us in creating a connection between two incompatible classes.</p><blockquote><strong>Facade pattern</strong></blockquote><p>In the Facade pattern, a complicated system is wrapped into a simpler system that will help us in getting the values from the complicated system without having knowledge of how the data is being fetched and returned to the view or the presenter.</p><p><strong><em>For example</em></strong>, We have one Presenter or View that shows us the users that are stored in the Database. So, the presenter demands the list of users by some DataManager class. The DataManager class deals with various data related things. It can have one NetworkHelper and one DatabaseHelper class. Internally, the DataManager may use the NetworkHelper or DatabaseHelper class to fetch the details, but our view or presenter is less bothered about that. It only needs the list of available users and nothing else. Even the view or presenter is unaware of the fact that there is some NerworkHelper or DatabaseHelper class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*oKk3_Tr_GpWC__T3.jpg" /></figure><h3>Behavioural Pattern</h3><p>Behavioural Pattern mainly tells how the objects of the classes will communicate with each other. These patterns help us in understanding the code in a better way because by viewing the code we can identify the pattern and then we can understand the code in a better way. Some of the behavioural patterns are Chain of Responsibility, Interpreter, Mediator, Observer, Command, Model View Controler, Model View ViewModel, etc.</p><blockquote><strong>Observer pattern</strong></blockquote><p>The observer pattern is like one-to-many(or one) dependencies between objects. <strong><em>For example</em></strong>, on YouTube, you can subscribe to a particular channel and if some video is uploaded on that channel then all its subscriber will be notified about the change or about the new video.</p><p>So, in Android also, when there is a change in some object, then the dependents of that object will be notified about the change and the possible update will be made accordingly in the dependents. This is called an Observer pattern because here we are observing for some change in the object.</p><p><strong><em>For example</em></strong>, In Android, LiveData is an observable data holder class that enables the use of an observer pattern.</p><p><a href="https://blog.mindorks.com/understanding-livedata-in-android"><strong>Learn how to use LiveData in Android.</strong></a></p><p>Also, RxJava enables the use of an observer pattern in Android.</p><p><a href="https://blog.mindorks.com/a-complete-guide-to-learn-rxjava-b55c0cea3631"><strong>Learn RxJava</strong></a>.</p><blockquote><strong>Command pattern</strong></blockquote><p>In the Command pattern, we give commands and we want our output and nothing else. We are not bothered about who will do our operation to give the desired result. All we want is our things to be done at the right time.</p><p><strong><em>For example</em></strong>, You have an “Execute” interface and there are two classes that are implementing this “Execute” interface. One class is responsible for writing something in the file and the other class is responsible for appending the contents of a file. So, you can call any of these two classes i.e. the “WriteFile” and “AppendClass” with the help of “Execute” interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*Ry_5a1IPUoHlGKAY.jpg" /></figure><blockquote><strong>Model View Controller pattern</strong></blockquote><p>Model View Controller or MVC is an Architectural Design pattern this is used to write an organised code for Android applications. Code following the MVC pattern is divided into three parts:</p><ul><li><strong>Model:</strong> It is the place where you write all your Business logic and data state. So, all the data classes of your application are considered as Model.</li><li><strong>View:</strong> It is the user interface that a user sees. In Android, the user interface is built with the help of XML. So, all the views that the user sees come under this category.</li><li><strong>Controller:</strong> A controller is simply a communication medium between the Model and the View. It takes the user input from the view. It processes the request and it sends the data from the Model to the view.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*qdKHm__jiCMD1PgZ.jpg" /></figure><p>Nowadays, we don’t use this pattern because it is declared as “<strong>Massive View Controller</strong>” for Android. Instead of MVC, we use MVP and MVVM.</p><blockquote><strong>Model View Presenter</strong></blockquote><p>Model View Presenter or MVP is a set of guidelines that are followed to make the code reusable and testable because it decouples the whole code. MVP divides the application into three parts:</p><ul><li><strong>Model: </strong>It is the place where you write all your Business logic and data state. So, all the data classes of your application are considered as Model.</li><li><strong>View:</strong> It is the user interface that a user sees. In Android, the user interface is built with the help of XML. So, all the views that the user sees come under this category.</li><li><strong>Presenter:</strong> The presenter is responsible for giving the data to the view. If view demands some data from the Model, then it is the presenter that will fetch the data from the Model and provide the data to the view to display the required details.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*utWlgs-AC4RR0PES.jpg" /></figure><p><a href="https://blog.mindorks.com/essential-guide-for-designing-your-android-app-architecture-mvp-part-1-74efaf1cda40#.lkml1yggq">Learn more about MVP</a></p><blockquote><strong>Model View ViewModel pattern</strong></blockquote><p>The Model View ViewModel or MVVC is similar to that of MVC but here the controller is replaced by the ViewModel. The three components of the Model View ViewModel are:</p><ul><li><strong>Model: </strong>It is the place where you write all your Business logic and data state. So, all the data classes of your application are considered as Model.</li><li><strong>View:</strong> It is the user interface that a user sees. In Android, the user interface is built with the help of XML. So, all the views that the user sees come under this category.</li><li><strong>ViewModel:</strong> It is a bridge between the Model and the View. Here most of the user interface logic is stored. This is mainly used to store and manage the UI-related and it resolves one of the biggest problems of data loss that was faced due to screen rotation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*siTq676TPtC4HbdY.jpg" /></figure><p><a href="https://blog.mindorks.com/mvvm-architecture-android-tutorial-for-beginners-step-by-step-guide">Have a look at our MVVM blog to have a better understanding of the same.</a></p><blockquote><strong>Clean Architecture</strong></blockquote><p>Clean Architecture defines the way in which the various layers of an app i.e. presentation, use case, domain, data, and framework layer interact with each other. The Clean Architecture produces a system that is testable, UI-independent, and independent of external agencies and libraries. The following image is a popular clean architecture image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/0*nJescW5Qb0SH4jZH.jpg" /></figure><p>These circles represent the various levels in our application. As we move inward in the circle, each circle is more abstract and higher-level. The inner circle is not dependent on any outer circle and the most inner circle denotes the business logic of the application.</p><h3>Conclusion</h3><p>So in this blog, we learned about some of the Design Patterns that are used in Android to write a cleaner and understandable code. We learn about Builder pattern, Singleton pattern, Dependency Injection pattern, Adapter pattern, Facade pattern, Observer pattern, Command pattern, MVC, MVP, and MVVM pattern.</p><p>Hope you will apply these Design Patterns in your next Android Project :)</p><p>If you are preparing for your next Android Interview, <a href="https://mindorks.com/android-app-development-online-course-for-professionals"><strong>Join our Android Professional Course</strong></a> to learn the latest in Android and land job at top tech companies.</p><p>Happy Learning :)</p><p><strong>Team MindOrks!</strong></p><p><strong>Also, Let’s connect on</strong> <a href="https://twitter.com/hiii_sumit"><strong>Twitter</strong></a><strong>,</strong> <a href="https://www.linkedin.com/in/mishra3452/"><strong>Linkedin</strong></a><strong>,</strong> <a href="https://github.com/mishra3452"><strong>Github</strong></a><strong>, and</strong> <a href="https://www.facebook.com/mishra3452"><strong>Facebook</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6d83b24c363" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mindorks/mastering-design-patterns-in-android-with-kotlin-a6d83b24c363">Mastering Design Patterns in Android with Kotlin</a> was originally published in <a href="https://medium.com/mindorks">MindOrks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>