<?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 Vishwajith Shettigar on Medium]]></title>
        <description><![CDATA[Stories by Vishwajith Shettigar on Medium]]></description>
        <link>https://medium.com/@zekromvishwa56789?source=rss-32a06404867c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WQ9byXWLxfEB11kM_jSjUw.png</url>
            <title>Stories by Vishwajith Shettigar on Medium</title>
            <link>https://medium.com/@zekromvishwa56789?source=rss-32a06404867c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:55:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zekromvishwa56789/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[Const vs val — Kotlin]]></title>
            <link>https://medium.com/@zekromvishwa56789/const-vs-val-kotlin-9c6d8efe26a8?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c6d8efe26a8</guid>
            <category><![CDATA[val]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[const]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 04:58:36 GMT</pubDate>
            <atom:updated>2025-08-05T04:58:36.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Const vs val — Kotlin</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kb2pr88GAhuVfJEbOYLAgQ.png" /></figure><h3>val</h3><ul><li><strong>Immutable variable</strong></li><li><strong>Evaluated at runtime</strong></li><li>Can store <strong>any type</strong> (objects, function results, etc.)</li><li>Can be used <strong>anywhere</strong> (inside functions, classes, etc.)</li></ul><pre>val currentTime = System.currentTimeMillis() // runtime value<br>val user = User(&quot;User-1&quot;)                      // object</pre><h3>const val</h3><ul><li><strong>Compile-time constant</strong></li><li>Must be a <strong>primitive or String</strong></li><li><strong>Known at compile time</strong></li><li>Only allowed in <strong>top-level</strong>, object, or companion object</li></ul><pre>const val APP_NAME = &quot;SilentZone&quot;<br>const val ACTION_KEY = &quot;com.app.ACTION&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c6d8efe26a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring S.O.L.I.D Principle in Android]]></title>
            <link>https://medium.com/@zekromvishwa56789/solid-principles-in-android-32779c6707cc?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/32779c6707cc</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 08:06:03 GMT</pubDate>
            <atom:updated>2025-08-05T06:25:28.022Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>from <a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts"><strong>Epic Android Concepts</strong></a> series.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_g40Zu_eG-Fq8E44lGVgg.png" /></figure><p><strong>SOLID principles, </strong>you might think you’ve never used them, or maybe you’re not even sure what they are. But here’s the truth: if you’ve been in Android development for over a year and care about writing <em>“clean code”</em> or <em>“good architecture”</em>, then chances are you’ve already applied parts of SOLID unknowingly.</p><p>You might’ve called it <em>“readable code,”</em> <em>“separation of concerns,”</em> or just <em>“a better way to do things.”</em> That’s SOLID in action.</p><h3>What is SOLID?</h3><p>SOLID is an acronym for five object-oriented design principles aimed at writing <strong>clean, maintainable, and scalable code</strong>. These principles were introduced by Robert C. Martin (aka Uncle Bob).</p><p>The five principles are:</p><ul><li><strong>S</strong> — Single Responsibility Principle</li><li><strong>O</strong> — Open/Closed Principle</li><li><strong>L</strong> — Liskov Substitution Principle</li><li><strong>I</strong> — Interface Segregation Principle</li><li><strong>D</strong> — Dependency Inversion Principle</li></ul><p>Let’s break down each one, using Android examples</p><h3>1. Single Responsibility Principle (SRP)</h3><blockquote><strong><em>“A class should have one, and only one, reason to change.”</em></strong></blockquote><p>🚫 <strong>Bad Example: ViewModel doing everything</strong></p><pre>class ProfileViewModel : ViewModel() {<br><br>    private val api = Retrofit.Builder().build().create(ProfileApi::class.java)<br>    private val database = Room.databaseBuilder(...).build().profileDao()<br><br>    val profileData = MutableLiveData&lt;Profile&gt;()<br><br>    fun loadProfile(userId: String) {<br>        viewModelScope.launch {<br>            val profile = api.getProfile(userId)<br>            database.saveProfile(profile)<br>            profileData.value = profile<br>        }<br>    }<br><br>    fun formatName(name: String): String {<br>        return name.uppercase()<br>    }<br>}</pre><blockquote><em>What’s wrong here?</em></blockquote><ul><li>ViewModel is handling <strong>network</strong>, <strong>database</strong>, <strong>business logic</strong>, and even <strong>UI formatting</strong>.</li><li>If API changes → ViewModel changes.</li><li>If DB changes → ViewModel changes.</li><li>If UI changes → ViewModel changes.</li><li>Not reusable, hard to test, not scalable.</li></ul><p>✅ <strong>Good Example: SRP-Compliant ViewModel</strong></p><p>Let’s refactor this into proper layers.</p><p>ProfileRepository.kt – Handles data sources</p><pre>class ProfileRepository(<br>    private val api: ProfileApi,<br>    private val dao: ProfileDao<br>) {<br>    suspend fun getProfile(userId: String): Profile {<br>        val profile = api.getProfile(userId)<br>        dao.saveProfile(profile)<br>        return profile<br>    }<br>}</pre><p>FormatUtils.kt – Separate formatter</p><pre>object FormatUtils {<br>    fun formatName(name: String): String {<br>        return name.uppercase()<br>    }<br>}</pre><p>ProfileViewModel.kt – Focused on UI state</p><pre>class ProfileViewModel(<br>    private val repository: ProfileRepository<br>) : ViewModel() {<br><br>    private val _profileData = MutableLiveData&lt;Profile&gt;()<br>    val profileData: LiveData&lt;Profile&gt; = _profileData<br><br>    fun loadProfile(userId: String) {<br>        viewModelScope.launch {<br>            val profile = repository.getProfile(userId)<br>            _profileData.value = profile<br>        }<br>    }<br>}</pre><p>Each class has <strong>exactly one reason to change</strong>. That’s true SRP.</p><p>I bet you already knew about this, you just called it <em>‘better code quality’. </em>Now you know it’s actually called the <strong>Single Responsibility Principle</strong>.</p><h3>2. Open/Closed Principle (OCP)</h3><blockquote><strong><em>“Software entities should be open for extension, but closed for modification.”</em></strong></blockquote><p>This one is about writing code that can be extended without changing existing functionality.</p><p>🚫 <strong>Wrong Example: Modifying Logic to Add New Types</strong></p><pre>fun getDiscount(type: String): Double {<br>    return when (type) {<br>        &quot;REGULAR&quot; -&gt; 0.05<br>        &quot;VIP&quot; -&gt; 0.1<br>        &quot;PREMIUM&quot; -&gt; 0.2<br>        else -&gt; 0.0<br>    }<br>}</pre><p>What if we need to add a new customer type tomorrow? We’ll have to edit this function. Every. Single. Time.</p><p>✅ <strong>Right Example: Use Inheritance or Strategy Pattern</strong></p><pre>interface DiscountStrategy {<br>    fun getDiscount(): Double<br>}<br><br>class RegularCustomer : DiscountStrategy {<br>    override fun getDiscount() = 0.05<br>}<br><br>class VipCustomer : DiscountStrategy {<br>    override fun getDiscount() = 0.1<br>}<br><br><br>fun getDiscount(type:DiscountStrategy): Double {<br>   return type.getDiscount()<br>}</pre><p>Now, adding a new customer type is as simple as creating a new class, no need to touch existing logic.</p><h3>3. Liskov Substitution Principle (LSP)</h3><blockquote><strong><em>“Subtypes must be substitutable for their base types.”</em></strong></blockquote><p>It means if B is a subtype of A, then we should be able to use B wherever we use A without breaking the program.</p><p>🚫 <strong>Wrong Example: Violating Substitution</strong></p><pre>open class Bird {<br>    open fun fly() {<br>        println(&quot;Flying high in the sky!&quot;)<br>    }<br>}<br><br>// Create a few subclasses:<br><br><br>class Sparrow : Bird() {<br>    override fun fly() {<br>        println(&quot;Sparrow is flying!&quot;)<br>    }<br>}<br><br>// Perfectly fine. But now comes trouble:<br><br>class Ostrich : Bird() {<br>    override fun fly() {<br>        throw UnsupportedOperationException(&quot;Ostrich can&#39;t fly!&quot;)<br>    }<br>}<br><br>fun letTheBirdFly(bird: Bird) {<br>    bird.fly()  // 💥 crashes for Ostrich<br>}<br><br>fun main(){<br><br>letTheBirdFly(Sparrow())<br>letTheBirdFly(Ostrich())// 💥 crashes for Ostrich<br>}</pre><p>We said Ostrich <em>is a</em> Bird. But clearly, it <strong>cannot behave like one</strong> when asked to fly.</p><p>✅<strong> Right Example: Use Inheritance or Strategy Pattern</strong></p><pre>open class Bird {<br>    fun layEggs() {<br>        println(&quot;Laying eggs...&quot;)<br>    }<br>}<br><br>// Extract flying capability to a separate interface<br><br>interface Flyable {<br>    fun fly()<br>}<br><br>// Now split behaviors correctly<br><br>class Sparrow : Bird(), Flyable {<br>    override fun fly() {<br>        println(&quot;Sparrow flying!&quot;)<br>    }<br>}<br><br>class Ostrich : Bird() {<br>}<br><br>fun makeItFly(bird: Bird) {<br>    if (bird is Flyable) {<br>        bird.fly()<br>    } else {<br>        println(&quot;This bird can&#39;t fly!&quot;)<br>    }<br>}</pre><p>Now <strong>every class behaves predictably</strong>, and you’re <strong>not lying about its abilities</strong>. This respects LSP.</p><h3>4. Interface Segregation Principle (ISP)</h3><blockquote><strong><em>“Clients should not be forced to depend on methods they do not use.”</em></strong></blockquote><p>This principle is about <strong>not bloating your interfaces</strong> with methods that only <em>some</em> consumers need. Instead, break them down into smaller, more focused ones each representing a <strong>single responsibility</strong>.</p><p>In short, this principle is about <strong>splitting big interfaces</strong> into smaller, more focused ones.</p><p><strong>🚫 Wrong Example: A Giant Interface</strong></p><p>Interface with too many responsibilities:</p><pre>interface AnalyticsService {<br>    fun trackScreen()<br>    fun trackButtonClick()<br>    fun trackVideoWatched()<br>    fun logCrash()<br>}<br><br>class LocalButtonAnalytics : AnalyticsService {<br><br>    override fun trackButtonClick() {<br>        println(&quot;Tracked button click.&quot;)<br>    }<br><br>    override fun trackScreen() {<br>        // ❌ Not used by this class<br>    }<br><br>    override fun trackVideoWatched() {<br>        // ❌ Not used<br>    }<br><br>    override fun logCrash() {<br>        // ❌ Not used<br>    }<br>}</pre><p>This is exactly what <strong>Interface Segregation Principle</strong> tells you <strong>not</strong> to do.</p><ul><li>You’re being <strong>forced to implement methods you don’t care about</strong>.</li><li>You might leave them <strong>empty</strong> (bad) or <strong>throw exceptions</strong> (worse).</li><li>If you’re mocking this in a test, you now need to stub irrelevant methods.</li></ul><p>✅ <strong>Right Example: Smaller Interfaces</strong></p><pre>interface ButtonClickTracker {<br>    fun trackButtonClick()<br>}<br><br>class LocalButtonAnalytics : ButtonClickTracker {<br>    override fun trackButtonClick() {<br>        println(&quot;Tracked button click (local)&quot;)<br>    }<br>}</pre><h3>5. Dependency Inversion Principle (DIP)</h3><blockquote><strong><em>“Depend on abstractions, not on concretions.”</em></strong></blockquote><p>🚫 <strong>Bad Example — ViewModel depending directly on Firebase</strong></p><pre>class AuthViewModel : ViewModel() {<br><br>    private val firebaseAuth = FirebaseAuth.getInstance()<br><br>    fun login(email: String, password: String, onResult: (Boolean) -&gt; Unit) {<br>        firebaseAuth.signInWithEmailAndPassword(email, password)<br>            .addOnCompleteListener {<br>                onResult(it.isSuccessful)<br>            }<br>    }<br>}</pre><p>Problems:</p><ul><li>AuthViewModel is <strong>tightly coupled</strong> to FirebaseAuth.</li><li>Can’t reuse with other auth providers (e.g. Google, Phone).</li><li>Hard to mock FirebaseAuth in unit tests.</li><li><strong>Violates DIP</strong> — the high-level module (ViewModel) depends directly on low-level detail (Firebase SDK).</li></ul><p>✅<strong> Good Example — DIP with abstraction</strong></p><pre>interface AuthService {<br>    suspend fun login(email: String, password: String): Boolean<br>}<br><br>// Firebase-based implementation<br><br>class FirebaseAuthService : AuthService {<br><br>    override suspend fun login(email: String, password: String): Boolean {<br>        return suspendCancellableCoroutine { continuation -&gt;<br>            FirebaseAuth.getInstance()<br>                .signInWithEmailAndPassword(email, password)<br>                .addOnCompleteListener { task -&gt;<br>                    continuation.resume(task.isSuccessful)<br>                }<br>        }<br>    }<br>}<br><br>// Google Auth implementation<br><br>class GoogleAuthService : AuthService {<br>    override suspend fun login(email: String, password: String): Boolean {<br>        // use GoogleSignInClient logic<br>        return true // dummy result<br>    }<br>}<br><br><br>class AuthViewModel(private val authService: AuthService) : ViewModel() {<br><br>    private val _loginResult = MutableLiveData&lt;Boolean&gt;()<br>    val loginResult: LiveData&lt;Boolean&gt; = _loginResult<br><br>    fun loginUser(email: String, password: String) {<br>        viewModelScope.launch {<br>            val success = authService.login(email, password)<br>            _loginResult.value = success<br>        }<br>    }<br>}</pre><p>Now you have full flexibility to use any authentication service. Firebase, Google, OAuth, or even your own backend — without ever modifying your ViewModel.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32779c6707cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Keyboard Overlap in ModalBottomSheet — Jetpack compose.]]></title>
            <link>https://medium.com/@zekromvishwa56789/handling-keyboard-overlap-in-modalbottomsheet-with-jetpack-compose-a-practical-approach-e68db28ff66e?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68db28ff66e</guid>
            <category><![CDATA[material3]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[modalbottomsheet]]></category>
            <category><![CDATA[ui-ux-design]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 15:49:18 GMT</pubDate>
            <atom:updated>2024-12-05T17:34:18.152Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNK0yHIlZuHDAbapYlbyPQ.png" /></figure><p>When working with Jetpack Compose’s ModalBottomSheet, a common issue arises when the <strong>keyboard (IME)</strong> opens—it often causes the bottom sheet content to be partially or fully hidden. This results in a frustrating user experience, especially when users need to interact with text fields or other input components inside the sheet. Something like this</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FmwWKsh3qwOA%3Ffeature%3Dshare&amp;type=text%2Fhtml&amp;schema=youtube&amp;display_name=YouTube&amp;src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FmwWKsh3qwOA%3Ffeature%3Doembed" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c877a4cfde50c501ead866a3d4be3f6b/href">https://medium.com/media/c877a4cfde50c501ead866a3d4be3f6b/href</a></iframe><p>In this article, we’ll explore a practical workaround using <strong>ViewTreeObserver</strong>, and <strong>WindowInsetsCompat</strong> to detect keyboard visibility manually and dynamically adjust the height of the ModalBottomSheet.</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun KeyboardAwareModalBottomSheet(<br>    onDismiss: () -&gt; Unit,<br>    profile: Any, // Your profile data<br>    onUpdate: () -&gt; Unit, // Your callback to update profile<br>) {<br>    // Remember the ModalBottomSheetState<br>    val bottomSheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)<br><br>    // Access the current View and keyboard visibility state<br>    val view = LocalView.current<br>    var isImeVisible by remember { mutableStateOf(false) }<br><br>    // Observe keyboard visibility using ViewTreeObserver<br>    DisposableEffect(Unit) {<br>        val listener = ViewTreeObserver.OnPreDrawListener {<br>            // Check if the IME (keyboard) is visible<br>            isImeVisible = ViewCompat.getRootWindowInsets(view)<br>                ?.isVisible(WindowInsetsCompat.Type.ime()) == true<br>            true<br>        }<br>        view.viewTreeObserver.addOnPreDrawListener(listener)<br>        onDispose {<br>            view.viewTreeObserver.removeOnPreDrawListener(listener)<br>        }<br>    }<br><br>    // Main UI: Adjust height of the ModalBottomSheet based on keyboard visibility<br>    Column(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .background(Color.Transparent),<br>        verticalArrangement = Arrangement.Bottom<br>    ) {<br>        ModalBottomSheet(<br>            windowInsets = WindowInsets.ime, // Handle keyboard insets<br>            onDismissRequest = {<br>                onDismiss() // Handle dismiss<br>            },<br>            sheetState = bottomSheetState,<br>            modifier = Modifier.then(<br>                if (isImeVisible)<br>                    Modifier.fillMaxHeight(1.0F) // Full height when keyboard is visible<br>                else<br>                    Modifier.fillMaxHeight(0.73F) // Partial height when keyboard is hidden<br>            )<br>        ) {<br>            // Content of the bottom sheet (e.g., edit profile form)<br>            EditProfileContent(<br>                profile = profile,<br>                onUpdate = onUpdate,<br>                onDismiss = onDismiss<br>            )<br>        }<br>    }<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FfOV7QE0QTmU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2FfOV7QE0QTmU%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FfOV7QE0QTmU%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d54534094c42b3d3b103cf7b219962fa/href">https://medium.com/media/d54534094c42b3d3b103cf7b219962fa/href</a></iframe><p>I discovered above workaround to address the issue until it’s officially resolved. Currently, Compose Material 3 has reached its stable release (v1.3.1), with the latest alpha version being v1.4.0-alpha04.</p><p>Here is repo link for detailed example.</p><p><a href="https://github.com/Vishwajith-Shettigar/ModalBottomSheet-Fix-Keyboard-Overlap---Jetpack-Compose">GitHub - Vishwajith-Shettigar/ModalBottomSheet-Fix-Keyboard-Overlap---Jetpack-Compose</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68db28ff66e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Broadcast Receiver]]></title>
            <link>https://medium.com/@zekromvishwa56789/understanding-android-broadcasts-a-practical-guide-for-developers-c05c1f431892?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c05c1f431892</guid>
            <category><![CDATA[broadcasting]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[broadcastreceiver]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Fri, 22 Nov 2024 15:06:53 GMT</pubDate>
            <atom:updated>2024-11-27T02:38:59.486Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>from <a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts"><strong>Epic Android Concepts</strong></a> series.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1CzDc28LnhYZdQfcIF2gg.png" /></figure><p>In Android, broadcasts are a way for the system or apps to send messages to let others know something important has happened. This could be as simple as the battery running low or as specific as a custom notification from one part of your app to another. If you’ve ever wanted your app to “listen” for system changes or communicate internally, broadcasts are the way to go.</p><p>This guide will walk you through:</p><ol><li>What broadcasts are.</li><li>The types of broadcasts.</li><li>How to send and receive them.</li><li>Key differences: implicit vs. explicit, manifest vs. dynamic.</li><li>A look at local broadcasts and export settings.</li></ol><h3>1. What Are Broadcasts in Android?</h3><p>A broadcast is like a public announcement. Imagine you’re in a crowded room, and someone shouts, “Lunch is ready!” Everyone in the room hears it, and anyone who cares will act on it. Similarly, Android sends “announcements” about various system events. Apps can also send their own broadcasts to share updates with other apps or parts of themselves.</p><h3>2. Types of Broadcasts</h3><h4>System Broadcasts</h4><p>The Android system sends these to notify apps about system-wide events.<br>Examples:</p><ul><li><strong>Low battery</strong> (ACTION_BATTERY_LOW)</li><li><strong>Airplane mode toggled</strong> (ACTION_AIRPLANE_MODE_CHANGED)</li><li><strong>Boot completed</strong> (ACTION_BOOT_COMPLETED)</li></ul><p>Your app can listen to these and respond accordingly.</p><h4>Custom Broadcasts</h4><p>These are created by developers to communicate specific events, either within their app or with other apps.<br>Example:</p><ul><li>A music app broadcasting that a song has finished playing.</li></ul><h3>3. How to Send and Receive Broadcasts</h3><h4>Sending a Broadcast</h4><p>To send a broadcast, you create an Intent with an action string and (optionally) additional data.</p><p><strong>Example: Sending a Custom Broadcast</strong></p><pre>val intent = Intent(&quot;com.example.MY_CUSTOM_ACTION&quot;)<br>intent.putExtra(&quot;message&quot;, &quot;Hello, this is a broadcast!&quot;)<br>sendBroadcast(intent)</pre><p>Here, com.example.MY_CUSTOM_ACTION is the unique action name that your app (or others) will use to identify this broadcast.</p><h4>Receiving a Broadcast</h4><p>To listen for a broadcast, you need a BroadcastReceiver. This is a special class that processes broadcasts when they arrive.</p><p><strong>Example: Creating a BroadcastReceiver</strong></p><pre>class MyBroadcastReceiver : BroadcastReceiver() {<br>    override fun onReceive(context: Context, intent: Intent) {<br>        val message = intent.getStringExtra(&quot;message&quot;)<br>        Log.d(&quot;MyBroadcastReceiver&quot;, &quot;Received: $message&quot;)<br>    }<br>}</pre><p>You’ll also need to register this receiver. There are two ways to do it: <strong>in the manifest</strong> or <strong>dynamically in code</strong>.</p><h3>4. Manifest vs. Dynamic Registration</h3><h4>Manifest-Declared Receivers</h4><p>Receivers declared in the AndroidManifest.xml can handle broadcasts even when your app isn’t running. They’re long-lived and good for system-level events.</p><p><strong>Example: Registering a Receiver in the Manifest</strong></p><pre>&lt;receiver android:name=&quot;.MyBroadcastReceiver&quot; android:exported=&quot;true&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;com.example.MY_CUSTOM_ACTION&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/receiver&gt;</pre><ul><li><strong>android:exported=&quot;true&quot;</strong>: This makes your receiver available to other apps. Use it if you want to accept broadcasts from outside your app.</li><li><strong>android:exported=&quot;false&quot;</strong>: Limits the receiver to broadcasts from your app only. This is more secure for app-specific events.</li></ul><h4>Dynamic Receivers</h4><p>Dynamic receivers are registered at runtime using registerReceiver(). They only work while the app is running. This is great for short-lived tasks, like listening for temporary events.</p><p><strong>Example: Registering a Receiver Dynamically</strong></p><pre>val filter = IntentFilter(&quot;com.example.MY_CUSTOM_ACTION&quot;)<br>registerReceiver(MyBroadcastReceiver(), filter)</pre><p>Starting from Android 12, dynamic receivers need explicit export settings:</p><ul><li><strong>RECEIVER_EXPORTED</strong>: Allows broadcasts from other apps.</li><li><strong>RECEIVER_NOT_EXPORTED</strong>: Restricts broadcasts to your app only.</li></ul><h3>5. Implicit vs. Explicit Broadcasts</h3><h4>Implicit Broadcasts</h4><p>Implicit broadcasts don’t target a specific receiver. They’re identified only by their action string, so any receiver with a matching action can process them.</p><p><strong>Example: Sending an Implicit Broadcast</strong></p><pre>val intent = Intent(&quot;com.example.MY_CUSTOM_ACTION&quot;)<br>sendBroadcast(intent)</pre><p><strong>Example: Receiving an Implicit Broadcast</strong></p><pre>val filter = IntentFilter(&quot;com.example.MY_CUSTOM_ACTION&quot;)<br>registerReceiver(MyBroadcastReceiver(), filter)</pre><h4>Explicit Broadcasts</h4><p>Explicit broadcasts target a specific BroadcastReceiver class. They’re safer and ensure only the intended receiver processes the broadcast.</p><p><strong>Example: Sending an Explicit Broadcast</strong></p><pre>val intent = Intent(this, MyBroadcastReceiver::class.java)<br>sendBroadcast(intent)</pre><h3>6. Local Broadcasts</h3><p>Local broadcasts are a lightweight alternative for app-internal communication. They:</p><ul><li>Are faster because they don’t leave the app’s process.</li><li>Are more secure since other apps can’t intercept them.</li></ul><p><strong>Example: Sending a Local Broadcast</strong></p><pre>val intent = Intent(&quot;com.example.LOCAL_ACTION&quot;)<br>LocalBroadcastManager.getInstance(context).sendBroadcast(intent)</pre><p><strong>Example: Receiving a Local Broadcast</strong></p><pre>val filter = IntentFilter(&quot;com.example.LOCAL_ACTION&quot;)<br>LocalBroadcastManager.getInstance(context).registerReceiver(MyBroadcastReceiver(), filter)</pre><h3>7. Best Practices for Broadcasts</h3><ol><li><strong>Be Specific with Actions</strong><br>Use unique action strings (e.g., com.example.APP.ACTION_NAME) to avoid conflicts with other apps.</li><li><strong>Restrict Access with </strong><strong>android:exported=&quot;false</strong><br>For private events, ensure your receiver isn’t exposed to other apps.</li><li><strong>Use Explicit Broadcasts for Targeted Communication</strong><br>This prevents other apps from hijacking or interfering with your broadcasts.</li><li><strong>Unregister Dynamic Receivers</strong><br>Always unregister dynamic receivers in onPause() or onDestroy() to avoid memory leaks.</li><li><strong>Prefer Local Broadcasts for App-Internal Communication</strong><br>They’re faster, safer, and simpler than global broadcasts.</li></ol><p>Broadcasts are a cornerstone of Android app communication. Whether you’re reacting to system events like low battery or building custom events for your app, understanding how and when to use broadcasts is essential. By carefully choosing between manifest or dynamic registration, implicit or explicit communication, and global or local broadcasts, you can make your app more responsive and secure.</p><p>I hope you found this guide helpful! Below is the link to a GitHub repository containing a complete example of implementing broadcasts in Android. Happy coding! 🚀</p><p><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts/tree/master/broadcast-event/src/main/java/com/example/broadcast_event">Epic-Android-Concepts/broadcast-event/src/main/java/com/example/broadcast_event at master · Vishwajith-Shettigar/Epic-Android-Concepts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c05c1f431892" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Push Notifications using FCM in Android.]]></title>
            <link>https://proandroiddev.com/push-notification-using-firebase-in-android-fcb78da6a443?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcb78da6a443</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 14:51:34 GMT</pubDate>
            <atom:updated>2025-08-07T17:35:26.816Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>from </em><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts"><strong><em>Epic Android Concepts</em></strong></a><em> series.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iL18tDKv_8DgFRlZEEK0mg.png" /></figure><p>Push notifications are a vital part of modern mobile applications, enabling real-time communication with users. In this blog, we’ll build a complete push notification system using <strong>Firebase Cloud Messaging (FCM)</strong>, <strong>Android (Kotlin)</strong>, and <strong>Node.js</strong> as the server. We’ll walk through the fundamentals, setup, and implementation details step by step.</p><h3>1. What are Push Notifications?</h3><p>Push notifications are short, timely messages sent to users device to engage them with the app.</p><p><strong>Firebase Cloud Messaging (FCM)</strong> is a free service by Google that allows developers to send notifications across platforms like Android, IOS, and Web.</p><h3>2. How FCM Works: A Quick Overview</h3><ol><li><strong>FCM Token</strong>: Each device registered with FCM gets a unique token. We can store the token in any database for future use. This token acts as the address for sending notifications to that device.</li><li><strong>Server-to-FCM Communication</strong>: The server uses the <strong>FCM v1 HTTP API</strong> or Firebase Admin SDK to send messages to specific tokens.</li><li><strong>FCM-to-Device Communication</strong>: Firebase delivers the notification to the device, which either displays it or processes it silently.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-FPpJvDBhdDpePByCrXAg.png" /></figure><h3>3. Setting Up Your Environment</h3><p>To implement push notifications, we’ll need:</p><ul><li>An Android app (Kotlin).</li><li>A Node.js server to trigger notifications. You can use any other framework to create server, in this article we will be using node.js</li></ul><h4>3.1 Firebase Setup</h4><ol><li>Go to the Firebase Console.</li><li>Create a new project or use an existing one.</li><li>Add your Android app by registering its package name and downloading the google-services.json file.</li><li>Enable <strong>Firebase Cloud Messaging</strong> under the Firebase project settings.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gdGcSf_uWd5sePI5-aEgQ.png" /></figure><h4>3.2 Android Project Setup</h4><ol><li>Add the following dependencies to your module’s build.gradle file.</li></ol><pre>implementation platform(&#39;com.google.firebase:firebase-bom:34.0.0&#39;)<br>implementation &#39;com.google.firebase:firebase-messaging&#39;</pre><h3>4. Implementation in Android</h3><h4>4.1 Store FCM token when user creates account in your app.</h4><p>It’s always good practice to create and store the FCM token when a user creates an account in your app.</p><pre>FirebaseMessaging.getInstance().token.addOnCompleteListener { task -&gt;<br>    if (task.isSuccessful) {<br>        val token = task.result<br>        storeTokenInFirestore(userId, token)<br>    } else {<br>        Log.e(&quot;FCM&quot;, &quot;Failed to fetch token&quot;, task.exception)<br>    }<br>}</pre><h4>4.2 Receive Push Notifications</h4><ol><li><strong>Extend FirebaseMessagingService</strong>: Create a service to handle token generation and incoming messages:</li></ol><pre>@HiltAndroidApp<br>class MyFirebaseMessagingService : FirebaseMessagingService() {<br><br>// Assuming you have access to userId<br>private val userId:String= &quot;userId&quot;<br><br>    override fun onNewToken(token: String) {<br>        super.onNewToken(token)<br>// FCM token could change anytime, this method will be called,<br>// when there is new updated token for this user, so always update user&#39;s<br>// fcm token in your databse.<br>// Store fcm token in user&#39;s record, so that later<br>// could be used to send notification to same user.<br><br>Log.d(&quot;FCM&quot;, &quot;Token: $token&quot;)<br>// Save or update token.<br>updateTokenInFireStore(userId,token);<br>    }<br><br>    override fun onMessageReceived(remoteMessage: RemoteMessage) {<br> // This method will be called everytime FCM service sends message.<br>        super.onMessageReceived(remoteMessage)<br>        remoteMessage.data?.let {<br>            showNotification(it[&quot;title&quot;], it[&quot;body&quot;])<br>        }<br>    }<br><br>    private fun showNotification(title: String?, body: String?) {<br>        val channelId = &quot;default_channel&quot;<br>        val channelName = &quot;Default Channel&quot;<br><br>        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {<br>            val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH)<br>            notificationManager.createNotificationChannel(channel)<br>        }<br><br>        val notification = NotificationCompat.Builder(this, channelId)<br>            .setContentTitle(title)<br>            .setContentText(body)<br>            .setSmallIcon(R.drawable.ic_notification)<br>            .setPriority(NotificationCompat.PRIORITY_HIGH)<br>            .build()<br><br>        notificationManager.notify(0, notification)<br>    }<br>}</pre><p><strong>2. Update the Manifest</strong>: Add your FirebaseMessagingService to the manifest:</p><pre>&lt;service android:name=&quot;.MyFirebaseMessagingService&quot;<br>    android:exported=&quot;true&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot;/&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><h3>5. Implementing the Server in Node.js</h3><p>Now, let’s build the backend server to send notifications.</p><h4>5.1 Configure Firebase Admin SDK</h4><ul><li>Download the Firebase Admin SDK key from the Firebase console (under Project Settings &gt; Service Accounts).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8MGo9vAWrLrMffMXefpAA.png" /></figure><ul><li>Save it as serviceAccountKey.json in your server directory.</li><li>Initialize Firebase in your Node.js server:</li></ul><pre>const admin = require(&quot;firebase-admin&quot;);<br>const serviceAccount = require(&quot;./serviceAccountKey.json&quot;);<br><br>admin.initializeApp({<br>    credential: admin.credential.cert(serviceAccount),<br>});</pre><h4>5.2 Sending Notifications</h4><p>Create an Express endpoint to send notifications:</p><pre>const express = require(&quot;express&quot;);<br>const bodyParser = require(&quot;body-parser&quot;);<br>const admin = require(&quot;firebase-admin&quot;);<br><br>// Please create your service account key in your project settings under service tab.<br>const serviceAccount = require(&quot;./serviceAccountKey.json&quot;);<br><br>admin.initializeApp({<br>    credential: admin.credential.cert(serviceAccount),<br>});<br><br>const app = express();<br><br>const firestore = admin.firestore();<br><br>app.use(bodyParser.json());<br><br>app.post(&quot;/send-notification&quot;, async (req, res) =&gt; {<br>// Assuming we have the userIds, title, and body to send notifications.<br>    const {<br>        userIds,<br>        title,<br>        body<br>    } = req.body;<br><br>    try {<br>        const allTokens = [];<br><br>         // We will retreive tokens of users whoes usersId we have<br>        for (const userId of userIds) {<br>            const userDoc = await firestore.collection(&quot;users&quot;).doc(userId).get();<br>            if (userDoc.exists &amp;&amp; userDoc.data().fcmToken) {<br>                const token = userDoc.data().fcmToken;<br>                allTokens.push(token);<br>            }<br>        }<br><br>        // create a message, that includes token, title, and body.<br>        const message = {<br>            data: {<br>                title: title,<br>                body: body,<br>            },<br>            token: &quot;&quot;,<br>        };<br><br>        // Send messages to FCM server.<br>        const notificationPromises = allTokens.map(async (token) =&gt; {<br>            message.token = token<br>      // Firebase Admin SDK sends message to specific token.<br>         await admin.messaging().send(message);<br>        })<br><br>        await Promise.all(notificationPromises);<br><br>        res.status(200).send(&quot;Notification sent&quot;);<br>    } catch (error) {<br>        console.error(&quot;Error sending notification:&quot;, error);<br>        res.status(500).send(error);<br>    }<br>});<br><br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));</pre><p>Data messages (data field) are not displayed as notifications when the app is in the background or killed. Only <strong>notification messages</strong> (using the notification field) will appear in the system tray unless custom logic is implemented in the app(which we already done).</p><p>You can add notification field, so that you don’t need to handle message manually, like below</p><pre>const message = {<br>    notification: {<br>        title: title,<br>        body: body,<br>    },<br>token:device_token<br>}</pre><p>Combining Notification and Data Payloads</p><pre>{<br>  &quot;notification&quot;: {<br>    &quot;title&quot;: &quot;New Message&quot;,<br>    &quot;body&quot;: &quot;You have a new message.&quot;<br>  },<br>  &quot;data&quot;: {<br>    &quot;key1&quot;: &quot;value1&quot;,<br>    &quot;key2&quot;: &quot;value2&quot;<br>  },<br>  &quot;token&quot;: &quot;device_token&quot;<br>}</pre><h4>Behavior:</h4><ol><li><strong>App in Foreground</strong>:</li></ol><ul><li>The data payload is passed to onMessageReceived.</li><li>The notification payload is <strong>not displayed automatically</strong>, but you can process it in onMessageReceived.</li></ul><p><strong>2. App in Background or Killed</strong>:</p><ul><li>The notification payload is displayed automatically by Firebase.</li><li>The data payload is included as part of the notification and can be accessed when the user interacts with the notification.</li></ul><p>Don’t forget to install dependencies.</p><pre>npm install express body-parser firebase-admin</pre><h3>6. Test Push Notification.</h3><ol><li>Run the server: node server.js.</li><li>Use tools like Postman to send a POST request to http://localhost:3000/send-notification with a JSON body:</li></ol><pre>{<br>    &quot;userIds&quot; : [&quot;673bdkw72k&quot;],<br>    &quot;title&quot; : &quot;You have got new notification&quot;,<br>    &quot;body&quot; :&quot; Epic Android Concepts Series, ep 3&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucQXySMt3CBlgJmD51_Whw.png" /></figure><p>I hope you found this guide helpful and now have a solid understanding of how to implement push notifications using FCM in Android. For a complete working example, you can visit the GitHub repository linked below.</p><p>Thank you for reading this far, and happy coding! 🚀</p><p><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts/tree/master/push-notification/src/main/java">Epic-Android-Concepts/push-notification/src/main/java at master · Vishwajith-Shettigar/Epic-Android-Concepts</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcb78da6a443" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/push-notification-using-firebase-in-android-fcb78da6a443">Push Notifications using FCM in Android.</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[Navigation in Jetpack Compose — Android]]></title>
            <link>https://medium.com/@zekromvishwa56789/navigation-in-jetpack-compose-android-7eff5770eb50?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eff5770eb50</guid>
            <category><![CDATA[navigation-in-compose]]></category>
            <category><![CDATA[compose-ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[navcontroller]]></category>
            <category><![CDATA[navigation]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 15:04:25 GMT</pubDate>
            <atom:updated>2024-09-22T15:28:28.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Navigation in Jetpack Compose — Android</h3><blockquote>from <strong>Epic Android Concepts</strong> series.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5s3GTRFJT63eqLJ1lLF08g.png" /></figure><h3>Basic Overview</h3><h4>1. NavHost</h4><p>The NavHost is the primary container for your navigation graph. It determines which composable screen should be displayed based on the current state of the NavController.</p><pre>val navController = rememberNavController()<br>NavHost(navController = navController, startDestination = &quot;home&quot;) {<br>    composable(&quot;home&quot;) { HomeScreen(navController) }<br>    composable(&quot;profile&quot;) { ProfileScreen(navController) }<br>}</pre><h4>2. NavController</h4><p>The NavController is responsible for managing app navigation. It handles the back stack, performs navigation actions, and manages destination arguments.</p><pre>navController.navigate(&quot;profile&quot;)</pre><h4>3. Composable Destinations</h4><p>Each screen in your app is defined as a composable function within the NavHost. You can also pass parameters to your screens.</p><pre>composable(&quot;detail&quot;) { DetailScreen(navController) }</pre><p>Now you may have a basic understanding of the core components of navigation in Compose. If not, no worries — I’ve explained them below with examples.</p><p>Let’s say you have two screens: Home and Profile. The user can navigate between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbmjbPHLPxUs_JNJKr_bOQ.png" /></figure><p>This is how code looks.</p><pre>class NavigationExample : ComponentActivity() {<br>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContent {<br>        // Here we have created navController to navigate between screens.<br>        val navController = rememberNavController()<br><br>        // When the app opens, the default home screen will display because<br>        // we set startDestination = &quot;home&quot;.<br>        NavHost(navController = navController, startDestination = &quot;home&quot;) {<br>            composable(&quot;home&quot;) {<br>                HomeScreen() {<br>                    // When the user clicks the button on the home screen, this will be triggered.<br>                    navController.navigate(&quot;profile&quot;)<br>                }<br>            }<br>            composable(&quot;profile&quot;) {<br>                ProfileScreen() {<br>                    // When the user clicks the button on the profile screen, this will be triggered.<br>                    navController.navigate(&quot;home&quot;)<br>                }<br>            }<br>        }<br>    }<br>}<br>}<br><br>@Composable<br>fun HomeScreen(onClick: () -&gt; Unit) {<br>  var num by rememberSaveable {<br>    mutableStateOf(1)<br>  }<br><br>  Row(<br>    modifier = Modifier.fillMaxSize(),<br>  )<br>  {<br>    LazyColumn(<br>      modifier = Modifier<br>          .wrapContentSize()<br>          .weight(1f),<br>      horizontalAlignment = Alignment.CenterHorizontally,<br>      verticalArrangement = Arrangement.Center<br>    ) {<br>      items(130) {<br>        Text(text = &quot;Home Screen!   -&gt;&quot; + it)<br>      }<br>    }<br>    Column(<br>      modifier = Modifier<br>          .wrapContentSize()<br>          .weight(1f)<br>    ) {<br>      Text(text = &quot;Home Screen!   -&gt;&quot; + num)<br>      Button(onClick = { num++ }) {<br>        Text(&quot;Increment&quot;)<br>      }<br>      Button(onClick = { onClick() }) {<br>        Text(&quot;Go to profile&quot;)<br>      }<br>    }<br>  }<br>}<br><br>@Composable<br>fun ProfileScreen(onClick: () -&gt; Unit) {<br>  Column(<br>    modifier = Modifier.fillMaxSize(),<br>    horizontalAlignment = Alignment.CenterHorizontally,<br>    verticalArrangement = Arrangement.Center<br>  )<br>  {<br>    Text(text = &quot;Profile Screen!&quot;)<br>    Button(onClick = { onClick() }) {<br>      Text(&quot;Go to Home&quot;)<br>    }<br>  }<br>}</pre><p>Let’s say the user navigates from Home to Profile and back to Home through buttons that trigger navController.navigate(route). The route is essentially the destination name, e.g., Home and Profile.</p><p>This is how the backstack looks after the navigations: Home -&gt; Profile, Profile -&gt; Home, Home -&gt; Profile. This will pile up the backstack and may slow down the app&#39;s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*gYlOsxRaGMDC6dewnHVfNg.png" /></figure><p>Here is the solution: we can remove the current screen from the back stack and navigate to the previous screen.</p><p>Let’s say you are on the profile screen, which is your current screen and at the top of the back stack. If you click the button, it will remove the profile screen from the back stack and display the previous screen. This will help prevent a pile-up in the back stack.</p><pre>class NavigationExample : ComponentActivity() {<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContent {<br>            // Here we have created navController to navigate between screens.<br>            val navController = rememberNavController()<br><br>            // When the app opens, the default home screen will display because<br>            // we set startDestination = &quot;home&quot;.<br>            NavHost(navController = navController, startDestination = &quot;home&quot;) {<br>                composable(&quot;home&quot;) {<br>                    HomeScreen() {<br>                        // When the user clicks the button on the home screen, this will be triggered.<br>                        navController.navigate(&quot;profile&quot;)<br>                    }<br>                }<br>                composable(&quot;profile&quot;) {<br>                    ProfileScreen() {<br>                        // When the user clicks the button on the profile screen, this will be triggered.<br>                        // navController.popBackStack() will pop the profile screen,<br>                        // which is on top of the back stack.<br>                        navController.popBackStack()<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Basically, navController.popBackStack() removes the top screen from the back stack. If you want to pop multiple screens from the stack, let’s say your navigation looks like this in an app: home → profile → details. If you are on the details screen, which is at the top of the stack, your back stack looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*fk6oTl1WPP8cQ9f5uUGYxw.png" /></figure><p>Now, if you want to navigate back to the home screen by popping the details and profile screens, here’s how you do that.</p><pre>class NavigationExample : ComponentActivity() {<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContent {<br>      val navController = rememberNavController()<br>      NavHost(navController = navController, startDestination = &quot;home&quot;) {<br>        composable(&quot;home&quot;) {<br>          HomeScreen() {<br>            navController.navigate(&quot;profile&quot;)<br>          }<br>        }<br>        composable(&quot;profile&quot;) {<br>          ProfileScreen() {<br>            navController.navigate(&quot;details&quot;)<br>          }<br>        }<br><br>// Here we added a new screen.<br>composable(&quot;details&quot;) {<br>    DetailsScreen() {<br>        // This will pop the screen back to the profile.<br>        navController.popBackStack(route = &quot;profile&quot;, inclusive = true)<br>    }<br>}<br><br>      }<br>    }<br>  }<br>}</pre><p>There, you can see a parameter named ‘inclusive,’ which I set to true. This means that when popping from the details screen to the profile screen, the profile screen will also be removed. If we set it to false, it will pop from the top screen down to the profile screen, but it won’t remove the profile screen itself.</p><p>Now, the back stack looks like this (inclusive = true).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_Fe6P27x7_tCJbRxaiR88w.png" /></figure><p>Remember, popBackStack removes screens from the top of the stack to the specified route. In our case, the details screen was at the top.</p><h4><strong>launchSingleTop</strong></h4><p>Now, let’s say an app has a bottom navigation bar with a home button. When the user clicks the home button, it navigates to the home screen. However, if the user keeps clicking the home button, it can create multiple instances of the home screen. To avoid this, we use launchSingleTop.</p><pre>  navController.navigate(&quot;home&quot;){<br>              launchSingleTop= true<br>            }</pre><p>This prevents the creation of the same screen instance again if that screen is already on top. If the home screen is at the top of the back stack and the user clicks the home button again, the app will check what screen is on top. If the home screen is already at the top of the stack, it will not create a new instance of the home screen.</p><h4><strong>popUpTo</strong></h4><p>Let’s say you have three screens: a splash screen, a login screen, and a home screen. The splash screen will be the start destination. When the user navigates to the login screen and then enters their login details to go to the home screen, we should destroy both the login and splash screens so that the user cannot return to the login screen. We can achieve this using popUpTo(route, inclusive).</p><pre>val navController = rememberNavController()<br><br>  NavHost(navController = navController, startDestination = &quot;splash&quot;) {<br><br>    composable(&quot;splash&quot;) {<br><br>      SplashScreen() {<br>        navController.navigate(&quot;login&quot;) {<br>        }<br>      }<br>    }<br>    composable(&quot;login&quot;) {<br>      LoginScreen() {<br>        navController.navigate(&quot;home&quot;) {<br>// Before navigating to home, it will pop the screen from the top to the splash screen,<br>// and then navigate to the home screen and push the home screen onto the stack.<br><br>          popUpTo(&quot;splash&quot;) {<br>            inclusive = true<br>          }<br>        }<br>      }<br>    }<br>    composable(&quot;home&quot;) {<br>      HomeScreen() {<br>      }<br>    }<br>  }</pre><p>Before the user clicks the login button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*x11z5LQqrsvG2OhIFOyFNw.png" /></figure><p>After the user clicks the login button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*_Fe6P27x7_tCJbRxaiR88w.png" /></figure><h3><strong>navController.navigateUp()</strong></h3><p>The method navController.navigateUp() is used to navigate up in the app&#39;s navigation hierarchy, which typically means going back to the parent screen of the current destination.</p><p>If the back stack is empty and you call navController.navigateUp(), the behavior depends on the context in which it&#39;s called:</p><ol><li><strong>No Parent Destination</strong>: If the current destination has no parent defined in the navigation graph (e.g., if it was the initial destination), navigateUp() will effectively do nothing. The app remains on the current screen since there’s nowhere to navigate up to.</li><li><strong>Back Navigation</strong>: If you try to navigate up and there are no more destinations in the back stack, it generally means you would be returning to the home screen of the app or exiting if the home screen is the only destination.</li><li><strong>On the Home Screen</strong>: In a typical app setup, if you’re already on the home screen (the first screen in your navigation graph) and you call navigateUp(), it won&#39;t change the screen since you’re at the root of the navigation hierarchy.</li></ol><pre>composable(&quot;home&quot;) {<br>      HomeScreen() {<br>// In our case, it will navigate to the splash screen, despite the absence of the splash screen in the back stack.       <br> navController.navigateUp()<br>      }<br>    }</pre><h4><strong>saveState and restoreState</strong></h4><p>When a screen is in the back stack and you revisit it, the state of the screen remains the same. However, if you pop the screen from the back stack and navigate to it again, it will show a new UI state. To save and restore the UI state even when the screen is removed from the back stack, we use saveState and restoreState.</p><p>For example, if you are on the home screen and navigate to the profile screen, then pop the home screen from the back stack, using saveState allows you to restore the old UI state when you navigate back to the home screen.</p><pre> val navController = rememberNavController()<br><br>  NavHost(navController = navController, startDestination = &quot;home&quot;) {<br>    composable(&quot;home&quot;) {<br>      HomeScreen() {<br>        navController.navigate(&quot;profile&quot;) {<br>          // pop home screen and navigate to profile screen.<br>          popUpTo(&quot;home&quot;) {<br>            inclusive = true<br>// Save the state of the popped screen.<br>            saveState = true<br>          }<br>        }<br>      }<br>    }<br>    composable(&quot;profile&quot;) {<br>      ProfileScreen(btnLabel = &quot;home&quot;) {<br>        navController.navigate(&quot;home&quot;) {<br>// Restore the UI state of the home screen.<br>          restoreState = true<br>        }<br>      }<br>    }<br>  }</pre><p>Here, I covered the basics and essentials of navigation in Compose. The remaining topics, such as passing data through navigation and deep links, will be covered in upcoming articles in this Epic Android Concepts series.</p><p><strong>Code sample link here :</strong></p><p><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts/tree/master/navigation-compose">Epic-Android-Concepts/navigation-compose at master · Vishwajith-Shettigar/Epic-Android-Concepts</a></p><p>Please let me know if I have delivered the concepts in an understandable way. Thank you for reading this far!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eff5770eb50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content Provider in Android with Kotlin.]]></title>
            <link>https://medium.com/@zekromvishwa56789/understanding-contentprovider-and-contentresolver-in-android-with-kotlin-f31952062649?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f31952062649</guid>
            <category><![CDATA[contactscontract]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[content-resolver]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[contentprovider]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Mon, 05 Aug 2024 15:22:49 GMT</pubDate>
            <atom:updated>2024-09-30T02:43:18.525Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>from </em><strong><em>Epic Android Concepts</em></strong><em> series.</em></blockquote><h4>What is <strong>ContentProvider </strong>and <strong>ContentResolver </strong>?</h4><p>Let’s take a scenario: an app named “Chat Me,” which is essentially a chat app. It needs contacts from your phone to display them to you so that you can click on them and chat with your friends. But how does it get that contact list? This is where ContentResolvers come into play. The “Chat Me” app uses ContentResolvers to fetch contacts from your phone’s contacts app and display them to you. But you might have one big question: how does your phone’s contact app allow other apps to fetch contacts? It does this using a ContentProvider.</p><p>A ContentProvider can serve its own app’s components as well. If it were only serving its own components, we would never use a ContentProvider; instead, we would use some kind of database like RoomDB, SQLite, etc. However, there is a catch: ContentProviders often use a database, such as SQLite, to manage the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*G7__y3vcvhESni7X.png" /><figcaption>Image source: <a href="https://developer.android.com/guide/topics/providers/content-provider-basics">developer.android.com</a></figcaption></figure><p>A ContentProvider acts as an abstraction layer that provides a standard interface for accessing and managing data in one application, making it accessible to other applications. It is particularly useful for sharing data across different applications or within different components of the same application. ContentProvider can manage various data sources, including SQLite databases, files, or even network data.</p><p>A ContentResolver is an interface that provides methods for interacting with ContentProviders. It acts as a client to communicate with ContentProviders to perform data operations. When an application needs to access data exposed by a ContentProvider, it uses a ContentResolver.</p><h4>Before diving into the implementation of ContentProvider, let’s learn about Content URIs (Uniform Resource Identifiers).</h4><p>A Content URI is a special type of URI used by Android’s ContentProvider to identify data. Unlike regular URIs used for accessing files or web resources, Content URIs are used specifically to interact with data stored within a ContentProvider.</p><p>Structure of a Content URI</p><pre>content://&lt;authority&gt;/&lt;path&gt;/&lt;id&gt;</pre><p><strong>Scheme:</strong> Always content:// for content providers.</p><p><strong>Authority:</strong> Identifies the ContentProvider. It is a unique string, typically in the form of a package name or custom identifier (e.g., com.example.myprovider).</p><p><strong>Path:</strong> Specifies the type of data (e.g., contacts). It can also include specific identifiers (e.g., contacts/1).</p><p><strong>ID (Optional):</strong> Specifies a specific record (e.g., 1). If omitted, it usually refers to a collection of records.</p><p><strong>But why are we learning about Content URIs?</strong></p><p>In your ContentProvider, you define which URIs are supported and what data they correspond to. This is typically done using a UriMatcher. When an app queries the ContentProvider, it uses a Content URI to specify what data it needs.</p><p>For example, when the “Chat me” app retrieves all contacts from your phone’s contacts app, it uses the Content URI content://com.example.myprovider/contacts with the ContentResolver. In this URI, content is the scheme, com.example.myprovider is the authority, and contacts is the path, which essentially represents the table name.</p><p>In your phone’s contacts app, the URI content://com.example.myprovider/contacts must be defined in the ContentProvider to enable data sharing with other apps like &quot;Chat me.&quot;</p><ul><li>content://com.example.myprovider/contacts/1 represents a single record.</li><li>content://com.example/myprovider/contacts represents the whole table.</li></ul><p>If you want to build an app that shares contacts with other apps like “Chat me” or with other components of the same app, you need to implement a ContentProvider. On the other hand, if your app only needs to access data from a ContentProvider provided by another app, you only need to implement a ContentResolver.</p><h3>Now, let’s learn how to implement a ContentProvider using SQLite to support data sharing with apps like &quot;Chat me.&quot;</h3><p>Lets write code for sqlite database helper</p><pre>class DatabaseHelper(context: Context) : SQLiteOpenHelper(<br>  context, DATABASE_NAME, null, DATABASE_VERSION<br>) {<br><br>  companion object {<br>    const val DATABASE_NAME = &quot;mydatabase&quot;<br>    const val DATABASE_VERSION = 1<br>    const val TABLE_NAME = &quot;contacts&quot;<br>    const val TABLE_CREATE_QUERY = &quot;create table $TABLE_NAME&quot; +<br>      &quot;(_id INTEGER PRIMARY KEY NOT NULL,&quot; +<br>      &quot;name TEXT,&quot; +<br>      &quot;phone TEXT)&quot;<br>  }<br><br>  override fun onCreate(db: SQLiteDatabase?) {<br>    db?.execSQL(TABLE_CREATE_QUERY)<br>  }<br><br>  override fun onUpgrade(db: SQLiteDatabase?, p1: Int, p2: Int) {<br>    db?.execSQL(&quot;DROP TABLE IF EXISTS $TABLE_NAME&quot;)<br>  }<br>}</pre><p>The DatabaseHelper class will be used by the ContentProvider to access and manage data. We will discuss when the onCreate() method is called and how the database will create a table named &quot;contacts&quot; later.</p><p>Here’s how you can create the MyContentProvider class:</p><pre>class MyContentProvider : ContentProvider() {<br>  companion object {<br>    const val AUTHORITY = &quot;com.example.mycontentprovider&quot;<br>    val CONTENT_URI: Uri = Uri.parse(&quot;content://$AUTHORITY/$TABLE_NAME&quot;)<br>    const val MYTABLE = 1<br>    const val MYTABLE_ID = 2<br><br>    val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {<br>      addURI(AUTHORITY, TABLE_NAME, MYTABLE)<br>      addURI(AUTHORITY, &quot;$TABLE_NAME/#&quot;, MYTABLE_ID)<br>    }<br>  }<br><br>  private lateinit var databaseHelper: DatabaseHelper<br><br>  override fun onCreate(): Boolean {<br>    databaseHelper = DatabaseHelper(context!!)<br>    return true<br>  }<br><br>  override fun query(<br>    uri: Uri,<br>    columns: Array&lt;out String&gt;?,<br>    selection: String?,<br>    selectionArgs: Array&lt;out String&gt;?,<br>    sortOrder: String?,<br>  ): Cursor? {<br>    val db = databaseHelper.readableDatabase<br><br>    when (uriMatcher.match(uri)) {<br>      MYTABLE -&gt; {<br>        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)<br>      }<br>      MYTABLE_ID -&gt; {<br>        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)<br>      }<br>    }<br>    return null<br>  }<br><br>  override fun getType(uri: Uri): String {<br>    return when (uriMatcher.match(uri)) {<br>      MYTABLE -&gt; &quot;vnd.android.cursor.dir/vnd.com.example.$TABLE_NAME&quot;<br>      MYTABLE_ID -&gt; &quot;vnd.android.cursor.item/vnd.com.example.$TABLE_NAME&quot;<br>      else -&gt; throw IllegalArgumentException(&quot;Unsupported URI: $uri&quot;)<br>    }<br>  }<br><br>  override fun insert(uri: Uri, values: ContentValues?): Uri {<br>    val db = databaseHelper.writableDatabase<br>    val id = db.insert(TABLE_NAME, null, values)<br>    context?.contentResolver?.notifyChange(uri, null)<br>    val resultUri = ContentUris.withAppendedId(CONTENT_URI, id)<br>    context?.contentResolver?.notifyChange(resultUri, null, true)<br>    return resultUri<br>  }<br><br>  override fun delete(uri: Uri, selection: String?, selectionArgs: Array&lt;String&gt;?): Int {<br>    val db = databaseHelper.writableDatabase<br>    val count = db.delete(TABLE_NAME, selection, selectionArgs)<br>    context?.contentResolver?.notifyChange(uri, null)<br>    return count<br>  }<br><br>  override fun update(<br>    uri: Uri, values: ContentValues?, selection: String?,<br>    selectionArgs: Array&lt;String&gt;?,<br>  ): Int {<br>    val db = databaseHelper.writableDatabase<br>    val count = db.update(TABLE_NAME, values, selection, selectionArgs)<br>    context?.contentResolver?.notifyChange(uri, null)<br>    return count<br>  }<br>}</pre><p>This class extends the ContentProvider class and overrides the onCreate(), query(), insert(), update(), delete(), and getType() methods.</p><p>In the companion object, we defined all the necessary constants, such as:</p><pre>    const val AUTHORITY = &quot;com.example.mycontentprovider&quot;<br>    val CONTENT_URI: Uri = Uri.parse(&quot;content://$AUTHORITY/$TABLE_NAME&quot;)<br>    const val MYTABLE = 1<br>    const val MYTABLE_ID = 2</pre><p>Now, our URI looks like content://com.example.mycontentprovider/contacts</p><pre>val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {<br>      addURI(AUTHORITY, TABLE_NAME, MYTABLE)<br>      addURI(AUTHORITY, &quot;$TABLE_NAME/#&quot;, MYTABLE_ID)<br>    }</pre><p>The UriMatcher will be explained when we discuss retrieving all records from the table and specific records from the table.</p><h3><strong>1. onCreate()</strong></h3><p>In the onCreate() method, we initialize the DatabaseHelper so that we can use it to access the database in later queries.</p><p>When is onCreate() called exactly?</p><p>When your application starts, the ContentProvider is not immediately created. Instead, it is instantiated lazily. The ContentProvider&#39;s onCreate() method is called the first time it is accessed via a ContentResolver. This means that if any part of your application or another application tries to access the content provider&#39;s data for the first time (using methods like query(), insert(), update(), delete(), or getType()), the onCreate() method will be triggered.</p><h3><strong>2. query()</strong></h3><p>This method is called when another app, or a part of the same application, wants to retrieve records. In the query() method, you can pass a URI, specify the column names you want to retrieve, provide a where clause (such as the selection column), and supply selection arguments to retrieve specific rows. Essentially, this is like executing an SQL query.</p><p>Inside this method, we instantiate the database to perform the query operations.</p><pre>val db = databaseHelper.readableDatabase</pre><p>At this point, the DatabaseHelper class’s onCreate() method will be called, and it will create a table named &quot;contacts&quot;. This code is present in all other methods such as insert, delete, and update, but these methods do not create a new table if it already exists. Instead, they obtain a reference to the database and execute the appropriate queries.</p><pre>return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)</pre><p>let’s dive into UriMatcher.</p><p>MYTABLE=1</p><p>MYTABLE_ID=2</p><pre>val uriMatcher = UriMatcher(UriMatcher.NO_MATCH).apply {<br>addURI(AUTHORITY, TABLE_NAME, MYTABLE) //addURI( &quot;com.example.mycontentprovider&quot;,&quot;contacts&quot;,1)<br><br>addURI(AUTHORITY, &quot;$TABLE_NAME/#&quot;, MYTABLE_ID) //addURI( &quot;com.example.mycontentprovider&quot;,&quot;contacts/1&quot;,2)<br>// # will match with any id(eg: 1,2,3, etc)<br>    }</pre><p>We are adding URIs to UriMatcher so that later we can use it to match URIs with codes like MYTABLE and MYTABLE_ID. Why do we need to match URIs with codes?</p><p>Let’s say the “Chat me” app wants only a single record, so it uses ContentResolver to write a query like this.</p><pre>// we will discuss more about this later in contentResolver part.<br>string id=1  <br>val selection = &quot;_id = ?&quot;<br>val selectionArgs = arrayOf(id)<br>val CONTENT_URI=&quot;com.example.mycontentprovider/contacts/1&quot;<br>val cursor = contentResolver.query(CONTENT_URI, null, selection, selectionArgs, null)</pre><p>This will call the query method in the ContentProvider. In this case, we use UriMatcher in our ContentProvider&#39;s query method to determine exactly what is being requested. The provided URI will match with MYTABLE_ID.</p><pre>when (uriMatcher.match(uri)) {<br>      MYTABLE -&gt; {<br>        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)<br>      }<br>      MYTABLE_ID -&gt; {<br>     // This query will gets executed<br>        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)<br>      }<br>    }</pre><p>Now, let’s say the “Chat me” app wants to retrieve the whole table.</p><pre><br>val CONTENT_URI=&quot;com.example.mycontentprovider/contacts&quot;<br>val cursor = contentResolver.query(CONTENT_URI, null, null, null, null)</pre><p>Provided uri will match with MYTABLE. and executes.</p><pre>when (uriMatcher.match(uri)) {<br>      MYTABLE -&gt; {<br>        // This query will gets executed<br>        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)<br>      }<br>      MYTABLE_ID -&gt; {<br>        return db.query(TABLE_NAME, columns, selection, selectionArgs, null, null, sortOrder)<br>      }<br>    }</pre><p>The URI passed to the ContentProvider&#39;s query method serves two purposes: it helps identify the correct data source and notifies observing processes when the data changes. This will be elaborated upon later in the context of insert, update, and delete operations. If you have multiple tables and corresponding URIs, the UriMatcher ensures that data is fetched from the correct table. However, retrieving the correct data ultimately depends on the selection arguments and column names you provide.</p><h3>3. insert()</h3><p>This method is used to insert data into the table. It returns the row ID where the data was inserted, and you can append this row ID to the URI to notify observing apps that this particular data is new or has changed. Observing apps will extract the row ID from the URI and use it as a selection argument to fetch the exact row using the query method.</p><pre>override fun insert(uri: Uri, values: ContentValues?): Uri {<br>    // Get writable database instance<br>    val db = databaseHelper.writableDatabase<br><br>    // Insert the values into the specified table and get the row ID of the newly inserted row<br>    val id = db.insert(TABLE_NAME, null, values)<br><br>    // Append the row ID to the CONTENT_URI to create a URI for the new row<br>    val resultUri = ContentUris.withAppendedId(CONTENT_URI, id)<br>    // resultUri will look like &quot;content://com.example.mycontentprovider/contacts/0&quot;<br><br>    // Notify all observing apps or components that the data has changed<br>    // Provide resultUri so they can query the updated data<br>    context?.contentResolver?.notifyChange(resultUri, null, true)<br><br>    return resultUri<br>}</pre><h3>4. update()</h3><p>This method is used to update data in the table. You can pass selection arguments to specify exactly what to update, and it will notify all observing apps of the changes.</p><pre>override fun update(<br>    uri: Uri, values: ContentValues?, selection: String?,<br>    selectionArgs: Array&lt;String&gt;?<br>): Int {<br>    val db = databaseHelper.writableDatabase<br>    // Updates records in the table and returns the count of updated records.<br>    val count = db.update(TABLE_NAME, values, selection, selectionArgs)<br>    // Notifies all observing apps that the data at the specified URI has changed.<br>    context?.contentResolver?.notifyChange(uri, null)<br>    return count<br>}</pre><h3>5. delete()</h3><p>This method used to delete data from table.</p><pre>override fun delete(uri: Uri, selection: String?, selectionArgs: Array&lt;String&gt;?): Int {<br>    val db = databaseHelper.writableDatabase<br>    // Deletes records from the table and returns the count of deleted records.<br>    val count = db.delete(TABLE_NAME, selection, selectionArgs)<br>    // Notifies all observing apps that the data at the specified URI has changed.<br>    context?.contentResolver?.notifyChange(uri, null)<br>    return count<br>}</pre><h3>6. getType()</h3><p>The getType() method in a ContentProvider is used to return the MIME type of the data at the given URI. This is useful for clients (such as other applications) to understand the type of data they are dealing with and how to handle it.</p><p>The getType() method typically returns a MIME type string based on the pattern of the URI. The MIME type format follows the structure:</p><ul><li><strong>vnd.android.cursor.dir/vnd.&lt;authority&gt;.&lt;path&gt;</strong>: Indicates a directory of items.</li><li><strong>vnd.android.cursor.item/vnd.&lt;authority&gt;.&lt;path&gt;</strong>: Indicates a single item.</li></ul><pre>  override fun getType(uri: Uri): String {<br>    return when (uriMatcher.match(uri)) {<br>      MYTABLE -&gt; &quot;vnd.android.cursor.dir/vnd.com.example.$TABLE_NAME&quot;<br>      MYTABLE_ID -&gt; &quot;vnd.android.cursor.item/vnd.com.example.$TABLE_NAME&quot;<br>      else -&gt; throw IllegalArgumentException(&quot;Unsupported URI: $uri&quot;)<br>    }<br>  }</pre><p>To allow other apps like “Chat Me” to access data from your ContentProvider, you need to declare the ContentProvider in your AndroidManifest.xml file. Here’s how you can do it:</p><pre>&lt;application<br>....<br>....<br>&gt;<br>&lt;provider<br>    android:name=&quot;com.example.contentproviders.MyContentProvider&quot;  &lt;!-- This is the path to your ContentProvider class. --&gt;<br>    android:authorities=&quot;com.example.mycontentprovider&quot;  &lt;!-- Authority name. --&gt;<br>    android:exported=&quot;true&quot; /&gt;  &lt;!-- Whether the ContentProvider is accessible to other apps. --&gt;<br>&lt;/application&gt;</pre><p>We’ve completed the implementation of the ContentProvider. Next, we’ll explore how different apps, like “Chat me,” can access data from a ContentProvider.</p><p>Before diving into the implementation of ContentResolver and learning how to access data from a ContentProvider, it’s important to understand how applications like “Chat me” obtain the URIs they use to access data. Typically, apps retrieve these URIs from the documentation provided by the content provider.</p><p>The documentation usually outlines the URIs available for data access, including how to structure them and what data they can access. This documentation is crucial for ensuring that the app queries the correct data and interacts with the ContentProvider properly.</p><p>In summary, the URIs act as a bridge between the app and the ContentProvider, allowing the app to request and retrieve the appropriate data. By consulting the documentation, developers can understand how to construct these URIs and use them effectively in their applications.</p><h3>Implementing contentResolver.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/0*189XQQS_5cSp5Dfl.png" /><figcaption>Image source: <a href="https://developer.android.com/guide/topics/providers/content-provider-basics">developer.android.com</a></figcaption></figure><p>Lets say you want all the contacts, you write query like below.</p><pre> private fun getAllContacts() :MutableList&lt;Contact&gt; {<br>val CONTENT_URI=Uri.parse(&quot;com.example.mycontentprovider/contacts&quot;)<br>val contactList=mutablelistof()<br>    val cursor = contentResolver.query(CONTENT_URI, null, null, null, null)<br><br>    if (cursor != null) {<br>      while (cursor.moveToNext()) {<br><br>        val id = cursor.getInt(cursor.getColumnIndex(&quot;_id&quot;))<br>        val name = cursor.getString(cursor.getColumnIndex(&quot;name&quot;))<br>        val phone = cursor.getString(cursor.getColumnIndex(&quot;phone&quot;))<br>        <br>        ccontactList.add(<br>          Contact(id, name, phone)<br>        )<br>      }<br>      cursor.close()<br>    }<br>  }</pre><p>val cursor = contentResolver.query(CONTENT_URI, null, null, null, null): This line queries the ContentProvider using the specified CONTENT_URI. The query method returns a Cursor object that can be used to iterate through the results. The null arguments indicate that all columns and rows are being requested without any specific filtering or sorting.</p><p>while (cursor.moveToNext()) { ... }: This loop iterates through each row in the cursor. The moveToNext() method moves the cursor to the next row and returns true if there is a next row, and false if there are no more rows.</p><ul><li>val id = cursor.getInt(cursor.getColumnIndex(&quot;_id&quot;)): This line retrieves the integer value of the _id column from the current row.</li><li>val name = cursor.getString(cursor.getColumnIndex(&quot;name&quot;)): This line retrieves the string value of the name column from the current row.</li><li>val phone = cursor.getString(cursor.getColumnIndex(&quot;phone&quot;)): This line retrieves the string value of the phone column from the current row</li></ul><p>cursor.close(): This line closes the cursor to release its resources. It is important to close the cursor to avoid memory leaks.</p><p>Lets say you want only single contacts you write query like below.</p><pre>private fun getChangedContact(id: String) {<br>// id = 0<br>val CONTENT_URI=Uri.parse(&quot;com.example.mycontentprovider/contacts/$id&quot;)<br>  val selection = &quot;_id = ?&quot;<br>  val selectionArgs = arrayOf(id)<br>  val cursor = contentResolver.query(CONTENT_URI, null, selection, selectionArgs, null)<br>  if (cursor != null) {<br>    while (cursor.moveToNext()) {<br>      val id = cursor.getInt(cursor.getColumnIndex(&quot;_id&quot;))<br>      val name = cursor.getString(cursor.getColumnIndex(&quot;name&quot;))<br>      val phone = cursor.getString(cursor.getColumnIndex(&quot;phone&quot;))<br>   <br>// Here we got single contact.<br>        val contact=Contact(id, name, phone)<br>     <br>    }<br>    cursor.close()<br>  }<br>}</pre><p>Insert new contact</p><ul><li><strong>ContentValues Preparation</strong>: A ContentValues object is prepared with the name and phone values.</li><li><strong>Insert Operation</strong>: contentResolver.insert(CONTENT_URI, contentValues) is called to insert the new contact into the ContentProvider.</li><li><strong>ID Generation</strong>: SQLite will automatically generate a unique ID for the new row.</li><li><strong>New URI</strong>: The insert method returns a URI pointing to the newly inserted row, which includes the new auto-generated ID.</li></ul><pre>private fun insertNewContact(name: String, phoneNumber: String) {<br>val CONTENT_URI=Uri.parse(&quot;com.example.mycontentprovider/contacts&quot;)<br>  val contentValues = ContentValues().apply {<br>    put(&quot;name&quot;, name)<br>    put(&quot;phone&quot;, phoneNumber)<br>  }<br>  val newUri = contentResolver.insert(CONTENT_URI, contentValues)<br>}</pre><p><strong>Update Existing Contact</strong></p><p>The updateContact function updates a contact in the database using the provided contact ID. Here&#39;s a concise summary:</p><ol><li><strong>Constructs the URI</strong>: Builds the URI for the specific contact to be updated, using the base content provider URI and the contact ID.</li><li><strong>Creates ContentValues</strong>: Prepares a ContentValues object with the new name and phone number from the input fields.</li><li><strong>Defines Selection Criteria</strong>: Specifies the selection criteria to identify the contact to be updated by its _id.</li><li><strong>Executes Update</strong>: Calls the update method on the contentResolver, passing the URI, ContentValues, selection criteria, and selection arguments.</li><li><strong>Updates the Contact</strong>: The database updates the contact with the provided new values, and the number of rows affected is returned and stored in updateCount.</li></ol><p>This function ensures that the contact with the given ID has its name and phone number updated in the database using the ContentProvider</p><pre>  private fun updateContact(id: Int) {<br>    val recordId = id<br>val CONTENT_URI=Uri.parse(&quot;com.example.mycontentprovider/contacts/$recordId&quot;)<br>    val updateValues = ContentValues().apply {<br>      put(&quot;name&quot;, binding.name.text.toString())<br>      put(&quot;phone&quot;, binding.phoneNumber.text.toString())<br>    }<br><br>    val selection = &quot;_id = ?&quot;<br>    val selectionArgs = arrayOf(recordId.toString())<br>    val updateCount = contentResolver.update(CONTENT_URI!!, updateValues, selection, selectionArgs)<br><br>  }</pre><p>Delete contact</p><p>The deleteContact function deletes a contact from the database using the provided contact ID.</p><ol><li><strong>Constructs the URI</strong>: Builds the base URI for the contacts table.</li><li><strong>Defines Selection Criteria</strong>: Specifies the selection criteria to identify the contact to be deleted by its _id.</li><li><strong>Executes Delete</strong>: Calls the delete method on the contentResolver, passing the URI, selection criteria, and selection arguments.</li><li><strong>Deletes the Contact</strong>: The database deletes the contact with the provided ID, and the number of rows affected is returned and stored in count.</li></ol><p>This function ensures that the contact with the given ID is deleted from the database using the ContentProvider.</p><pre>private fun deleteContact(id: Int) {<br>val CONTENT_URI=Uri.parse(&quot;com.example.mycontentprovider/contacts&quot;)<br>  val selection = &quot;_id = ?&quot;<br>  val selectionArgs = arrayOf(id.toString())<br> val count = contentResolver.delete(CONTENT_URI, selection, selectionArgs)<br>}</pre><h4><strong>Observe changes in contentProvider’s data</strong></h4><pre>  private lateinit var contentObserver: ContentObserver<br><br>  init  {<br>      contentObserver = object : ContentObserver(Handler()) {<br><br>      override fun onChange(selfChange: Boolean, uri: Uri?) {<br>        super.onChange(selfChange, uri)<br>        if (uri != null) {<br>          // Data change detected.<br>         // Here also we are using uriMatcher, you need to define first, like we defined in contentProvider&#39;s part.<br>          when (uriMatcher.match(uri)) {<br>            MYTABLE -&gt; {<br>              getAllContacts()<br>            }<br>            MYTABLE_ID -&gt; {<br>              getChangedContact(ContentUris.parseId(uri).toString())<br>            }<br>          }<br>        }<br>      }<br>    }<br><br>    // Register a ContentObserver to listen for changes <br>    contentResolver.registerContentObserver(<br>      CONTENT_URI,<br>      true,<br>      contentObserver<br>     )<br><br>}</pre><p>The provided code initializes a ContentObserver to monitor changes in the content provider&#39;s data and take appropriate actions based on the URI of the changed data.</p><ol><li><strong>Initialize ContentObserver</strong>:</li></ol><ul><li>contentObserver = object : ContentObserver(Handler()) { ... }: Creates a ContentObserver instance with a Handler to handle callbacks.</li></ul><p><strong>2. Override onChange Method</strong>:</p><ul><li>override fun onChange(selfChange: Boolean, uri: Uri?) { ... }: The onChange method is overridden to handle data changes. If a URI is provided:</li><li>when (uriMatcher.match(uri)) { ... }: Checks which URI was changed:</li><li>MYTABLE -&gt; getAllContacts(): If the change is for the entire table, it calls getAllContacts() to fetch all contacts.</li><li>MYTABLE_ID -&gt; getChangedContact(ContentUris.parseId(uri).toString()): If the change is for a specific record, it calls getChangedContact with the ID of the changed record.</li></ul><p><strong>3. Register ContentObserver</strong>:</p><ul><li>contentResolver.registerContentObserver(CONTENT_URI, true, contentObserver): Registers the ContentObserver to listen for changes to the specified CONTENT_URI and all its descendants (true).</li></ul><p>In this article, we’ve explored the roles of ContentProvider and ContentResolver in Android development, learned about Content URIs, and implemented a ContentProvider with SQLite in Kotlin. By understanding these concepts, you can efficiently manage and share data within and across your applications. You can find the full example in this GitHub repository. In this example, we accessed ContentProvider&#39;s data within the same app&#39;s components. You can try writing ContentResolver code in a different app to access data from the ContentProvider. Make sure both apps implementing ContentProvider and ContentResolver are installed on your device.</p><p><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts/tree/master/content-provider">Epic-Android-Concepts/content-provider at master · Vishwajith-Shettigar/Epic-Android-Concepts</a></p><p>Thank you for reading! I hope you found this guide helpful. Stay tuned for more articles in the Epic Android Concepts series. If you have any questions or feedback, feel free to leave a comment below. I would love to hear from you so that I can improve my explanations in future articles in the Epic Android Concepts series.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f31952062649" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Kotlin Coroutines: launch vs withContext.]]></title>
            <link>https://medium.com/@zekromvishwa56789/understanding-kotlin-coroutines-launch-vs-withcontext-aa9e91111456?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9e91111456</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutinescope]]></category>
            <category><![CDATA[coroutine]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 15:30:40 GMT</pubDate>
            <atom:updated>2024-11-17T15:29:46.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cNFIb068Gnc9Oeqv" /></figure><h3>What are Coroutines?</h3><p>Coroutines in Kotlin are a design pattern for handling asynchronous tasks. They enable you to write non-blocking, asynchronous code that is simple and readable, making concurrency management more intuitive.</p><h3>Coroutine Builders: launch and withContext</h3><h3>launch</h3><p>The launch function starts a new coroutine. It&#39;s typically used for tasks that don&#39;t return a result and where you don&#39;t need to wait for the task to complete.</p><ul><li><strong>Purpose</strong>: Launch a new coroutine.</li><li><strong>Return Type</strong>: Job - can be used to manage the coroutine.</li><li><strong>Use Case</strong>: Fire-and-forget tasks.</li><li><strong>Behavior</strong>: Runs concurrently with the rest of the code; non-blocking.</li></ul><h3>withContext</h3><p>The withContext function switches the context of the current coroutine. It&#39;s used for tasks where you need to get a result or when you need to switch to a different dispatcher temporarily.</p><ul><li><strong>Purpose</strong>: Change the coroutine context.</li><li><strong>Return Type</strong>: Result of the block of code.</li><li><strong>Use Case</strong>: Executing a block of code in a different context and getting the result.</li><li><strong>Behavior</strong>: Suspends the coroutine until the block completes; doesn’t block the thread.</li></ul><h3>Practical Examples</h3><p>Let’s consider a scenario where you want to fetch data from a network on a background thread and then update the UI on the main thread.</p><pre>import kotlinx.coroutines.*<br><br>fun main() = runBlocking {<br>    launch(Dispatchers.IO) {<br>        val data = fetchDataFromNetwork()<br>        withContext(Dispatchers.Main) {<br>            updateUI(data)<br>        }<br>    }<br>}<br><br>suspend fun fetchDataFromNetwork(): String {<br>    delay(1000) // Simulate network delay<br>    return &quot;Data from network&quot;<br>}<br><br>fun updateUI(data: String) {<br>    println(&quot;Updating UI with: $data&quot;)<br>}</pre><p>In this example:</p><ul><li>The launch block starts a new coroutine on the IO dispatcher for network operations.</li><li>Inside launch, withContext is used to switch to the Main dispatcher to update the UI.</li></ul><h3>Key Differences</h3><ol><li><strong>Execution Context</strong>:</li></ol><ul><li>launch(Dispatchers.Main): Runs the coroutine concurrently on the main thread.</li><li>withContext(Dispatchers.Main): Switches the coroutine to the main thread temporarily.</li></ul><p><strong>2. Result Handling</strong>:</p><ul><li>launch: Returns a Job and doesn&#39;t provide a direct result.</li><li>withContext: Returns the result of the block executed within the specified context.</li></ul><p><strong>3. Blocking Behavior</strong>:</p><ul><li>launch: Non-blocking for the thread; the coroutine runs concurrently.</li><li>withContext: Blocks the coroutine (not the thread) until the block completes.</li></ul><p><strong>4. Use Cases</strong>:</p><ul><li>Use launch for starting independent tasks where the result is not immediately needed.</li><li>Use withContext for executing a specific block of code in a different context, especially for tasks like network requests or file I/O where you need to switch back to the original context after completion.</li></ul><blockquote><em>Thanks for reading, happy coding !!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9e91111456" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up Protocol Buffers in an Android Project]]></title>
            <link>https://medium.com/@zekromvishwa56789/setting-up-protocol-buffers-in-an-android-project-8f7bad31981f?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7bad31981f</guid>
            <category><![CDATA[data-serialization]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[proto]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Mon, 20 May 2024 06:04:19 GMT</pubDate>
            <atom:updated>2024-12-08T06:30:20.048Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>from <a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts"><strong>Epic Android Concepts</strong></a> series.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*hMoE4yxz32IxoWMw6gsWhw.png" /></figure><p>Protocol Buffers (Protobuf) is a language-neutral, platform-neutral extensible mechanism for serializing structured data. This guide will walk you through setting up Protobuf in an Android project using a separate model module.</p><h3>Prerequisites</h3><p>Ensure you have the following installed:</p><ul><li>Android Studio</li><li>Basic knowledge of Gradle and Android project structure</li></ul><blockquote>Note: In this article, I demonstrate how to create Protobuf files in a separate module called model. If you prefer not to create a separate module, you can place the Protobuf files and required dependencies directly in the app module&#39;s build.gradle file. To do this, simply skip Step 1 and add the Protobuf dependencies and configurations to the app module&#39;s build.gradle file wherever they are specified for the model module. Below, I’ve included a link to a GitHub repository where the Protobuf setup is done directly in the app module.</blockquote><h3>Step 1: Create a Model Module</h3><ol><li>Open your Android project in Android Studio.</li><li>Create a new module:</li></ol><ul><li>Go to File &gt; New &gt; New Module.</li><li>Select Java or Kotlin Library and click Next.</li><li>Name the module model and click Finish.</li></ul><p>3. Include the model module in your project:</p><p>Open settings.gradle and add the following line:</p><pre>include &#39;:app&#39;, &#39;:model&#39;</pre><p>4. Add the model module as a dependency to your app module:</p><p>Open app/build.gradle and add the following line inside the dependencies block:</p><pre>dependencies {<br>    implementation project(&#39;:model&#39;)<br>    // Other dependencies...<br>}</pre><h3>Step 2: Configure Project-Level Gradle</h3><p>Open the build.gradle file at the project level and add the following configuration:</p><pre>buildscript {<br>    ext.kotlin_version = &#39;1.8.0&#39;<br>    ext.protobufVersion = &#39;0.8.15&#39;<br><br>    repositories {<br>        google()<br>        jcenter()<br>    }<br>    dependencies {<br>        classpath &#39;com.android.tools.build:gradle:4.1.3&#39;<br>        classpath &quot;org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version&quot;<br>        classpath &quot;com.google.protobuf:protobuf-gradle-plugin:$protobufVersion&quot;<br>    }<br>}<br><br>allprojects {<br>    repositories {<br>        google()<br>        jcenter()<br>    }<br>}</pre><p><em>If you get error</em> like below</p><pre>Build was configured to prefer settings repositories over project repositories but repository &#39;Google&#39; was added by build file &#39;build.gradle&#39;</pre><p>Open settings.gradle, and make below changes</p><pre>pluginManagement {<br>    repositories {<br>        google()<br>        gradlePluginPortal()<br>        mavenCentral()<br><br>    }<br>}<br>dependencyResolutionManagement {<br>  // repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)<br>    repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)<br>    repositories {<br>        google()<br>        mavenCentral()<br>    }<br>}<br>rootProject.name = &quot;your project name&quot;<br>include &#39;:app&#39;<br>include &#39;:model&#39;</pre><h3>Step 3: Configure Model Module Gradle</h3><p>Open the build.gradle file in the model module and add the following configuration:</p><pre>apply plugin: &#39;java-library&#39;<br>apply plugin: &#39;com.google.protobuf&#39;<br><br>protobuf {<br>    protoc {<br>        artifact = &quot;com.google.protobuf:protoc:3.8.0&quot;<br>    }<br>    generateProtoTasks {<br>        all().each { task -&gt;<br>            task.builtins {<br>                java {<br>                    option &#39;lite&#39;<br>                }<br>            }<br>        }<br>    }<br>}<br><br>dependencies {<br>    implementation &#39;com.google.protobuf:protobuf-javalite:4.26.1&#39;<br>}<br><br>sourceSets {<br>    main {<br>        java {<br>            srcDir &#39;build/generated/source/proto/main/java&#39;<br>        }<br>        proto {<br>            srcDir &#39;src/main/proto&#39;<br>        }<br>    }<br>}<br><br>java {<br>    sourceCompatibility = JavaVersion.VERSION_1_8<br>    targetCompatibility = JavaVersion.VERSION_1_8<br>}<br><br>tasks.withType(ProcessResources) {<br>    duplicatesStrategy = DuplicatesStrategy.EXCLUDE<br>}</pre><ul><li>srcDir &#39;build/generated/source/proto/main/java&#39;: Includes the directory where the Protobuf plugin outputs the generated Java code. This ensures that the generated Java files are part of the project&#39;s source code and are compiled and included in the final build.</li><li>srcDir &#39;src/main/proto&#39;: Specifies the location of your .proto files. This tells the Protobuf plugin where to find the Protobuf definitions that need to be compiled into Java code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*HHN7EiQDeA1FTTWw3u5FjQ.png" /></figure><h3>Step 4: Configure App Module Gradle</h3><p>Open the build.gradle file in the app module and add the following dependency:</p><pre>    dependencies {<br>      implementation(&quot;com.google.protobuf:protobuf-javalite:4.26.1&quot;) {<br>        exclude module: &#39;protobuf-java&#39;<br>      }<br>    // Other dependencies...<br>}</pre><h3>Step 5: Create Protobuf Definition</h3><ol><li>Create the directory for your Protobuf files:</li></ol><ul><li>In the model module, navigate to src/main.</li><li>Create a new directory named proto.</li></ul><p>2. Create the Protobuf file:</p><ul><li>Inside proto, create a file named post.proto with the following content:</li></ul><pre>syntax = &quot;proto3&quot;;<br><br>package model;<br><br>option java_package = &quot;com.example.model&quot;;<br>option java_multiple_files = true;<br><br>message Post {<br>  string name = 1;<br>  int32 id = 2;<br>  string email = 3;<br>}</pre><ol><li>option java_package = &quot;com.example.model&quot;</li></ol><p>This option specifies the Java package name that will be used for the generated Java classes. In the provided line (option java_package = &quot;com.example.model&quot;;), the generated Java classes will be placed in the com.example.model package. Full path looks like this, build/generated/source/proto/main/java/<strong>com/example/model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*XlCnq_LO3AJqC6aCHtQmEQ.png" /></figure><p>2. option java_multiple_files = true</p><p>This option determines whether each message in the .proto file will be output to a separate Java file or if multiple messages will be combined into a single Java file. If java_multiple_files is set to true, each message in the .proto file will result in a separate Java file in the specified Java package.</p><h3>Step 5: Generate Protobuf Files</h3><ol><li>Clean and rebuild the project:</li></ol><ul><li>Go to Build &gt; Clean Project.</li><li>Go to Build &gt; Rebuild Project.</li></ul><ol><li>Ensure the Protobuf files are generated:</li></ol><p>The generated Java files should be in model/build/generated/source/proto/main/java/com/example/model.</p><h3>Step 6: Use Generated Protobuf Files in App Module</h3><ol><li>Import the generated Protobuf classes in your app module:</li></ol><pre>import com.example.model.Post;</pre><p>2. Use the Post class in your app code:</p><pre>Post post = Post.newBuilder()<br>                .setName(&quot;John Doe&quot;)<br>                .setId(1)<br>                .setEmail(&quot;john.doe@example.com&quot;)<br>                .build();</pre><pre>package com.example.setupprotobuf<br><br>import androidx.appcompat.app.AppCompatActivity<br>import android.os.Bundle<br>import android.util.Log<br>import com.example.model.Post<br><br>class MainActivity : AppCompatActivity() {<br>  override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br>    setContentView(R.layout.activity_main)<br>    val post = Post.newBuilder().apply {<br>      this.id = 1<br>      this.name = &quot;Shinchan&quot;<br>      this.email = &quot;welcomebackhome@nohara.com&quot;<br>    }.build()<br><br>    Log.d(&quot;protobuf&quot;,post.toString())<br><br>  }<br>}</pre><p>Below are links for example Github repo 🚀.</p><ol><li><a href="https://github.com/Vishwajith-Shettigar/Setup-Protobuf-in-an-Android-project"><em>Setting up protobuf in a separate module( eg :model module) 🔗</em></a></li><li><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts/tree/master/protobuf/src/main"><em>Setting up protobuf in an app module.</em></a><em> </em><a href="https://github.com/Vishwajith-Shettigar/Epic-Android-Concepts/tree/master/protobuf/src/main"><em>🔗</em></a></li></ol><h3>Conclusion</h3><p>By following these steps, you’ve successfully integrated Protobuf into your Android project using a separate model module. This setup allows you to define your data structures in a .proto file and use the generated classes across your app module efficiently. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7bad31981f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dagger 2: Custom Scopes and Subcomponents in Android]]></title>
            <link>https://medium.com/@zekromvishwa56789/understanding-dagger-2-custom-scopes-and-subcomponents-in-android-1af073a3283e?source=rss-32a06404867c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1af073a3283e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dagger]]></category>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Vishwajith Shettigar]]></dc:creator>
            <pubDate>Thu, 16 May 2024 03:52:43 GMT</pubDate>
            <atom:updated>2024-05-16T04:39:21.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*14Br87_vs6KJHkZo.png" /></figure><blockquote>Note: This blog only talks about custom scopes and subcomponents, so readers better know Dagger basics.</blockquote><p>In this blog post, we’ll dive deep into Dagger 2, an essential dependency injection framework for Android, and explore how to create and use custom scopes, subcomponents, and properly manage lifetimes of dependencies. We will walk through an example project to illustrate these concepts in detail.</p><h3>Project Overview</h3><p>Our example project will include:</p><ol><li>Application-wide dependencies</li><li>Activity-specific dependencies</li><li>Fragment-specific dependencies</li></ol><p>To manage these dependencies effectively, we will define custom scopes and use subcomponents.</p><h3>Custom Scopes</h3><p>Custom scopes help manage the lifespan of dependencies. Let’s define scopes for activities and fragments.</p><blockquote>Defining Custom Scopes</blockquote><pre>@Scope<br>@Retention(AnnotationRetention.RUNTIME)<br>annotation class ActivityScope<br><br>@Scope<br>@Retention(AnnotationRetention.RUNTIME)<br>annotation class FragmentScope</pre><h3>Modules and Components</h3><p>We’ll define three modules and three components to manage dependencies:</p><ol><li>AppModule for application-wide dependencies</li><li>ActivityModule for activity-specific dependencies</li><li>FragmentModule for fragment-specific dependencies</li></ol><blockquote>AppModule</blockquote><pre>@Module<br>class AppModule(private val context: Context) {<br>    @Provides<br>    @Singleton<br>    fun provideContext(): Context {<br>        return context<br>    }<br>}</pre><p>In AppModule, we provide the application context, which can be used across the entire application.</p><blockquote>ActivityModule</blockquote><pre>@Module<br>class ActivityModule(private val activity: AppCompatActivity) {<br>    @Provides<br>    @ActivityScope<br>    fun provideActivity(): AppCompatActivity = activity<br>}</pre><p>In ActivityModule, we provide the activity instance, which will be scoped to the activity lifecycle.</p><blockquote>FragmentModule</blockquote><pre>@Module<br>class FragmentModule(private val fragment: Fragment) {<br>    @Provides<br>    @FragmentScope<br>    fun provideFragment(): Fragment = fragment<br>}</pre><p>In FragmentModule, we provide the fragment instance, which will be scoped to the fragment lifecycle.</p><h3>Components and Subcomponents</h3><blockquote>AppComponent</blockquote><p>AppComponent is the root component that provides application-wide dependencies.</p><pre>@Singleton<br>@Component(modules = [AppModule::class])<br>interface AppComponent {<br>    fun inject(application: MyApplication)<br>    fun activityComponent(activityModule: ActivityModule): ActivityComponent<br>}</pre><blockquote>ActivityComponent</blockquote><p>ActivityComponent is a subcomponent of AppComponent and provides activity-specific dependencies.</p><pre>@ActivityScope<br>@Subcomponent(modules = [ActivityModule::class])<br>interface ActivityComponent {<br>    fun inject(activity: HomeActivity)<br>    fun fragmentComponent(fragmentModule: FragmentModule): FragmentComponent<br>}</pre><blockquote>FragmentComponent</blockquote><p>FragmentComponent is a subcomponent of ActivityComponent and provides fragment-specific dependencies.</p><pre>@FragmentScope<br>@Subcomponent(modules = [FragmentModule::class])<br>interface FragmentComponent {<br>    fun inject(fragment: HomeFragment)<br>}</pre><h3>Application Class</h3><p>In the Application class, we initialize the AppComponent.</p><pre>class MyApplication : Application() {<br><br>    lateinit var appComponent: AppComponent<br><br>    override fun onCreate() {<br>        super.onCreate()<br>        appComponent = DaggerAppComponent.builder()<br>            .appModule(AppModule(this))<br>            .build()<br>    }<br>}</pre><h3>Activity Setup</h3><p>In HomeActivity, we create the ActivityComponent from AppComponent.</p><pre>@ActivityScope<br>class HomeActivity : AppCompatActivity() {<br><br>    lateinit var activityComponent: ActivityComponent<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        activityComponent = (application as MyApplication).appComponent<br>            .activityComponent(ActivityModule(this))<br>        activityComponent.inject(this)<br>    }<br>}</pre><h3>Fragment Setup</h3><p>In HomeFragment, we create the FragmentComponent from ActivityComponent.</p><pre>@FragmentScope<br>class HomeFragment : Fragment() {<br><br>    lateinit var fragmentComponent: FragmentComponent<br><br>    override fun onAttach(context: Context) {<br>        super.onAttach(context)<br>        fragmentComponent = (activity as HomeActivity).activityComponent<br>            .fragmentComponent(FragmentModule(this))<br>        fragmentComponent.inject(this)<br>    }<br>}</pre><h3>Accessing Dependencies Across Scopes</h3><p>One of the main benefits of using subcomponents and custom scopes is the ability to access dependencies across different scopes. For example:</p><ul><li>Application-wide dependencies: These are available throughout the entire app. For instance, you might need access to the application context or a singleton service class</li></ul><pre>class MySingletonService @Inject constructor(private val context: Context) {<br>    // Singleton service code<br>}</pre><ul><li>Activity-specific dependencies: These are available within a specific activity. For example, you might have a presenter or view model that should only live as long as the activity.</li></ul><pre>class HomeActivity : AppCompatActivity() {<br><br>    @Inject<br>    lateinit var mySingletonService: MySingletonService // Application scoped dependency<br><br>    @Inject<br>    lateinit var activityPresenter: ActivityPresenter // Activity scoped dependency<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        activityComponent = (application as MyApplication).appComponent<br>            .activityComponent(ActivityModule(this))<br>        activityComponent.inject(this)<br><br>        // Use mySingletonService and activityPresenter<br>    }<br>}</pre><ul><li>Fragment-specific dependencies: These are available within a specific fragment. For example, you might have a fragment presenter or view model that should only live as long as the fragment.</li></ul><pre>class HomeFragment : Fragment() {<br><br>    @Inject<br>    lateinit var mySingletonService: MySingletonService // Application scoped dependency<br><br>    @Inject<br>    lateinit var activityPresenter: ActivityPresenter // Activity scoped dependency<br><br>    @Inject<br>    lateinit var fragmentPresenter: FragmentPresenter // Fragment scoped dependency<br><br>    override fun onAttach(context: Context) {<br>        super.onAttach(context)<br>        fragmentComponent = (activity as HomeActivity).activityComponent<br>            .fragmentComponent(FragmentModule(this))<br>        fragmentComponent.inject(this)<br><br>        // Use mySingletonService, activityPresenter, and fragmentPresenter<br>    }<br>}</pre><p>In this example, HomeFragment can access dependencies from the application scope (mySingletonService), activity scope (activityPresenter), and its own fragment scope (fragmentPresenter). This demonstrates the flexibility and power of using custom scopes and subcomponents in Dagger 2.</p><h3>Understanding the Lifespans and Scopes</h3><ol><li>@Singleton:</li></ol><ul><li>Lifespan: Lives as long as the application is alive.</li><li>Usage: For application-wide dependencies such as Context.</li></ul><p>2. @ActivityScope:</p><ul><li>Lifespan: Lives as long as the activity is alive.</li><li>Usage: For dependencies that should exist only within an activity’s lifecycle, such as activity-specific presenters or view models.</li></ul><p>3. @FragmentScope:</p><ul><li>Lifespan: Lives as long as the fragment is alive.</li><li>Usage: For dependencies that should exist only within a fragment’s lifecycle, such as fragment-specific presenters or view models.</li></ul><h3>How Subcomponents Work</h3><p>Subcomponents allow for a hierarchical structure where dependencies can be scoped to specific parts of your application. Here’s how they interact:</p><ul><li>AppComponent: Provides dependencies that live as long as the application.</li><li>ActivityComponent: A subcomponent of AppComponent that provides dependencies specific to an activity&#39;s lifecycle.</li><li>FragmentComponent: A subcomponent of ActivityComponent that provides dependencies specific to a fragment&#39;s lifecycle.</li></ul><p>This hierarchical structure ensures that dependencies are appropriately scoped and managed, preventing memory leaks and ensuring efficient resource usage.</p><h3>Conclusion</h3><p>Using Dagger 2 with custom scopes and subcomponents allows for precise control over the lifetimes of dependencies. This ensures efficient resource management and reduces the risk of memory leaks in Android applications. By following the outlined structure, you can create a modular and maintainable dependency injection setup in your projects.</p><p>By understanding and implementing these concepts, you can leverage the full power of Dagger 2 to create robust, scalable, and maintainable Android applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1af073a3283e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>