<?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 Karan Singh on Medium]]></title>
        <description><![CDATA[Stories by Karan Singh on Medium]]></description>
        <link>https://medium.com/@skaran5672011?source=rss-671e4194fd3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3xkvyY_IiiF6SofE</url>
            <title>Stories by Karan Singh on Medium</title>
            <link>https://medium.com/@skaran5672011?source=rss-671e4194fd3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:07:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skaran5672011/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[Understanding the Android Activity Lifecycle: Real-World Scenarios Explained]]></title>
            <link>https://medium.com/@skaran5672011/understanding-the-android-activity-lifecycle-real-world-scenarios-explained-b4f26908159f?source=rss-671e4194fd3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4f26908159f</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[activity-lifecycle]]></category>
            <dc:creator><![CDATA[Karan Singh]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 06:45:01 GMT</pubDate>
            <atom:updated>2024-08-23T06:45:01.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*aL1Wm-K_EebgTtHyGaSN0A.png" /></figure><p>The Android Activity Lifecycle is a key concept every Android developer needs to grasp. It describes how an activity (a single screen with a user interface) moves through different stages during its existence. By understanding this lifecycle, you can build apps that handle changes smoothly and provide a great user experience. Let’s explore some common real-world scenarios to see how the Android Activity Lifecycle works and how to manage it effectively.</p><h4>1. Starting an App (Normal App Launch)</h4><p><strong>Scenario:</strong> The user taps on your app icon to open it.</p><p><strong>Actions:</strong> When the app is launched, the system calls the onCreate() method. This is where you set up the initial state of the activity. You initialize the user interface (UI), load any necessary data, and prepare the app for interaction.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onCreate(): Initializes the activity.</li><li>onStart(): Makes the activity visible to the user.</li><li>onResume(): Makes the activity interactive, ready for user input.</li></ul><h4>2. Handling Device Rotation (Configuration Changes)</h4><p><strong>Scenario:</strong> The user rotates their device from portrait to landscape mode (or vice versa).</p><p><strong>Actions:</strong> Android treats this as a configuration change and automatically destroys and recreates the activity to adjust to the new layout. However, it’s crucial to preserve the user’s data during this process, like text input in a form.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onDestroy(): Called before the activity is destroyed.</li><li>onCreate(): Recreates the activity with the new configuration.</li><li>onStart() and onResume(): Bring the activity back to the foreground.</li></ul><h4>3. Switching Apps (Home Button Press)</h4><p><strong>Scenario:</strong> The user presses the home button to use another app.</p><p><strong>Actions:</strong> The activity doesn’t get destroyed but moves into the background. This allows the user to return quickly to where they left off.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onPause(): Called when the activity loses focus.</li><li>onStop(): Called when the activity is no longer visible but still in memory.</li></ul><h4>4. App Going into the Background</h4><p><strong>Scenario:</strong> The user receives a phone call while using your app, sending your app into the background.</p><p><strong>Actions:</strong> Similar to pressing the home button, your app’s activity is paused and stopped as it moves out of view.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onPause(): Prepares the activity to stop interacting with the user.</li><li>onStop(): Moves the activity out of the visible area but keeps it in memory.</li></ul><h4>5. Returning to the App</h4><p><strong>Scenario:</strong> After finishing the phone call, the user returns to your app.</p><p><strong>Actions:</strong> When the user comes back, the system restarts the activity, bringing it to the foreground, where the user left off.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onRestart(): Called when the activity is coming back to the foreground.</li><li>onStart(): Makes the activity visible again.</li><li>onResume(): Re-engages the user, making the activity interactive.</li></ul><h4>6. Dealing with Low Memory</h4><p><strong>Scenario:</strong> The device is running low on memory, and the system needs to free up resources.</p><p><strong>Actions:</strong> The system might destroy your activity to free up memory. Before this happens, you should save important data so that you can restore the activity state when the user returns.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onSaveInstanceState(): Saves the activity’s state before it’s destroyed.</li><li>onRestoreInstanceState(): Restores the saved state when the activity is recreated.</li><li>onCreate(), onStart(), onResume(): Used to recreate and resume the activity.</li></ul><h4>7. Explicitly Finishing an Activity</h4><p><strong>Scenario:</strong> The user navigates to a different screen in your app, and you decide to close the current screen.</p><p><strong>Actions:</strong> You can explicitly finish the activity, freeing up resources. This is common when moving from one screen to another.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onPause(): Prepares to stop interacting with the user.</li><li>onStop(): The activity is no longer visible.</li><li>onDestroy(): The activity is completely removed from memory.</li></ul><h4>8. Device Shutdown</h4><p><strong>Scenario:</strong> The user turns off their device while your app is running.</p><p><strong>Actions:</strong> The system calls onStop() and onDestroy() on all active activities, ensuring that everything is properly closed down.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onStop(): Ensures the activity is no longer visible.</li><li>onDestroy(): Cleans up resources as the activity is removed.</li></ul><h4>9. Displaying a Dialog (Dialog Overlapping Activity)</h4><p><strong>Scenario:</strong> A dialog or alert appears over your activity, like a confirmation box.</p><p><strong>Actions:</strong> When the dialog appears, the activity is partially paused. Once the dialog is dismissed, the activity resumes full interaction with the user.</p><p><strong>Lifecycle Methods Involved:</strong></p><ul><li>onPause(): Called when the dialog takes focus.</li><li>onResume(): Called when the dialog is dismissed and the activity regains focus.</li></ul><p>By understanding and managing these scenarios, you can ensure that your Android app handles changes smoothly and provides a seamless user experience. Mastering the Android Activity Lifecycle is crucial for creating reliable, user-friendly applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4f26908159f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy vs Lateinit Properties in Kotlin : Deep Understanding of  using it properly .]]></title>
            <link>https://medium.com/@skaran5672011/lazy-vs-lateinit-properties-in-kotlin-deep-understanding-of-using-it-properly-3a8a8f73e541?source=rss-671e4194fd3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a8a8f73e541</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Karan Singh]]></dc:creator>
            <pubDate>Mon, 06 May 2024 09:38:36 GMT</pubDate>
            <atom:updated>2024-05-06T09:38:36.257Z</atom:updated>
            <content:encoded><![CDATA[<h3>Lazy vs Lateinit Properties in Kotlin : Deep Understanding of using it properly .</h3><p>I have seen many android developers knowing only the definition of By Lazy and lateinit in kotlin but when it is time to implement it practically then they don’t know when we have to use which things .</p><p>So today I will tell you what is By Lazy and lateinit are in kotlin and when we have to use it in our projects .</p><p><strong>Lateinit :</strong></p><p>Whenever we don’t want to initialize our value at declaration time , but we initialize it later in the code before using it then we use lateinit .</p><p>Now the Question arises in the mind is what is the benefit of using lateinit when we can simply initialize it.</p><p>Well the advantage is that the lateinit is used to declare non nullable type which will reduce the null check in your code</p><p>Let us take an example :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O8X5507OvnQsYylA" /></figure><p>Here if we declared it by creating a nullable variable then we have to smart cast by making a null check .</p><p>Now let use the lateinit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*qf6Cr-GX_fZLvOB6" /></figure><p>Here we can see that we don’t have to do any null check because the lateinit is a non-nullable type .</p><p>Now let us suppose you have forgotten to initialize before using it then an error will encounter a <strong>“UninitializedPropertyAccessException” </strong>exception. T<strong>o avoid this error</strong>, we can also use the <strong>isInitialized() method</strong> that Kotlin provides for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*ipNsMJhOCdtfMJ69" /></figure><p><strong>When to use Lateinit initialization</strong></p><ul><li>If a variable is mutable and can be initialized at a later stage.</li><li>You are sure about initializing a variable before using it.</li><li>using the var keyword.</li></ul><p><strong>By Lazy :</strong></p><p>Lazy initialization is a common technique in software where we create objects only <strong>the first time when we use them</strong>, <strong>otherwise we don’t have to initialize them. This</strong> is helpful when creating an object takes a long time and other parts of the program depend on it and we all know that allocating a lots of object during app start up can led longer start up time So In Kotlin, ‘lazy’ lets us do this easily.</p><p><em>In other words we can say that the object will get initialized only when it is accessed for the first time, else it will not get initialized.</em></p><p><strong>Let us take an example :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/0*Ib-sLn-d-AzQgpA-" /></figure><p>So what will be the output of the above code when we run ?</p><p>Let see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6gaJcqpY41chBaG0" /></figure><p>Here we can see that the object is only initialized once when we try to access it .</p><p><strong>When to use Lazy initialization</strong></p><ul><li>Variables will not be initialized unless you call it.</li><li>Initializes the variable once; that same value is then used throughout the code.</li><li>Used in case of val property i.e. read-only properties as the same object will be shared throughout the program.</li></ul><p>I hope it clears the difference between lazy and lateinit property . If you like this article then please support and stay tuned for the next article .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a8a8f73e541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leakage and best practices to avoid memory leakage in Android]]></title>
            <link>https://medium.com/@skaran5672011/memory-leakage-and-best-practices-to-avoid-memory-leakage-in-android-a8a268344cf2?source=rss-671e4194fd3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8a268344cf2</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Karan Singh]]></dc:creator>
            <pubDate>Wed, 01 May 2024 07:04:58 GMT</pubDate>
            <atom:updated>2024-05-01T07:04:58.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qka4zwoW52UezeT3" /></figure><p>Recently I got a chance to work on another person’s live android project and when I saw the code I found that the whole code is full of memory leakage . No proper handling has been done for memory leakage . Activity references are stored in companion objects and inside ViewModel . No callback removed for handler and many more . So I thought I would give a brief knowledge about the memory leakage and best practices to avoid memory leakage in android .</p><p>So first let us see what <strong>memory leakage</strong> is ?</p><p><strong>Memory leakage</strong> is basically when a garbage collector is unable to free up the allocated space once the task is done or we can say that when memory is allocated but it never gets free.</p><p>So the question that came to mind is how the garbage collector is unable to free up allocated space when the task is done . As we know that the work of a garbage collector is clean garbage from memory .</p><p>Well the garbage collector traverse to each and every object which is linked to the root and the object which is not linked are considered inactive object and are eligible for garbage collection but sometimes some unused object are still marked as linked because the object has some reference that&#39;s why GC not enable for garbage collection and thus resulting in memory leaks .</p><p>Now if the memory leakage is clear then let’s see what are the bad practices that cause memory leakage .</p><p><strong>1: Use of Static view or reference</strong></p><p>The most common mistake developers do in the early phase is using static view and reference which is a common cause of memory leakage . This happens when a static field holds a reference to a view or context, such as an Activity, which prevents the garbage collector from reclaiming the memory even after the context is no longer in use.</p><p><strong>Bad Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5c9nL4d--0fKLvbF" /></figure><p>Avoid using static reference to view or context and if you need to retain then use ViewModel or SavedInstanceState .</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BeST_MiyQPgXlRPZ" /></figure><p><strong>2: Improper handling of Handlers and runnable</strong></p><p>Use of handlers can cause memory leakage if not implemented correctly . Let us take an example: you are using a handler for a delayed task but before the task gets completed the activity or fragment gets destroyed which leads the handler to hold the reference of the activity and cause memory leakage .</p><p><strong>Bad Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c9A9VK_GjPsACaXG" /></figure><p>In the above code we can see that testRunnable is an inner class of TestActivity which holds the reference and if TestActivity is destroyed before 50 seconds then the garbage collector is unable to free up space before the handler task gets completed which causes memory leakage .</p><p>To avoid this type of memory leakage use static inner class or separate inner class by Converting Runnable to a static inner class or a separate class. If necessary, use WeakReference to hold references to the Activity or Fragment. And also Ensure that any pending tasks are cancelled in the onDestroy() method of your Activity or Fragment.</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rLkrzF2ua4Jc7OLy" /></figure><p><strong>3: ViewBinding and DataBinding</strong></p><p>ViewBinding and DataBinding can cause memory leakage if they are not used correctly. It is important to Always set the binding variable to null when the view is destroyed.</p><p><strong>Bad Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71jMeEFV5roawqJQ" /></figure><p>So here we can see that the binding is keeping the reference of the view . And after the fragment gets destroyed it holds the reference which can cause the memory leakage .</p><p>To avoid this type of leakage always try to set the binding variable to null when the view is destroyed .</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k87NZ5aABnYZjUxg" /></figure><p><strong>4: Broadcast Receivers</strong></p><p>Broadcast Receivers in Android are components that allow you to listen for and respond to system-wide broadcast announcements or custom broadcasts. However, improper management of Broadcast Receivers can lead to memory leaks.</p><p>Broadcast Receivers, when registered, can hold a reference to the context (usually an Activity or Service). If they are not unregistered when the context is destroyed, they continue to live in the memory, leading to leaks.</p><p><strong>Bad Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YJ4MdZ8edgSI7rCw" /></figure><p>Here we can see that the broadcastReceiver is registered but never gets unregistered due to which when the activity gets destroyed the receiver continues to hold the reference which can cause the memory leak .</p><p>To Avoid this type of leakage, always unregister the Broadcast Receiver when activity gets destroyed .</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0guuucEQ3BwrUqBT" /></figure><p><strong>5: Using Listeners:</strong></p><p>There are multiple scenarios when we register a listener to Activity or Fragment but forget to unregister it. These listeners hold strong reference to it and prevent it from being garbage collected even when it is unused.</p><p><strong>Bad Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y4n1lt-nAPUDo8fe" /></figure><p>The above code will cause memory leakage because the listener is holding the activity reference and when the activity gets destroyed the GC will be unable to clean .</p><p>To Avoid this, always unregister any listener when activity gets destroyed .</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*81PzDCVGnK7rcqem" /></figure><p><strong>6: Singleton with context</strong></p><p>Singletons in Android are a common design pattern used to ensure that only one instance of a class exists throughout the application’s lifecycle. However, if a singleton holds a reference to a context (especially an Activity context), it can lead to serious memory leaks.</p><p>Singletons class are designed to stay alive for the duration of an application’s lifecycle. If a singleton holds a direct reference to an Activity context, it prevents that Activity instance from being garbage collected even after it’s destroyed, leading to a memory leak.</p><p><strong>Bad Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0khbU50-gKcS9DoT" /></figure><p>In the above code, we can see that MySingleton takes a Context in its constructor. If an Activity context is passed to getInstance, the singleton holds a reference to that activity, leading to a memory leak.</p><p>To avoid this, always use the application context. The application context is global and lives as long as the application is alive, which matches the lifecycle of a singleton. And If possible, design the singleton so that it doesn’t need to store a context.</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xw5e7yL8rSJtLld0" /></figure><p><strong>7: WebViews</strong></p><p>Webview are used for displaying web content but if not handled property then they can cause memory leak . let me show you the bad practice of using webview where it can lead to memory leak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YasV5Z77J0SFTunh" /></figure><p>Here we can see that we are using the web view but not clearing it on activity destroyed . Let us take an example that there is some url loading in the web view but during the loading the activity gets closed and the web view is having the reference due to which GC can not free up the memory .</p><p>To avoid this kind of memory leak, always destroy the webview and remove all the views associated with the web view when activity gets destroyed .</p><p><strong>Good Practice :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OFv4xcN9TlZcvwia" /></figure><p>I hope you enjoyed the article! Your feedback matters, so don’t forget to clap and share your thoughts in the comments. Keep coding, and here’s to your success!</p><p>So in the next article we will cover all the tools and methods by which we can identify memory leaks and solve the leak issue .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8a268344cf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OutOfMemoryError Android and Understanding Memory Management in Android]]></title>
            <link>https://medium.com/@skaran5672011/outofmemoryerror-android-and-understanding-memory-management-in-android-9cb9606be982?source=rss-671e4194fd3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cb9606be982</guid>
            <dc:creator><![CDATA[Karan Singh]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 11:21:35 GMT</pubDate>
            <atom:updated>2024-04-26T11:21:35.546Z</atom:updated>
            <content:encoded><![CDATA[<p>Few days ago I was working on a YouTube shorts clone project where i have implemented an exoplayer and by mistake i was only pausing the player instead of releasing it due to which after some videos swap an error occurs on my logcat OutOfMemoryError and app gets crashed .</p><p>So let’s discuss what is OutOfMemoryError and why this error occurs in our code . Before coming to the topic let’s get a brief about the memory management in android because the error is related to memory management and we have to get the overview of how memory is managed in android .</p><p><strong>Memory Management in Android:</strong></p><p>Android’s memory management revolves around the Android Runtime (ART) and the Dalvik virtual machine. These systems utilize paging and memory-mapping to oversee memory operations. Essentially, any memory alterations by an app, be it allocating new objects or accessing mapped pages, remain in RAM unless explicitly released. The primary means of memory release is through relinquishing object references, enabling the garbage collector to free up memory.</p><ol><li><strong>Garbage Collector:</strong> The garbage collector in Android’s runtime automatically identifies and releases memory that is no longer in use. It achieves this by tracking memory allocations and reclaiming resources from unused objects.</li><li><strong>Shared Memory: </strong>Android optimizes RAM usage by sharing memory across processes. This is facilitated through processes like forking from a parent process called Zygote and memory mapping static data.</li><li><strong>Allocate and Reclaim App Memory:</strong> Each app in Android has a Dalvik heap, with a set virtual memory range. After garbage collection, unused memory pages are returned to the system, reducing the physical memory footprint.</li><li><strong>Restrict App Memory: </strong>Android imposes a hard limit on the heap size for each app to maintain multitasking functionality. If an app exceeds this limit, it triggers an OutOfMemoryError.</li><li><strong>Switching Apps: </strong>Android retains inactive apps in a cache when users switch between apps. Apps with excessive memory usage are more likely to be terminated from the cache to free up resources.</li></ol><p><strong>Understanding OutOfMemoryError:</strong></p><p>OutOfMemoryError occurs when an app surpasses the allocated heap size limit set by Android. This can happen due to inefficient memory management practices, such as failing to release resources like media players after use, as experienced in the YouTube Shorts clone project.</p><p><strong>Conclusion:</strong></p><p>In conclusion, comprehending memory management in Android is pivotal for crafting robust and efficient applications. By understanding the mechanisms behind memory allocation, garbage collection, and heap size limitations, developers can mitigate errors like OutOfMemoryError and enhance the overall performance of their apps.</p><p>If you enjoyed this article, stay tuned for our next one on memory leaks. We’ll cover how to spot and prevent them, vital for keeping your Android apps stable and efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cb9606be982" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>