<?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 Devarsh Bhalara on Medium]]></title>
        <description><![CDATA[Stories by Devarsh Bhalara on Medium]]></description>
        <link>https://medium.com/@devarshbhalara3072?source=rss-e81dd0b64bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cFvgzAwczC0OnOSC</url>
            <title>Stories by Devarsh Bhalara on Medium</title>
            <link>https://medium.com/@devarshbhalara3072?source=rss-e81dd0b64bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 00:16:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devarshbhalara3072/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[Handler vs Job in Android (Kotlin):]]></title>
            <link>https://medium.com/@devarshbhalara3072/handler-vs-job-in-android-kotlin-93c9b4cd583e?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c9b4cd583e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[handler]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[coroutine-job]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 16:54:58 GMT</pubDate>
            <atom:updated>2025-11-11T16:54:58.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*el8jxEkHDbOBw01diLUnJQ.png" /></figure><p>When working with background tasks in Android, two common options often come up: <strong>Handler</strong> and <strong>Job</strong>.<br> Both help manage asynchronous or delayed work, but they serve different purposes and belong to different generations of Android concurrency APIs.</p><p><strong>1. The Legacy: Handler</strong></p><p>The <strong>Handler</strong> has been part of Android since the early days.<br> It works with a <strong>Looper</strong> and a <strong>MessageQueue</strong> to post tasks (Runnable or Message) to a specific thread, often the <strong>main thread</strong>.</p><p>Example:</p><pre>val handler = Handler(Looper.getMainLooper())<br><br>handler.postDelayed({<br>    Log.d(&quot;HandlerExample&quot;, &quot;Executed after delay!&quot;)<br>    // you can do some UI work or anything<br>}, 2000)</pre><p>✅ <strong>Pros:</strong></p><ul><li>Simple for small, delayed tasks.</li><li>Updating UI from background threads</li><li>Integrated with the Android Looper/MessageQueue system.</li></ul><p>❌ <strong>Cons:</strong></p><ul><li>Not lifecycle-aware</li><li>Can lead to memory leaks if not removed properly (handler.removeCallbacks() needed).</li><li>Hard to cancel or chain multiple async operations.</li><li>Doesn’t play well with structured concurrency.</li></ul><p><strong>2. What is a Job?</strong></p><p>With Kotlin Coroutines, <strong>Job</strong> represents a <strong>cancellable unit of work</strong>. <br>Every coroutine runs inside a Jobit can be started, cancelled, or awaited, and integrates beautifully with Android lifecycle components.</p><p>Example :</p><pre>val job = CoroutineScope(Dispatchers.Main).launch {<br>    delay(2000)<br>    Log.d(&quot;JobExample&quot;, &quot;Executed after delay!&quot;)<br>}<br><br>// Cancel if needed<br>job.cancel()</pre><p>✅ <strong>Pros:</strong></p><ul><li>Lifecycle-aware (when used with lifecycleScope or viewModelScope)</li><li>Structured concurrency (child jobs are automatically cancelled when parents are)</li><li>Clear cancellation handling</li><li>Integrates well with suspend functions and async workflows</li></ul><p>❌ <strong>Cons:</strong></p><ul><li>Launching coroutines in GlobalScope or unmanaged scopes can cause memory leaks or unintended background work.</li><li>If you don’t use lifecycleScope or viewModelScope, coroutines won’t automatically cancel with the UI lifecycle.</li></ul><p><strong>Conclusion</strong></p><ul><li>Use <strong>Handler</strong> only for <strong>simple, short-lived, UI-thread tasks</strong>.</li><li>Prefer <strong>Job (Coroutines)</strong> for <strong>modern, lifecycle-aware async work</strong> — especially in Jetpack Compose or MVVM apps.</li><li>If you’re still using Handler extensively, it might be time to migrate — CoroutineScope + Job offers better readability, safety, and control.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c9b4cd583e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Open Browser in Android & iOS using Jetpack Compose Multiplatform (CMP)]]></title>
            <link>https://medium.com/@devarshbhalara3072/how-to-open-browser-in-android-ios-using-jetpack-compose-multiplatform-cmp-fb1a68a27e7f?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb1a68a27e7f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 15:43:30 GMT</pubDate>
            <atom:updated>2025-09-12T15:43:30.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GHxQ6C8XgN_E7F6BGLeew.png" /></figure><p>Recently, I was learning CMP by <strong>converting my Jetpack Compose Android app to Compose Multiplatform (CMP)</strong> to target both Android and iOS using a single codebase. While most of the UI and business logic converted smoothly, I got stuck when it came to implementing platform-specific actions, like opening the default browser.</p><p>After some research and experimenting, I found a clean and simple solution that leverages Kotlin Multiplatform’s expect/actual mechanism. In this article, I’ll walk you through the exact steps to open a browser in both Android and iOS using CMP — keeping your shared code clean while handling platform-specific needs.</p><p><strong>Step 1: Define expect Functions in Shared Module (commonMain) :</strong></p><blockquote>You’ll define expect functions in your commonMain source set, then provide their actual platform-specific implementations in corresponding files within your androidMain and iosMain (or other platform) source sets.</blockquote><pre>expect fun openBrowser(url: String, completionHandler: (Boolean) -&gt; Unit = {})</pre><p>This acts as a contract — each platform must provide its own actual implementation.</p><p>The url parameter is used to pass the URL that we want to open in the browser.</p><p>The completionHandler in your openBrowser function is a callback that gets executed after iOS attempts to open the URL.<br> It takes a single Boolean argument:</p><ul><li>true: if the URL was successfully opened by an application.</li><li>false: if the URL could not be opened (e.g., no app is registered to handle the URL scheme).</li></ul><p><strong>Step 2: Android Implementation(androidMain) :</strong></p><pre>actual fun openBrowser(url: String, completionHandler: (Boolean) -&gt; Unit) {<br>    try {<br>        val intent = Intent(<br>            Intent.ACTION_VIEW, url.toUri()<br>        ).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }<br>        context.startActivity(intent)<br>    } catch (e: Exception) {<br>        println(e.printStackTrace())<br>        completionHandler(false)<br>    }<br>}</pre><p>This Android function opens a URL using an Intent. It sets a flag (FLAG_ACTIVITY_NEW_TASK) to ensure it can be called from outside an Activity. <br>If an error occurs (e.g., no browser installed), it prints the error and calls the completionHandler with false.</p><p><strong>Step 3: iOS Implementation (iosMain) :</strong></p><pre>actual fun openBrowser(url: String, completionHandler: (Boolean) -&gt; Unit) {<br>    NSURL.URLWithString(url)?.let {<br>        UIApplication.sharedApplication.openURL(<br>            url = it,<br>            options = emptyMap&lt;Any?, Any&gt;(),<br>            completionHandler = completionHandler<br>        )<br>    }<br>}</pre><p>This iOS function attempts to open a URL. It converts the string url into an NSURL object. <br>If successful, it calls UIApplication.sharedApplication.openURL to ask the system to open it. The completionHandler is a callback that iOS executes after trying to open the URL, indicating success or failure.</p><p><strong>Step 4: Open a web browser using </strong><strong>openBrowser() :</strong></p><pre>Button(<br>        onClick = {<br>            openBrowser(urlToOpen) { success -&gt;<br>                if (success) {<br>                    println(&quot;Successfully opened $urlToOpen&quot;)<br>                    // You can add any other logic here on successful opening<br>                } else {<br>                    println(&quot;Failed to open $urlToOpen&quot;)<br>                    // You can add error handling or user feedback here<br>                }<br>            }<br>        },<br>        modifier = modifier<br>    ) {<br>        Text(text = buttonText)<br>    }</pre><p>Thanks to our shared openBrowser() function, opening a URL is straightforward, just call it from your common code with the target URL, and it will work seamlessly across Android and iOS.</p><p>The completion handler in the code while calling openBrowser()is optional; you can omit it if you prefer. Just write openBrowser(url) to open the browser.</p><h4><strong>Conclusion :</strong></h4><p>During my journey of converting a Jetpack Compose app into a CMP app, handling platform-specific features was a key challenge. This simple and elegant solution allowed me to keep my shared Compose UI code clean and reusable, while implementing platform-specific browser functionality.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb1a68a27e7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update RecyclerView Items Without notifyDataSetChanged() or notifyItemChanged()]]></title>
            <link>https://medium.com/@devarshbhalara3072/update-recyclerview-items-without-notifydatasetchanged-or-notifyitemchanged-d6c19213cd65?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c19213cd65</guid>
            <category><![CDATA[data-binding]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[recyclerview-in-android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 15:16:05 GMT</pubDate>
            <atom:updated>2025-06-02T15:16:05.687Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*el8jxEkHDbOBw01diLUnJQ.png" /></figure><p>Updating specific views in a RecyclerView without refreshing the whole list is a common requirement, especially when you&#39;re working with things like item selection, toggling favourites, or animating state changes.</p><p>Instead of calling the adapter.notifyDataSetChanged() (which refreshes all items unnecessarily), we can use <strong>Android Data Binding</strong> and <strong>observable data models</strong> to update only the affected view.</p><h4>In this post, you’ll learn how to:</h4><ul><li>Use BaseObservable to build a reactive data model for UI updates</li><li>Bind view properties directly using XML Data Binding</li><li>Handle item click events to update the selection state <strong>without refreshing the entire RecyclerView</strong></li></ul><h3>Example:</h3><p>Let’s say you’re building a simple list of images. You want the user to select an item visually. Only one item should be selected at a time, and the selected item should have a special background like round corners.</p><p>Make sure to enable databinding in build.gradle file :</p><pre>buildFeatures {<br>  dataBinding = true<br>}</pre><h4>Step 1: Create an Observable Data Model</h4><pre>data class ImageListModel(<br>    val image: Int,<br>    private var _isSelected: Boolean = false,<br>): BaseObservable() {<br><br>    @get:Bindable<br>    var isSelected: Boolean<br>        get() = _isSelected<br>        set(value) {<br>            if (_isSelected != value) {<br>                _isSelected = value<br>                notifyPropertyChanged(BR.selected)<br>            }<br>        }<br><br>}</pre><p>We’ll use BaseObservable and @Bindable to allow the UI to observe property changes.</p><blockquote><strong>Note:</strong> If you get an error in importing BR, then just write import yourpackname.BR like import `com.example.demo.BR` .</blockquote><h4>🧩 Step 2: Layout XML With Data Binding</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;layout&gt;<br><br>    &lt;data&gt;<br>        &lt;import type=&quot;android.view.View&quot; /&gt;<br>        &lt;variable<br>            name=&quot;data&quot;<br>            type=&quot;com.example.demo.ImageListModel&quot; /&gt;<br>    &lt;/data&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>        xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_margin=&quot;10dp&quot;&gt;<br><br>        &lt;ImageView<br>            android:id=&quot;@+id/ivEyePattern&quot;<br>            android:layout_width=&quot;78dp&quot;<br>            android:layout_height=&quot;78dp&quot;<br>            android:background=&quot;@{ data.isSelected ? @drawable/bg_edit_qr_selected_option : @drawable/bg_edit_qr_default_option }&quot;<br>            android:padding=&quot;16dp&quot;<br>            app:drawableResource=&quot;@{ data.image }&quot;<br>            app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintHorizontal_bias=&quot;0.5&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            app:layout_constraintVertical_bias=&quot;0.5&quot; /&gt;<br><br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br>&lt;/layout&gt;</pre><p>bg_edit_qr_default_option.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:shape=&quot;rectangle&quot;&gt;<br><br>    &lt;stroke<br>        android:width=&quot;2dp&quot;<br>        android:color=&quot;#1F9D9D9D&quot; /&gt;<br>    &lt;corners android:radius=&quot;14dp&quot; /&gt;<br><br>&lt;/shape&gt;</pre><p>bg_edit_qr_selected_option.xml:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:shape=&quot;rectangle&quot;&gt;<br><br>    &lt;stroke<br>        android:width=&quot;2dp&quot;<br>        android:color=&quot;#0046FF&quot; /&gt;<br>    &lt;corners android:radius=&quot;14dp&quot; /&gt;<br><br>&lt;/shape&gt;</pre><p><strong>Note:</strong> app:drawableResource is a custom @BindingAdapter that I created to set an image resource on an ImageView using a resource ID via data binding. If you don’t know this custom property, then refer to my blog <a href="https://medium.com/@devarshbhalara3072/binding-adapter-in-android-kotlin-using-bindingadapter-a-powerful-tool-for-custom-bindings-or-817343db02d9">here</a> or else you can skip this part for now and set your image via recycler view adapter directly.</p><h4>🛠 Step 3: RecyclerView Adapter</h4><pre>class ImageListAdapter(<br>    private val items: List&lt;ImageListModel&gt;,<br>    private val onItemClick: (ImageListModel) -&gt; Unit<br>) : RecyclerView.Adapter&lt;ImageListAdapter.ImageViewHolder&gt;() {<br><br>    inner class ImageViewHolder(val binding: ItemImageBinding) :<br>        RecyclerView.ViewHolder(binding.root) {<br>        fun bind(data: ImageListModel) {<br>            binding.data = data<br><br>            binding.root.setOnClickListener {<br>                items.forEach { it.isSelected = false }<br>                data.isSelected = true<br>                onItemClick(data)<br>            }<br>        }<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder {<br>        return ImageViewHolder(<br>            ItemImageBinding.inflate(<br>                LayoutInflater.from(parent.context),<br>                parent,<br>                false<br>            )<br>        )<br>    }<br><br>    override fun onBindViewHolder(holder: ImageViewHolder, position: Int) {<br>        holder.bind(items[position])<br>    }<br><br>    override fun getItemCount(): Int = items.size<br>}<br><br>//in Activity, call this function at onCreate()<br><br>private fun setupRecyclerView() {<br>    val list = listOf(<br>        ImageListModel(R.drawable.image_1, _selected = true),<br>        ImageListModel(R.drawable.image_2),<br>         .........<br>    )<br><br>    val adapter = ImageListAdapter(list) { selectedModel -&gt;<br>        // handle your click here<br>    }<br><br>    binding.recyclerView.adapter = adapter<br>}</pre><h4>Notice that:</h4><ul><li>We don’t call notifyItemChanged() or notifyDataSetChanged().</li><li>We rely on the isSelected property triggering UI updates via notifyPropertyChanged().</li></ul><h4>Result :</h4><p>When you click an item:</p><ul><li>All items are marked isSelected = false</li><li>The clicked one is marked true</li><li>Only that view is re-bound because the binding system detects the property change</li></ul><p>No adapter refresh. No flickering. Smooth performance.</p><p>Output:</p><p><a href="https://drive.google.com/file/d/1DcANEqgB8-uz6UNy1OqKqfJ0puODSh3d/view?usp=sharing">https://drive.google.com/file/d/1DcANEqgB8uz6UNy1OqKqfJ0puODSh3d/view?usp=sharing</a></p><h4>✅ Benefits of This Approach :</h4><ul><li><strong>Efficient</strong>: Only the views that change are updated.</li><li><strong>Cleaner Code</strong>: No need to track selected position manually.</li><li><strong>MVVM Friendly</strong>: Great for modern Android architecture.</li><li><strong>Less Bug-Prone</strong>: No manual UI state sync needed.</li></ul><h4>📌 Conclusion</h4><p>If you’re still relying on adapter.notifyDataSetChanged() to update RecyclerView views, consider switching to BaseObservable and data binding for reactive UI updates. It’s a cleaner, more modern way to handle item state, especially for cases like selection, toggling, or dynamic UI changes.<br>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c19213cd65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Screen Width and Height in Compose Multiplatform (CMP) for Android & iOS]]></title>
            <link>https://medium.com/@devarshbhalara3072/how-to-get-screen-width-and-height-in-kotlin-multiplatform-kmp-for-android-ios-31d29af9be99?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d29af9be99</guid>
            <category><![CDATA[kmp]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[androi̇d]]></category>
            <category><![CDATA[compose]]></category>
            <category><![CDATA[responsive-design]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Thu, 17 Apr 2025 14:28:51 GMT</pubDate>
            <atom:updated>2025-04-17T14:42:08.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5GHxQ6C8XgN_E7F6BGLeew.png" /></figure><p>When building cross-platform applications with Compose Multiplatform (CMP), you often need to access platform-specific features, like the screen width of a device or height of device to make responsive layout. In this blog, we’ll explore how to retrieve the screen width and height in a shared module using expect/actual declarations, and provide platform-specific implementations for Android and iOS.</p><p><strong>Step 1: Define expect Functions in Shared Module (commonMain)</strong></p><pre>expect fun getScreenWidth(): Float<br><br>expect fun getScreenHeight(): Float</pre><p>This acts as a contract — each platform must provide its own actual implementation.</p><p><strong>Android Implementation(androidMain) :</strong></p><pre>actual fun getScreenWidth(): Float {<br>    val configuration = Resources.getSystem().configuration<br>    return configuration.screenWidthDp.toFloat() // Returns screen width in dp<br>}<br><br>actual fun getScreenHeight(): Float {<br>    val configuration = Resources.getSystem().configuration<br>    return configuration.screenHeightDp.toFloat()<br>}</pre><p>Resource.getSystem().configuration.screenWidthDp gives the width in Dp and Resources.getSystem().configuration.screenheightDp gives height in Dp.</p><p><strong>iOS Implementation (iosMain) :</strong></p><pre>@OptIn(ExperimentalForeignApi::class)<br>actual fun getScreenWidth(): Float {<br>    val bounds = UIScreen.mainScreen.bounds<br>    return CGRectGetWidth(bounds).toFloat()<br>}<br><br>@OptIn(ExperimentalForeignApi::class)<br>actual fun getScreenHeight(): Float {<br>    val bounds = UIScreen.mainScreen.bounds<br>    return CGRectGetHeight(bounds).toFloat()<br>}</pre><p>UIScreen.mainScreen.bounds gives us the <strong>full screen rectangle</strong> (frame) in <strong>points</strong>, which includes width and height.</p><p><strong>CGRectGetWidth(bounds) &amp; CGRectGetHeight(bounds)</strong></p><ul><li>These are <strong>interop functions</strong> provided by the Objective-C bridge (platform.CoreGraphics).</li><li>They extract the <strong>width</strong> and <strong>height</strong> values from the CGRect (rectangle) returned by bounds.</li></ul><p><strong>How to use?</strong></p><p>Let’s take an example I want to set one PagerView’s content height to 60% of any device height. How can I achieve this? By using the above functions.</p><pre>@Composable<br>fun PagerView(<br>    pagerState: PagerState,<br>    state: List&lt;Result&gt;,<br>    onClick: (String) -&gt; Unit<br>) {<br><br>    Box(modifier = Modifier.fillMaxWidth()) {<br><br>        HorizontalPager(state = pagerState) { page -&gt;<br>            Card(<br>                Modifier<br>                    .graphicsLayer {<br>                        val pageOffset = (<br>                                (pagerState.currentPage - page) + pagerState<br>                                    .currentPageOffsetFraction<br>                                ).absoluteValue<br>                        alpha = lerp(<br>                            start = 0.5f,<br>                            stop = 1f,<br>                            fraction = 1f - pageOffset.coerceIn(0f, 1f)<br>                        )<br>                    }<br>                    .clickable {<br>                        onClick(state[page].id.toString())<br>                    }<br>            ) {<br><br>                // get Screen height<br>                val screenHeight = getScreenHeight()<br>                // Use the screen height to calculate item dimensions<br>                val itemHeight = screenHeight.dp * 0.6f<br><br>                Box(<br>                    modifier = Modifier<br>                        .height(itemHeight)<br>                        .background(Color.Red)<br>                ) {<br><br>                  // your content<br><br>                }<br>            }<br>        }<br>    }<br>}</pre><p>In the above example, I have set my Box height to 60% of my device height. It will occupy only 60% of my screen.</p><p>Another example…</p><pre>@Composable<br>fun PopularMoviesItemView(item: Result, onClick: (String) -&gt; Unit) {<br><br>    // get Screen width<br>    val screenWidth = getScreenWidth()<br><br>    // Use the screen width to calculate item dimensions<br>    val itemWidth = screenWidth.dp * 0.3f<br>    val itemHeight = itemWidth * (513f / 342f) //ratio calculation<br><br>    Image(<br>        painter = rememberAsyncImagePainter(AppConstants.BASE_POSTER_PATH + item.posterPath),<br>        contentDescription = null,<br>        contentScale = ContentScale.Fit,<br>        modifier = Modifier<br>            .width(itemWidth)<br>            .height(itemHeight)<br>            .background(Color.Red)<br>            .clickable {<br>                onClick(&quot;${item.id}&quot;)<br>            }<br>    )<br><br>}</pre><p>Here in the above example Image will occupy 30% width of my device. For height, I have used the image’s height and width to calculate the ratio you can ignore that thing.</p><p><strong>Conclusion</strong></p><p>Using expect/actual, we can easily fetch screen width and height in a Compose Multiplatform project. With Android returning dimensions in dp and iOS in points, this approach keeps shared code clean and adaptable across platforms. Perfect for building responsive layouts with minimal platform-specific code.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d29af9be99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Offline Data Caching: Load JSON from Cache When Internet Is Not Available]]></title>
            <link>https://medium.com/@devarshbhalara3072/android-offline-data-caching-load-json-from-cache-when-internet-is-not-available-7dcc7187bb5e?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dcc7187bb5e</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[cache-data]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 13:03:44 GMT</pubDate>
            <atom:updated>2025-03-18T13:03:44.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGYvUebNVdu6oR4BhHca2Q.jpeg" /></figure><p>You may have seen in many apps like Instagram, and Facebook that if you open the app without the internet then it will show previously fetched data in your feed.</p><p>In Android apps, ensuring a smooth user experience is crucial even when the internet is unavailable. Caching data locally allows users to access previously fetched data.</p><p>We should also implement this mechanism into our app to ensure a smooth user experience. The logic here is that whatever last API data we fetch, we need to add it to the cache data with a separate JSON file.</p><h3>1. Read and Write JSON to Cache</h3><p>This class is used to save string to the cache directory and to retrieve string from the cache directory.</p><pre>class ReadWriteToCache {<br>    companion object {<br><br>        // Save file in cache<br>        fun saveStringToCache(context: Context, fileName: String, content: String) {<br>            val cacheDir = context.cacheDir<br>            val file = File(cacheDir, fileName)<br><br>            try {<br>                FileOutputStream(file).use { fos -&gt;<br>                    fos.write(content.toByteArray())<br>                    fos.flush()<br>                }<br>            } catch (e: Exception) {<br>                e.printStackTrace()<br>            }<br>        }<br><br>        fun readStringFromCache(context: Context, fileName: String): String {<br>            val cacheDir = context.cacheDir<br>            val file = File(cacheDir, fileName)<br><br>            val stringBuilder = StringBuilder()<br><br>            try {<br>                if(!file.exists()) {<br>                    file.createNewFile()<br>                }<br>                FileInputStream(file).use { fis -&gt;<br>                    val reader = BufferedReader(InputStreamReader(fis))<br>                    var line: String? = reader.readLine()<br>                    while (line != null) {<br>                        stringBuilder.append(line).append(&quot;\n&quot;)<br>                        line = reader.readLine()<br>                    }<br>                }<br>            } catch (e: Exception) {<br>                e.printStackTrace()<br>            }<br>            return stringBuilder.toString()<br>        }<br>    }<br>}</pre><h3>2. ViewModel to Fetch and Cache Data</h3><p>Here in this ViewModel I am making an API call to get a user list. As you can see in getUser() when the internet is available I receive data from the API and after receiving I add that JSON data to the cache with the file named “users.json”.</p><p>In getUser(), I have used the condition to check internet availability. If the internet is not available then I am reading data from the cache with the file named “users.json” (make sure you handle the case when in the cache file name as “users.json” must be there).</p><pre>class GetUserViewModel: ViewModel() {<br><br>    private var _userLiveData = MutableLiveData&lt;List&lt;Data&gt;&gt;()<br>    var userLiveData: LiveData&lt;List&lt;Data&gt;&gt; = _userLiveData<br><br>    fun getUser(context: Context, networkUtils: NetworkUtils) {<br><br>        if(networkUtils.isInternetAvailable()) {<br><br>            RetrofitInstance.getUserApi.getUsers(&quot;2&quot;).enqueue(object : Callback&lt;User?&gt; {<br>                override fun onResponse(call: Call&lt;User?&gt;, response: Response&lt;User?&gt;) {<br>                    _userLiveData.value = response.body()?.data<br>                    _userLiveData.value?.let { addDataToCache(it, context) }<br>                }<br><br>                override fun onFailure(call: Call&lt;User?&gt;, t: Throwable) {<br>                    Log.d(&quot;users&quot;, &quot;failll&quot;)<br>                }<br>            })<br>        } else {<br>            val users = readDataFromCache(context)<br>            Toast.makeText(context, &quot;Loading data from cache...&quot;, Toast.LENGTH_SHORT).show()<br>            _userLiveData.value = users<br>        }<br>    }<br><br>    private fun readDataFromCache(context: Context): List&lt;Data&gt; {<br><br>        val usersStrings = ReadWriteToCache.readStringFromCache(<br>            context,<br>            &quot;users.json&quot;<br>        )<br><br>        if(usersStrings.isNotEmpty()) {<br><br>            val type = object : TypeToken&lt;List&lt;Data&gt;&gt;() {}.type<br>            val users: List&lt;Data&gt; = Gson().fromJson(usersStrings, type)<br>            return users<br>        } else {<br>            // data not saved in cache<br>            return emptyList()<br>        }<br>    }<br><br>    private fun addDataToCache(data: List&lt;Data&gt;, context: Context) {<br>        try {<br>            val jsonTheme = Gson().toJson(data)<br>            ReadWriteToCache.saveStringToCache(<br>                context,<br>                &quot;users.json&quot;,<br>                jsonTheme<br>            )<br>        } catch (e: Exception) {<br>            Log.e(&quot;json&quot;, e.printStackTrace().toString())<br>        }<br>    }<br>}</pre><h3>3. Activity Implementation</h3><p>This is my Activity, where I just need to call viewmodel’s getUser() function and the observer will handle the rest.</p><pre>class ActivityApiCall : AppCompatActivity() {<br><br>    private lateinit var binding: ActivityApiCallBinding<br>    private val viewModel: GetUserViewModel by viewModels()<br>    private lateinit var networkUtils: NetworkUtils<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        binding = ActivityApiCallBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br>        init()<br>    }<br><br>    private fun init() {<br>        networkUtils = NetworkUtils(this)<br>        val userAdapter = UserAdapter()<br><br>        viewModel.getUser(this, networkUtils)<br><br>        viewModel.userLiveData.observe(this) {<br>            viewModel.userLiveData.value?.let { userAdapter.addItem(it) }<br>            binding.rvUsers.adapter = userAdapter<br>        }<br>    }<br>}</pre><h3>4. Network Utility Class</h3><p>This class checks for network availability and listens for connectivity changes.</p><pre>class NetworkUtils(context: Context) {<br>    <br>    private val connectivityManager =<br>        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager<br><br>    private var isNetworkAvailable = false<br><br>    init {<br>        // Initial network state check<br>        checkNetworkConnection()<br>        registerNetworkCallback()<br>    }<br><br>    private fun registerNetworkCallback() {<br><br>        try {<br>                // Register a network callback to listen for changes<br>                connectivityManager.registerDefaultNetworkCallback(object :<br>                    ConnectivityManager.NetworkCallback() {<br>                    override fun onAvailable(network: Network) {<br>                        super.onAvailable(network)<br>                        isNetworkAvailable = true<br>                    }<br><br>                    override fun onLost(network: Network) {<br>                        super.onLost(network)<br>                        isNetworkAvailable = false<br>                    }<br>                })<br>        } catch (e: Exception) {<br>            Log.e(&quot;&quot;, e.printStackTrace().toString())<br>        }<br>    }<br><br>    fun isInternetAvailable(): Boolean {<br>        return isNetworkAvailable<br>    }<br><br>    private fun checkNetworkConnection() {<br>        val activeNetwork = connectivityManager.activeNetwork<br>        val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork)<br><br>        isNetworkAvailable = networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true<br>    }<br><br>}</pre><h3>Conclusion</h3><p>By implementing this approach, your Android app can load cached JSON data when offline, ensuring a seamless user experience. The <strong>ReadWriteToCache</strong> class helps in managing JSON storage, while <strong>ViewModel</strong> and <strong>Retrofit</strong> ensure data fetching from both network and cache.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dcc7187bb5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binding adapter in Android kotlin using @BindingAdapter : A  Powerful Tool for Custom Bindings or…]]></title>
            <link>https://medium.com/@devarshbhalara3072/binding-adapter-in-android-kotlin-using-bindingadapter-a-powerful-tool-for-custom-bindings-or-817343db02d9?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/817343db02d9</guid>
            <category><![CDATA[glide]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[custom-properties]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[bindingadapter]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 17:05:59 GMT</pubDate>
            <atom:updated>2024-10-01T17:05:59.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>Binding adapter in Android kotlin using @<strong>BindingAdapter : A Powerful Tool for Custom Bindings or Custom Property</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGYvUebNVdu6oR4BhHca2Q.jpeg" /></figure><p>In Android development, we often need to customize how views are updated with data. The <strong>Data Binding</strong> library makes this easier by allowing developers to bind UI components in layouts to data sources declaratively.</p><p>We’ll explore <strong>Binding Adapters</strong> in Android, and how you can use them to create custom attributes for XML views.</p><p>When it comes to loading images from URLs in Android, the <strong>Glide</strong> library is a popular choice among developers. Typically, the code to load images remains largely consistent, with only the URL and ImageView ID changing. This repetitive pattern can clutter your code and make it harder to maintain. To address this issue, we can create a custom property for our XML views using <strong>Data Binding</strong> and @BindingAdapter. By doing so, we can streamline the image loading process, allowing us to set an image directly from a URL in a more declarative and reusable way. This approach not only reduces boilerplate code but also enhances readability, making it clear what each ImageView is displaying right within the layout.</p><p><strong>What is @BindingAdapter?</strong></p><p>@BindingAdapter is part of the Android <strong>Data Binding</strong> library, which allows developers to bind UI components to data sources in a declarative way. When the default attributes and bindings don’t fit your needs, @BindingAdapter lets you create custom attributes in XML to control how data is displayed and manipulated.</p><p>With this annotation, you can specify custom logic for properties directly in the XML layout files, reducing boilerplate code in your activities and fragments.</p><p><strong>What is @BindingAdapter?</strong></p><p>@BindingAdapter is part of the Android <strong>Data Binding</strong> library, which allows developers to bind UI components to data sources in a declarative way.<br>Binding adapters are responsible for making the appropriate framework calls to set values. <br>One example is setting a property value, like calling the <a href="https://developer.android.com/reference/android/widget/TextView#setText(int)">setText()</a> method. Another example is setting an event listener, like calling the <a href="https://developer.android.com/reference/android/view/View#setOnClickListener(android.view.View.OnClickListener)">setOnClickListener()</a> method.<br>When the default attributes and bindings don’t fit your needs, @BindingAdapter lets you create custom attributes in XML to control how data is displayed and manipulated.</p><p>With this annotation, you can specify custom logic for properties directly in the XML layout files, reducing boilerplate code in your activities and fragments.</p><p><strong>Why @BindingAdapter?</strong></p><ol><li><strong>Reusability</strong>: It enables reusable logic that can be shared across multiple views or layouts.</li><li><strong>Separation of Concerns</strong>: You can keep your UI logic clean and out of the activity or fragment, making the code easier to manage and maintain.</li><li><strong>Declarative UI</strong>: It promotes a declarative UI style, where your XML becomes more expressive, clearly defining what each view is supposed to do.</li></ol><p><strong>Let’s create Custom Binding Adapter :</strong></p><p>Let’s take an real world example of how to use @BindingAdapter to load images into ImageView using Glide.</p><p>What this custom adapter can do ?</p><ul><li>Loading images from a URL.</li><li>Using a placeholder while the image is loading.</li><li>Optionally applying a circular transformation to make the image round.</li></ul><p><strong>Step 1: Adding Dependencies and Enable Data binding</strong></p><p>Glide :</p><pre>dependencies {<br>    implementation(&quot;com.github.bumptech.glide:glide:4.12.0&quot;)<br>    kapt(&quot;com.github.bumptech.glide:compiler:4.12.0&quot;)<br>}</pre><p>DataBinding:</p><pre>android {<br>...<br>    buildFeatures {<br>       dataBinding true<br>    }<br>}</pre><p><strong>Step 2: Create the @BindingAdapter</strong></p><p>Here’s how you can create a custom binding adapter for loading images into an ImageView with Glide. The @BindingAdapter will take three optional parameters.</p><ul><li>The URL of the image.</li><li>A placeholder image to display while loading.</li><li>A boolean to determine if the image should be rounded.</li></ul><p>This parameter can vary according to your requirements. First, you need to analyze and then adjust the parameters based on your needs. For example, if you know that your app design does not include any rounded image views, then you do not need the “isRound” parameter.</p><pre>@SuppressLint(&quot;CheckResult&quot;)<br>@BindingAdapter(&quot;imageUrl&quot;, &quot;placeholder&quot;, &quot;isRounded&quot;, requireAll = false)<br>fun ImageView.bindImage(<br>    url: String?,<br>    placeholder: Drawable? = null,<br>    isRounded: Boolean? = false<br>) {<br>    // If no URL is provided, do nothing<br>    if (url == null) return<br><br>    // Load image with Glide<br>    Glide.with(this)<br>        .load(url)<br>        .placeholder(<br>            placeholder ?: AppCompatResources.getDrawable(<br>                context,<br>                R.drawable.baseline_music_note_24 // Default placeholder if none provided<br>            )<br>        )<br>        .apply {<br>            // Apply circle cropping if &#39;isRounded&#39; is true<br>            isRounded?.let { if (it) circleCrop() }<br>        }<br>        .into(this) // Load the image into the ImageView<br>}</pre><p><strong>Step 3: Using the @BindingAdapter in XML</strong></p><p>Once you’ve defined the @BindingAdapter, you can use it directly in your XML layout files. Here’s an example of how to bind an image URL, set a placeholder, and optionally round the image:</p><p>I’ve used this Binding adapter in my recycler view’s item layout here is the example:</p><pre>&lt;layout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:bind=&quot;http://schemas.android.com/apk/res-auto&quot;&gt;<br><br>   &lt;data&gt;<br>        &lt;variable<br>            name=&quot;category&quot;<br>            type=&quot;com.mymusic.app.data.model.remote.Category&quot; /&gt;<br>    &lt;/data&gt;<br><br>    &lt;ImageView<br>        android:layout_width=&quot;100dp&quot;<br>        android:layout_height=&quot;100dp&quot;<br>        bind:imageUrl=&quot;@{ category.images[0].url }&quot; &lt;!-- Image URL from Model object --&gt;<br>        bind:placeholder=&quot;@{@drawable/placeholder_image}&quot; &lt;!-- Placeholder image --&gt;<br>        bind:isRounded=&quot;@{true}&quot; &lt;!-- Circular image transformation --&gt;<br>        /&gt;<br>&lt;/layout&gt;</pre><blockquote>If you encounter an error with bind:imageUrl or any other custom property in your XML layout, try rebuilding your project to ensure that the data binding process is updated and recognizes the new bindings.</blockquote><p>In this example:</p><ul><li>app:imageUrl binds the image URL provided by the model object.</li><li>app:placeholder defines the drawable resource to show while the image is loading.</li><li>app:isRounded specifies whether the image should be rounded.</li></ul><p><strong>How It Works</strong></p><ol><li><strong>Image Loading</strong>: The adapter uses Glide to load the image from the provided URL.</li><li><strong>Placeholder Handling</strong>: If a placeholder drawable is provided, it will be displayed while the image is loading. If no placeholder is specified, it falls back to a default drawable.</li><li><strong>Circular Image</strong>: When isRounded is set to true, the image is transformed into a circle using Glide’s circleCrop() method.</li></ol><p><strong>How to use this in Activity, Fragment or Adapter :</strong></p><p>You can access variable from xml into your class using binding, for example this is how i’ve used this in my adapter :</p><pre>class CategoryAdapter : BaseAdapter&lt;Category&gt;() {<br><br>    override fun getLayoutId(viewType: Int): Int = R.layout.item_category<br><br>    override fun setDataForListItemWithPosition(<br>        binding: ViewDataBinding,<br>        data: Category,<br>        adapterPosition: Int<br>    ) {<br>        //write this in your onBindViewHolder()<br>        (binding as? ItemCategoryBinding)?.apply {<br>            category = data //set your varible of xml<br>            categoryContainer.setCardBackgroundColor(Int.randomColor())<br>        }<br>    }<br>}</pre><p>You can achieve this in your Activity or Fragment by using binding.variable_nameto assign the value. Once you do this, the image will be loaded successfully.</p><p><strong>Benefits of Using @BindingAdapter for Image Loading</strong></p><p>• Cleaner Code: Rather than writing code to load images in every activity or fragment, you can simply bind the data directly in the layout files.</p><p>• Improved Separation of Concerns: By relocating the image loading logic away from your view components, you maintain cleaner activity and fragment code that is more focused on business logic.</p><p>• Reusable Logic: The custom binding adapter is reusable across various layouts and components, providing a more flexible and maintainable solution.</p><p><strong>Conclusion</strong></p><p>@BindingAdapter is a powerful tool that allows Android developers to extend the data binding library with custom functionality. In this blog, we’ve demonstrated how to use @BindingAdapter to bind images to ImageView components, leveraging the Glide library for efficient image loading. With this approach, you can keep your UI code cleaner, more reusable, and declarative, making your layouts easier to manage.</p><p>With this example, you’re now equipped to implement more advanced binding logic for your custom views, improving the overall efficiency and cleanliness of your codebase.</p><p>That’s all for now! I hope you found this guide helpful. Stay tuned for more advanced topics in Android development!</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=817343db02d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Dynamic Shortcuts in Android Using Kotlin: Complete Guide]]></title>
            <link>https://medium.com/@devarshbhalara3072/how-to-implement-dynamic-shortcuts-in-android-using-kotlin-complete-guide-d0a187adf354?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0a187adf354</guid>
            <category><![CDATA[app-shortcuts]]></category>
            <category><![CDATA[android-app-shortcuts]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-shortcut]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 17:20:53 GMT</pubDate>
            <atom:updated>2024-09-23T17:22:44.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGYvUebNVdu6oR4BhHca2Q.jpeg" /></figure><p>Dynamic shortcuts in Android offer a way to provide users with fast access to key features of your app, directly from their home screen. Unlike static shortcuts, which are declared in the app’s manifest, dynamic shortcuts can be created, updated, and removed programmatically during runtime.</p><p><strong>Step 1: Add Required Dependencies:</strong></p><blockquote>You can start directly with Step 2 to implement dynamic shortcuts. If you encounter any errors, such as “Undefined class” or “Undefined symbols”, then you can add the necessary dependency to your project to resolve the issue.</blockquote><pre>implementation(&quot;androidx.core:core-ktx:1.9.0&quot;)</pre><p><strong>Step 2: Creating a Dynamic Shortcuts Helper Class</strong></p><p>We will now create a ShortcutsHelper class that manages our shortcuts. This class will include methods to create, manage, and remove shortcuts dynamically.</p><pre>class ShortcutsHelper(private val context: Context) {<br><br>    companion object {<br>        const val HOME_SHORTCUT_ID = &quot;home_shortcut_id&quot;<br>    }<br><br>    fun createShortcuts() {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N_MR1) {<br>            val listOfShortcuts = getShortcutsList()<br>            ShortcutManagerCompat.setDynamicShortcuts(context, listOfShortcuts)<br>        }<br>    }<br><br>    fun updateShortcut(<br>        id: String,<br>        shortLabel: String,<br>        longLabel: String,<br>        intent: Intent,<br>        shortcutIcon: Int<br>    ) {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N_MR1) {<br>            val updatedShortcut = buildShortcut(<br>                id = id,<br>                shortLabel = shortLabel,<br>                longLabel = longLabel,<br>                intent = intent,<br>                shortcutIcon = shortcutIcon<br>            )<br>            ShortcutManagerCompat.updateShortcuts(context, listOf(updatedShortcut))<br>        }<br>    }<br><br>    fun removeShortcut(shortcutId: String) {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N_MR1) {<br>            ShortcutManagerCompat.removeDynamicShortcuts(context, listOf(shortcutId))<br>        }<br>    }<br><br>    private fun getShortcutsList(): List&lt;ShortcutInfoCompat&gt; {<br>        val homeShortCut = buildShortcut(<br>            id = HOME_SHORTCUT_ID,<br>            shortLabel = &quot;Home&quot;,<br>            longLabel = &quot;Home Screen&quot;,<br>            intent = Intent(context, ActivityOne::class.java).apply {<br>                action = Intent.ACTION_VIEW<br>            },<br>            shortcutIcon = R.drawable.baseline_home_24<br>        )<br><br>        // create more shortcut if you want and don&#39;t forget to add that to list<br><br>        return listOf(homeShortCut)<br>    }<br><br>    private fun buildShortcut(<br>        id: String,<br>        shortLabel: String,<br>        longLabel: String,<br>        intent: Intent,<br>        shortcutIcon: Int<br>    ): ShortcutInfoCompat {<br>        return ShortcutInfoCompat.Builder(context, id)<br>            .setShortLabel(shortLabel)<br>            .setLongLabel(longLabel)<br>            .setIntent(intent)<br>            .setIcon(IconCompat.createWithResource(context, shortcutIcon))<br>            .build()<br>    }<br>}</pre><p><strong>Step 4: Using the Shortcuts in an Activity</strong></p><p>Once the ShortcutsHelper class is set up, you can create dynamic shortcuts in any activity. Just create an instance of ShortcutsHelper and call it’s createShortcuts() to create an Shortcut.</p><p>You can integrate the shortcut creation logic into your app’s flow as needed. For instance, if you want to set up the shortcuts by default when the activity is launched, you can call the createShortcuts() method inside the onCreate() method of the activity., like this:</p><pre>// Initialize the ShortcutsHelper and create shortcuts<br>val shortcutsHelper = ShortcutsHelper(this)<br>shortcutsHelper.createShortcuts()</pre><p><strong>Step 4: Removing Dynamic Shortcuts</strong></p><p>If you want to remove dynamic shortcuts programmatically, especially if they are no longer relevant to the user. Here’s how you can do that:</p><pre>val shortcutsHelper = ShortcutsHelper(this)<br>shortcutsHelper.removeShortcut(ShortcutsHelper.HOME_SHORTCUT_ID) // pass id of the shortcut that you want to remove</pre><p>This will remove the shortcut with the specified ID.</p><p><strong>Step 6: Updating Shortcuts</strong></p><p>You can also update an existing dynamic shortcut using the same ID. For example, you might want to update the label or icon of a shortcut:</p><pre>val shortcutsHelper = ShortcutsHelper(this)<br>shortcutsHelper.updateShortcut(<br>     ShortcutsHelper.HOME_SHORTCUT_ID, // use id of shortcut that you want to update<br>     &quot;Updated home&quot;,<br>     &quot;Update Home Screen&quot;,<br>      Intent(this, ActivityTwo::class.java).apply {<br>          action = Intent.ACTION_VIEW<br>      },<br>      R.drawable.baseline_settings_24<br>)</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*CgQzkzk3Xok7Zwjb4qSllg.png" /></figure><p>By clicking on the Home Screenshortcut, the corresponding activity, which was specified when creating the shortcut, will be launched.</p><p><strong>Conclusion:</strong></p><p>Dynamic shortcuts are a powerful feature in Android that can greatly enhance the user experience by allowing quick access to key functionalities of your app. By following the steps above, you can implement dynamic shortcuts in your Android app using Kotlin, and even update or remove them as needed.</p><p>Dynamic shortcuts not only improve usability but can also increase engagement by giving users direct access to frequently used parts of your app. Implement this feature, and you’ll provide a smoother, more interactive experience for your users.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a187adf354" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Api calling and State handling in Jetpack compose]]></title>
            <link>https://medium.com/@devarshbhalara3072/api-calling-and-state-handling-in-android-jetpack-compose-360fd3e6eb44?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/360fd3e6eb44</guid>
            <category><![CDATA[android-jetpack-compose]]></category>
            <category><![CDATA[api-calling-in-android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin-stateflow]]></category>
            <category><![CDATA[state-management]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Tue, 17 Sep 2024 17:08:12 GMT</pubDate>
            <atom:updated>2024-09-17T17:09:39.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGYvUebNVdu6oR4BhHca2Q.jpeg" /></figure><p>Jetpack Compose, Android’s modern UI toolkit, makes building UI components easier and more declarative. When combined with ViewModel and state management, it becomes a powerful tool for handling dynamic UI and API calls in a clean and efficient way.</p><p>In this blog, we’ll demonstrate how to handle API calls and state management using Jetpack Compose, with the help of ViewModel, StateFlow, and MutableStateFlow. We will use a login functionality as our use case for demonstrating this.</p><p>In this blog i’m using example of Login functionality of my application, how i handled that states…</p><p>We will use the following components in our architecture:</p><ul><li><strong>ViewModel</strong>: Manages UI-related data in a lifecycle-conscious way.</li><li><strong>StateFlow</strong>: For managing and updating the UI state in response to API events.</li><li><strong>Jetpack Compose</strong>: To build the UI that reacts to the state changes in real-time.</li></ul><p>The primary task for the login flow is to:</p><ol><li>Validate user input (email and password).</li><li>Make an API call to the server to authenticate the user.</li><li>Manage the state of the UI based on the API response (success, error, or loading).</li></ol><p><strong>1. State Management with LoginUserState</strong></p><p>State management is key to handling different scenarios like form input, validation errors, and API responses. The LoginUserState data class is used to capture and manage this state.</p><blockquote>How to design this state class ?</blockquote><blockquote>To design the LoginUserState class, we first need to map out all the possible states our UI can have. Since we’re dealing with a login form, the UI will handle multiple scenarios such as user input, form validation, API responses (loading, success, and error), and successful login data. Let’s break down the different aspects of the UI and the possible states it can go through. If you have another screen or another scenario then you need to figure this out on your own.</blockquote><p>Here’s the structure of the LoginUserState:</p><pre>data class LoginUserState(<br>    var email: String? = null,<br>    var password: String? = null,<br>    var error: String? = null,<br>    var emailEmpty: String? = null,<br>    var passwordEmpty: String? = null,<br>    var userData: LoginResponse? = null,<br>    var isSuccess: Boolean = false,<br>)</pre><p>This class keeps track of:</p><ul><li><strong>email and password</strong>: The user’s input for the login form.</li><li><strong>error</strong>: The error message returned by the server, if any.</li><li><strong>emailEmpty and passwordEmpty</strong>: Validation errors for the form fields.</li><li><strong>userData</strong>: The server’s response data, such as user details and tokens.</li><li><strong>isSuccess</strong>: A flag to determine if the login was successful.</li></ul><p><strong>2. ViewModel with StateFlow</strong></p><p>In our ViewModel, we use StateFlow to track the state of the login form, which allows the UI to observe and react to changes in the state.</p><pre>@HiltViewModel<br>class LoginUserViewModel @Inject constructor(<br>    private val userRepository: UserRepository,<br>    private val savedStateHandle: SavedStateHandle<br>): ViewModel() {<br><br>    private val email = savedStateHandle.getStateFlow(&quot;email&quot;, &quot;&quot;)<br>    private val password = savedStateHandle.getStateFlow(&quot;password&quot;, &quot;&quot;)<br><br>    private val _apiState = MutableStateFlow(LoginUserState())<br>    val apiState = _apiState.asStateFlow()<br><br>    val state =<br>        combine(email, password) { email, password -&gt;<br>            LoginUserState(<br>                email = email,<br>                password = password,<br>            )<br>        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), LoginUserState())<br><br>    fun onEmailChanges(email: String) {<br>        savedStateHandle[&quot;email&quot;] = email<br>    }<br><br>    fun onPasswordChanges(password: String) {<br>        savedStateHandle[&quot;password&quot;] = password<br>    }<br><br>    fun loginUser(context: Context) {<br>        val loginRequest = LoginRequest(<br>            email = state.value.email ?: &quot;&quot;,<br>            password = state.value.password ?: &quot;&quot;<br>        )<br><br>        val results = UserValidator.validateLoginData(loginRequest)<br>        val error = listOfNotNull(<br>            results.emailError,<br>            results.passwordError<br>        )<br><br>        if (error.isEmpty()) {<br>            viewModelScope.launch {<br>                _apiState.value = state.value<br>                userRepository.loginUser(loginRequest).collectLatest {<br>                    when (it) {<br>                        is Resource.Error -&gt; {<br>                            _apiState.value = _apiState.value.copy(<br>                                error = it.message<br>                            )<br>                        }<br>                        is Resource.Loading -&gt; {<br>                            Log.e(&quot;login_vm&quot;, &quot;Loading&quot;)<br>                        }<br>                        is Resource.Success -&gt; {<br>                            if (it.data?.status == true) {<br>                                _apiState.value = _apiState.value.copy(<br>                                    error = null,<br>                                    isSuccess = true,<br>                                    userData = it.data<br>                                )<br>                                EPreference(context).setString(EPreference.USER_TOKEN, it.data.token!!)<br>                            } else {<br>                                _apiState.value = _apiState.value.copy(<br>                                    error = it.data?.message,<br>                                    isSuccess = false,<br>                                )<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        } else {<br>            _apiState.value = _apiState.value.copy(<br>                emailEmpty = results.emailError,<br>                passwordEmpty = results.passwordError,<br>                isSuccess = false,<br>            )<br>        }<br>    }<br>}<br><br><br>// User validator <br><br>object UserValidator {<br><br>    fun validateLoginData(contact: LoginRequest): LoginValidationResult {<br>        var result = LoginValidationResult()<br><br><br>        if(contact.email.isBlank()) {<br>            result = result.copy(emailError = &quot;The email can&#39;t be empty.&quot;)<br>        }<br><br>        val emailRegex = Regex(&quot;^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}\$&quot;)<br>        if(!emailRegex.matches(contact.email)) {<br>            result = result.copy(emailError = &quot;This is not a valid email.&quot;)<br>        }<br><br>        if(contact.password.isBlank()) {<br>            result = result.copy(passwordError = &quot;The password can&#39;t be empty.&quot;)<br>        }<br><br>        return result<br>    }<br><br>    data class LoginValidationResult(<br>        val emailError: String? = null,<br>        val passwordError: String? = null,<br>    )<br>}</pre><p><strong>Explanation:</strong></p><ol><li><strong>StateFlow for email and password</strong>: The ViewModel uses SavedStateHandle to persist the email and password fields, ensuring they survive configuration changes.</li><li><strong>API State with MutableStateFlow</strong>: The _apiState tracks the entire state of the API call. It is updated based on the result of the API call (loading, success, or error).</li><li><strong>State validation</strong>: The login data is validated using UserValidator, and if there are any errors, they are reflected in the UI state.</li></ol><p><strong>3. Making the API Call</strong></p><p>The API call is initiated in the loginUser() function of the ViewModel. We use the UserRepository to perform the network request, and handle success, loading, and error states.</p><pre>class UserRepository(<br>    private val userService: ApiUserService<br>): BaseRepository() {<br><br>    suspend fun loginUser(loginRequest: LoginRequest) = flow {<br>        emit(Resource.Loading())<br>        try {<br>            userService.loginUser(loginRequest).let {<br>                val response = handleResponse(it)<br>                emit(response)<br>            }<br>        } catch (e: Exception) {<br>            Log.e(&quot;error_repo&quot;, e.printStackTrace().toString())<br>            emit(Resource.Error(&quot;Something went wrong, Please try again later!&quot;))<br>        }<br>    }.flowOn(Dispatchers.IO)<br><br>}<br><br>// Api response Class replace &#39;T&#39; with your desired response from Api<br>sealed class Resource&lt;T&gt;(val data: T? = null, val message: String? = null) {<br>    class Loading&lt;T&gt;(data: T? = null) : Resource&lt;T&gt;(data)<br>    class Success&lt;T&gt;(data: T?) : Resource&lt;T&gt;(data)<br>    class Error&lt;T&gt;(message: String, data: T? = null) : Resource&lt;T&gt;(data, message)<br>}</pre><p>When the API call is successful:</p><ul><li>The LoginUserState is updated with the response data.</li><li>The success flag (isSuccess) is set to true.</li><li>The user’s token is saved locally via EPreference.</li></ul><p>If the API call fails, the state is updated with the error message.</p><p><strong>4. Displaying the UI with Jetpack Compose</strong></p><p>Now that we’ve managed the state and API call in the ViewModel, we can display the UI using Jetpack Compose. The UI will observe the apiState and update accordingly.</p><p>This is my demo composable function which shows how to call Login api and observe api states.</p><pre>@Composable<br>fun LoginScreen(navController: NavController, modifier: Modifier = Modifier) {<br><br>    val viewModel: LoginUserViewModel = hiltViewModel()<br>    val state by viewModel.state.collectAsState()<br>    val apiState by viewModel.apiState.collectAsState()<br><br>    val context = LocalContext.current<br><br>    LaunchedEffect(key1 = apiState) {<br>        if (apiState.isSuccess) {<br>            Toast.makeText(context, &quot;Login Successfully!&quot;, Toast.LENGTH_SHORT).show()<br>            navController.navigate(&quot;home&quot;)<br>        }<br><br>        if (!apiState.error.isNullOrEmpty()) {<br>            Toast.makeText(context, apiState.error, Toast.LENGTH_SHORT).show()<br>        }<br>    }<br><br>    Scaffold { padding -&gt;<br><br>        Column(modifier = Modifier.fillMaxWidth()) {<br><br>            Text(<br>                text = &quot;Welcome back!&quot;,<br>                fontSize = 24.sp,<br>                fontWeight = FontWeight.Bold,<br>                style = TextStyle(color = Color.Black)<br>            )<br><br>            Spacer(Modifier.height(8.dp))<br><br>            Text(<br>                text = &quot;Sign in to your account&quot;,<br>                fontSize = 16.sp,<br>            )<br><br>            UserTextField(<br>                value = state.email ?: &quot;&quot;,<br>                onValueChange = viewModel::onEmailChanges,<br>                placeholder = &quot;Enter Email&quot;,<br>                error = apiState.emailEmpty<br>            )<br><br>            Spacer(Modifier.height(8.dp))<br><br>            UserTextField(<br>                value = state.password ?: &quot;&quot;,<br>                onValueChange = viewModel::onPasswordChanges,<br>                placeholder = &quot;Enter Password&quot;,<br>                error = apiState.passwordEmpty<br>            )<br><br>            Button(<br>                onClick = {<br>                    viewModel.loginUser(context)<br>                },<br>                modifier = Modifier.fillMaxWidth(),<br>                shape = RoundedCornerShape(12.dp), // Apply rounded corners<br>                enabled = true<br>            ) {<br>                Text(&quot;Login&quot;)<br>            }<br><br>        }<br><br>    }<br>}<br><br>@Composable<br>fun UserTextField(<br>    value: String,<br>    onValueChange: (String) -&gt; Unit,<br>    placeholder: String,<br>    error: String?,<br>    modifier: Modifier = Modifier)<br>{<br><br>    Column(modifier) {<br>        OutlinedTextField(<br>            value = value,<br>            placeholder = {<br>                Text(text = placeholder)<br>            },<br>            onValueChange = onValueChange,<br>            shape = RoundedCornerShape(20.dp),<br>            modifier = Modifier.fillMaxWidth()<br>        )<br><br>        if(error != null) {<br>            Text(text = error, color = Color.Red)<br>        }<br>    }<br><br>}</pre><p><strong>Explanation:</strong></p><ul><li><strong>Reactive UI</strong>: The UI components such as TextField and Button reactively bind to the state variables. As soon as the state changes (e.g., when the API call succeeds or fails), the UI updates.</li><li><strong>Form Validation</strong>: The UI also reflects validation errors like emailEmpty and passwordEmpty using error text fields.</li><li><strong>API Success and Error</strong>: Once the login is successful, the UI will display a success message. If there’s an error, it shows the error message.</li></ul><p><strong><em>Understanding the Login Flow with Scenarios (Don’t miss this…) :</em></strong></p><p>In this login flow, we will explore the interaction between the UI and the ViewModel in Jetpack Compose, focusing on how state is managed and handled during the process. Here’s how the flow works:</p><p>1. <strong>Initial State on Composable Rendering</strong>:</p><ul><li>When the LoginScreen composable is rendered on the screen (i.e., when the UI becomes visible), the ViewModel is initialized.</li><li>At this stage, all fields within our LoginUserState are empty, so the Email and Password text fields will also be empty in the UI by default. The state values (e.g., email, password, error) are all initialized with default values (null or empty).</li></ul><p>2. <strong>Handling User Interaction (Login Button Click)</strong>:</p><ul><li>When the user clicks the <strong>Login</strong> button without entering a password, validation in the ViewModel is triggered.</li><li>The ViewModel checks if all required fields are filled. Since the password is missing, the validation fails, and the passwordEmpty field in our state is populated with an appropriate error message (e.g., “Password is required”).</li><li>The _apiState is then updated with this new value, reflecting the validation error.</li><li>As a result, the composable function observing apiState will react to this state change and recompose the UI. Specifically, the Password text field will show an error message (using passwordEmpty from the state).</li></ul><p>This process showcases <strong>state handling</strong> — where the state is updated in the ViewModel and automatically reflected in the UI. The UI reacts and re-draws itself based on the updated state values.</p><p>3. <strong>Valid Input and API Call</strong>:</p><ul><li>After the user correctly enters the password and clicks the <strong>Login</strong> button again, the ViewModel triggers an API call to log in the user.</li><li>The call happens within a coroutine (managed by viewModelScope), and the state is updated to indicate loading (via isLoading).</li><li>If the email or password is incorrect, the API will return a response with a status of false. This is handled in the Resource.Success block of the ViewModel, where:</li><li>The _apiState is updated with the error message from the server response (e.g., “Invalid credentials”).</li><li>The UI observes this state change and recomposes to display the error message using the error field from the state.</li></ul><p>Similar to validation, the UI updates automatically when the state changes, ensuring that the error message is shown to the user.</p><p>4. <strong>Successful Login</strong>:</p><ul><li>If the login credentials are correct, the API response returns a status of true, along with the user’s data (e.g., token, user information).</li><li>The ViewModel captures this response and updates _apiState to:</li><li>Set the isSuccess field to true.</li><li>Store the user data in the userData field.</li><li>The UI, observing the changes in apiState, will reflect the successful login. This might include navigating to a new screen or displaying a success message.</li></ul><p><strong>Key Points:</strong></p><p>• <strong>Composable Recomposition</strong>: Each time the state is updated (whether it’s from user input validation, an API error, or a success), the relevant parts of the UI are <strong>recomposed</strong>. This ensures that the UI stays in sync with the current state.</p><ul><li><strong>Validation Errors</strong>: Fields like passwordEmpty and emailEmpty are used to capture validation errors. These fields are directly mapped to the UI so that error messages are shown whenever validation fails.</li><li><strong>API Call Response</strong>: The API call can either succeed or fail. The response is handled by updating the error or isSuccess fields, and the UI responds accordingly.</li><li><strong>Separation of Concerns</strong>: The state handling logic (validation, API calls) is kept in the ViewModel, while the UI in Jetpack Compose observes these states and reacts by recomposing as needed.</li></ul><p>This flow highlights how <strong>state management</strong> in Jetpack Compose, combined with a ViewModel, creates a reactive system where changes in data are automatically reflected in the UI without the need for manual updates. The UI becomes declarative, reacting only to changes in state.</p><p>By applying these principles, you can improve the maintainability and scalability of your Android apps.</p><p>Feel free to extend this example further by adding features like loading indicators, error handling for network connectivity issues, and more complex forms!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=360fd3e6eb44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Nested Lists in Jetpack Compose: Avoiding Common Pitfalls]]></title>
            <link>https://medium.com/@devarshbhalara3072/handling-nested-lists-in-jetpack-compose-avoiding-common-pitfalls-5fafcd0a8bb3?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fafcd0a8bb3</guid>
            <category><![CDATA[lazyverticalgrid]]></category>
            <category><![CDATA[compose-lazycolumn]]></category>
            <category><![CDATA[lazycolumn]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[nested-list]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Fri, 30 Aug 2024 17:37:42 GMT</pubDate>
            <atom:updated>2024-08-30T17:37:42.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGYvUebNVdu6oR4BhHca2Q.jpeg" /></figure><p><strong>Introduction:</strong></p><p>Jetpack Compose has revolutionized the way we build Android UIs by providing a more intuitive, declarative approach. However, like any powerful tool, it comes with its own set of challenges. One common scenario that can trip up developers is handling nested lists. If not handled correctly, this can lead to crashes and unexpected UI behavior.</p><p>In this blog post, we’ll dive into the details of how to manage nested lists in Jetpack Compose, why it’s tricky, and how to avoid common pitfalls.</p><p><strong>Understanding Nested Lists in Jetpack Compose</strong></p><p>Nested lists are a common requirement in many applications. Imagine a scenario where you have a list of categories, and each category contains a list of products. Displaying such hierarchical data might seem straightforward at first, but it comes with certain challenges, especially around managing the height of each list.</p><blockquote><strong>The Problem with Nested Lists</strong></blockquote><blockquote>In Jetpack Compose, you can’t directly set an item of a list as another list without specifying some constraints like a maximum height or actual height. If you don’t manage the height properly, you may encounter crashes or unexpected behavior. This is because Compose’s layout system needs to know how much space to allocate for each composable, and when dealing with dynamic content like nested lists, this can get tricky.</blockquote><p>If you implement simple Nested list like this below code then you’ll get crash. In this code inside Scaffold i have take a LazyColumn, inside that column’s item i have take a LazyVerticalGrid</p><pre> Scaffold(<br>        topBar = {<br>            TopAppBar(<br>                title = { Text(&quot;Home&quot;) },<br>            )<br>        },<br>        modifier = Modifier.background(Color.White)<br>    ) { paddingValues -&gt;<br><br>        Column(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(paddingValues)<br>                .background(Color.White)<br>        ) {<br>            Searchbar(<br>                value = &quot;&quot;,<br>                onValueChange = {},<br>                placeholder = &quot;Search any item!&quot;,<br>                error = null<br>            )<br><br>            Spacer(modifier = modifier.height(16.dp))<br><br>            LazyColumn(<br>                contentPadding = PaddingValues(16.dp),<br>                verticalArrangement = Arrangement.spacedBy(16.dp),<br>            ) {<br>                state.data?.let {<br>                    items(it) {<br>                        ItemView(categories = it)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>@Composable<br>fun ItemView(categories: HomeDataItem, modifier: Modifier = Modifier) {<br>    Column {<br>        Text(<br>            text = categories.name.capitalize(Locale.current),<br>            style = TextStyle(<br>                fontSize = 18.sp,<br>                color = Color.Black,<br>                fontWeight = FontWeight.Bold<br>            )<br>        )<br>        if (categories.data.isNotEmpty()) {<br>            LazyVerticalGrid(<br>                columns = GridCells.Fixed(2),<br>                modifier = Modifier<br>                    .heightIn(max = 1000.dp)<br>                    .fillMaxWidth(),<br>                verticalArrangement = Arrangement.spacedBy(8.dp),<br>                horizontalArrangement = Arrangement.spacedBy(8.dp)<br>            ) {<br>                items(categories.data) {<br>                    ProductCard(product = it)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>If you’re getting crash in Nested List then it would probably like this:</p><pre>FATAL EXCEPTION: main (Ask Gemini)<br> Process: com.example.firstjetpack, PID: 1846<br> java.lang.IllegalStateException: Vertically scrollable component was measured with an infinity maximum height constraints, which is disallowed. One of the common reasons is nesting layouts like LazyColumn and Column(Modifier.verticalScroll()). If you want to add a header before the list of items please add a header as a separate item() before the main items() inside the LazyColumn scope. There are could be other reasons for this to happen: your ComposeView was added into a LinearLayout with some weight, you applied Modifier.wrapContentSize(unbounded = true) or wrote a custom layout. Please try to remove the source of infinite constraints in the hierarchy above the scrolling container.<br> at androidx.compose.foundation.CheckScrollableContainerConstraintsKt.checkScrollableContainerConstraints-K40F9xA(CheckScrollableContainerConstraints.kt:35)<br> at androidx.compose.foundation.lazy.grid.LazyGridKt$rememberLazyGridMeasurePolicy$1$1.invoke-0kLqBqw(LazyGrid.kt:178)<br> at androidx.compose.foundation.lazy.grid.LazyGridKt$rememberLazyGridMeasurePolicy$1$1.invoke(LazyGrid.kt:177)<br> at androidx.compose.foundation.lazy.layout.LazyLayoutKt$LazyLayout$3$2$1.invoke-0kLqBqw(LazyLayout.kt:107)<br> at androidx.compose.foundation.lazy.layout.LazyLayoutKt$LazyLayout$3$2$1.invoke(LazyLayout.kt:100)<br> at androidx.compose.ui.layout.LayoutNodeSubcompositionsState$createMeasurePolicy$1.measure-3p2s80s(SubcomposeLayout.kt:708)<br> at androidx.compose.ui.node.InnerNodeCoordinator.measure-BRTryo0(InnerNodeCoordinator.kt:126)<br> at androidx.compose.foundation.AndroidOverscroll_androidKt$StretchOverscrollNonClippingLayer$2.invoke-3p2s80s(AndroidOverscroll.android.kt:584)<br> at androidx.compose.foundation.AndroidOverscroll_androidKt$StretchOverscrollNonClippingLayer$2.invoke(AndroidOverscroll.android.kt:583)<br> at androidx.compose.ui.layout.LayoutModifierImpl.measure-3p2s80s(LayoutModifier.kt:291)<br> at androidx.compose.ui.node.LayoutModifierNodeCoordinator.measure-BRTryo0(LayoutModifierNodeCoordinator.kt:116)<br> at androidx.compose.foundation.AndroidOverscroll_androidKt$StretchOverscrollNonClippingLayer$1.invoke-3p2s80s(AndroidOverscroll.android.kt:568)<br> at androidx.compose.foundation.AndroidOverscroll_androidKt$StretchOverscrollNonClippingLayer$1.invoke(AndroidOverscroll.android.kt:567)<br> at androidx.compose.ui.layout.LayoutModifierImpl.measure-3p2s80s(LayoutModifier.kt:291)…….</pre><p>Let’s understand why we are getting this crash:</p><p>If you’re creating a nested list in Jetpack Compose, your code might look something like the example above. In RecyclerView, when we use another RecyclerView as an item, the inner RecyclerView automatically calculates its height according to the content.</p><p>However, in Jetpack Compose, we can’t do this. We need to provide either an estimated height or a fixed height for the inner list. But the question is, how can we manage dynamic heights for the inner list based on its content?</p><p>We can’t give fix height to inner list because we want height of inner list as per content, so we have to give max height to it</p><p><strong>Why You Need a maxHeight ?</strong></p><p>Without defining a maximum height, Jetpack Compose won’t know how much space to allocate for the nested list. This can result in an unstable UI or crashes due to the lack of proper constraints. By setting a heightIn constraint, you’re providing Compose with the necessary information to render the nested list correctly. Like this :</p><pre><br>    Scaffold(<br>        topBar = {<br>            TopAppBar(<br>                title = { Text(&quot;Home&quot;) },<br>            )<br>        },<br>        modifier = Modifier.background(Color.White)<br>    ) { paddingValues -&gt;<br><br><br>        Column(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .padding(paddingValues)<br>                .background(Color.White)<br>        ) {<br><br>            Searchbar(<br>                value = &quot;&quot;,<br>                onValueChange = {},<br>                placeholder = &quot;Search any item!&quot;,<br>                error = null<br>            )<br><br>            Spacer(modifier = modifier.height(16.dp))<br><br>            LazyColumn(<br>                contentPadding = PaddingValues(16.dp),<br>                verticalArrangement = Arrangement.spacedBy(16.dp),<br>            ) {<br>                state.data?.let {<br>                    items(it) {<br>                        ItemView(categories = it)<br>                    }<br>                }<br>            }<br>        }<br>    }<br><br>@Composable<br>fun ItemView(categories: HomeDataItem, modifier: Modifier = Modifier) {<br><br>    Column(<br>    ) {<br>        Text(<br>            text = categories.name.capitalize(Locale.current),<br>            style = TextStyle(<br>                fontSize = 18.sp,<br>                color = Color.Black,<br>                fontWeight = FontWeight.Bold<br>            )<br>        )<br>        if (categories.data.isNotEmpty()) {<br><br>            LazyVerticalGrid(<br>                columns = GridCells.Fixed(2),<br>                modifier = Modifier<br>                    .heightIn(max = 1000.dp) // add this 😃<br>                    .fillMaxWidth(),<br>                verticalArrangement = Arrangement.spacedBy(8.dp),<br>                horizontalArrangement = Arrangement.spacedBy(8.dp)<br>            ) {<br>                items(categories.data) {<br>                    ProductCard(product = it)<br>                }<br>            }<br>        }<br>    }<br><br>}</pre><p>Let’s say you know that your inner list’s maximum height is 2000 dp. If the content in the inner list is less than 2000 dp in height, the list will only take up as much height as needed. However, if the content exceeds 2000 dp, only the portion that fits within 2000 dp will be displayed.<br>In Jetpack it’s necessary to give some estimate height of inner list that’s why either we can give fix height (which is not optimal) or max height.<br>In my example i have created LazyVerticalGrid inside LazyColumn.</p><p>Here is my output screen shot (I have used dummy api which is created by me just for learning purpose so just ignore images and content☺️) :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*tLCDWTQlrDj75lhVVeapjA.png" /></figure><p>Here i have created LazyColumn with LazyVerticalGrid. You can also use LazyColumn or any List types instead of LazyVerticalGrid according to your need.</p><p><strong>Conclusion</strong></p><p>Handling nested lists in Jetpack Compose requires careful consideration of layout constraints, especially around height management. By setting appropriate fix height or maxHeight values, you can avoid crashes and ensure your UI renders smoothly.</p><p>If you’re dealing with nested lists in your Compose project, remember to always define size constraints. This simple step can save you from a lot of headaches down the road.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fafcd0a8bb3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management in Jetpack compose using ViewModel and StateFlow(Basic)]]></title>
            <link>https://medium.com/@devarshbhalara3072/state-management-in-jetpack-compose-using-viewmodel-and-stateflow-basic-c4515eb5169d?source=rss-e81dd0b64bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4515eb5169d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androidviewmodel]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[kotlin-stateflow]]></category>
            <dc:creator><![CDATA[Devarsh Bhalara]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 16:50:40 GMT</pubDate>
            <atom:updated>2024-08-29T16:50:40.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CGYvUebNVdu6oR4BhHca2Q.jpeg" /></figure><p>Jetpack Compose has redefined UI development in Android by introducing a declarative approach to building user interfaces. However, as your app grows in complexity, managing state becomes more challenging, especially when dealing with data that needs to survive configuration changes like screen rotations. This is where integrating Jetpack Compose with ViewModel and StateFlow becomes invaluable.</p><p>In this blog, we will explore how to manage state in Jetpack Compose using ViewModel and StateFlow, demonstrating these concepts with a simple counter example.</p><blockquote><strong>Why Use ViewModel and StateFlow?</strong></blockquote><blockquote>In Jetpack Compose, state can be managed directly within composables using functions like remember and mutableStateOf. While this approach is fine for simpler scenarios, it has limitations when it comes to more complex apps. For example, if your app’s state needs to persist across configuration changes or be shared between multiple composables, relying solely on composable state can lead to complications.</blockquote><blockquote>ViewModel is a lifecycle-aware component designed to store and manage UI-related data in a way that survives configuration changes. Combined with StateFlow, a Kotlin construct for state management, you can create reactive streams of data that are easy to observe in Jetpack Compose.</blockquote><p><strong>Example: Counter App with ViewModel and StateFlow</strong></p><ol><li><strong>Setting Up the Activity</strong></li></ol><p>The ViewModelStateActivity class extends ComponentActivity and serves as the entry point of the app. In the onCreate method, we set the content of the activity using setContent, applying the app’s theme with JetpackDemosTheme, and setting the main screen with the MainScreen composable.</p><pre>class ViewModelStateActivity : ComponentActivity(){<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        enableEdgeToEdge()<br>        setContent {<br>            JetpackDemosTheme {<br>                MainScreen()<br>            }<br>        }<br>    }<br>}</pre><p><strong>2. MainScreen Composable: Integrating ViewModel and StateFlow</strong></p><p>In the MainScreen composable, we first obtain an instance of CounterViewModel using viewModel(). This is the recommended way to get a ViewModel instance in Jetpack Compose, as it is lifecycle-aware and scoped to the composable.</p><p>The count state in the ViewModel is exposed as a StateFlow, which is a state holder observable through Jetpack Compose’s collectAsState() extension function. This ensures that whenever the count state changes, the MainScreen composable will automatically recompose.</p><pre>@Composable<br>fun MainScreen(modifier: Modifier = Modifier) {<br><br>    val viewModel: CounterViewModel = viewModel()<br>    val counter by viewModel.count.collectAsState()<br><br>    Scaffold(<br>        floatingActionButton = {<br>            FloatingActionButton(onClick = {<br>                viewModel.increment()<br>            }) {<br>                Icon(Icons.Default.Add, contentDescription = &quot;Add&quot;)<br>            }<br>        },<br>        modifier = Modifier.fillMaxSize()) { innerPadding -&gt;<br><br>        Column(<br>            verticalArrangement = Arrangement.Center,<br>            modifier = Modifier.fillMaxSize()<br>        ) {<br>            Greeting(<br>                text = &quot;You clicked button $counter times&quot;,<br>                modifier = Modifier.padding(innerPadding)<br>            )<br>        }<br>    }<br>}</pre><p><strong>3. Scaffold Layout: Structuring the UI</strong></p><p>The Scaffold composable provides a basic structure for your screen, with slots for common UI elements like the floating action button (FAB). The FAB triggers the increment function in the ViewModel when clicked, increasing the counter value stored in the StateFlow. The Greeting composable then displays the updated count.</p><pre>Scaffold(<br>    floatingActionButton = {<br>        FloatingActionButton(onClick = {<br>            viewModel.increment()<br>        }) {<br>            Icon(Icons.Default.Add, contentDescription = &quot;Add&quot;)<br>        }<br>    },<br>    modifier = Modifier.fillMaxSize()<br>) { innerPadding -&gt;<br><br>    Column(<br>        verticalArrangement = Arrangement.Center,<br>        modifier = Modifier.fillMaxSize()<br>    ) {<br>        Greeting(<br>            text = &quot;You clicked the button $counter times&quot;,<br>            modifier = Modifier.padding(innerPadding)<br>        )<br>    }<br>}</pre><p><strong>4. Greeting Composable: Displaying the State</strong></p><p>The Greeting composable is responsible for displaying the text that reflects the current count. It uses the text parameter, which is dynamically updated as the state in the ViewModel changes.</p><pre>@Composable<br>fun Greeting(text: String, modifier: Modifier = Modifier) {<br>    Text(<br>        text = &quot;Hello $text!&quot;,<br>        textAlign = TextAlign.Center,<br>        modifier = modifier.fillMaxWidth()<br>    )<br>}</pre><p><strong>5. CounterViewModel: Managing State with StateFlow</strong></p><p>The CounterViewModel holds the counter state using a MutableStateFlow. The MutableStateFlow is initialized with a value of 0, and the count property exposes it as a read-only StateFlow to the rest of the app. The increment function updates the _count value, triggering recomposition in any composable that collects this state.</p><pre>class CounterViewModel: ViewModel() {<br>    private val _count = MutableStateFlow(0)<br>    val count = _count.asStateFlow()<br><br>    fun increment() {<br>        _count.value++<br>    }<br>}</pre><p><strong>Benefits of Using ViewModel with StateFlow in Jetpack Compose</strong></p><p>1. <strong>Survives Configuration Changes:</strong> Since the ViewModel is lifecycle-aware, the counter state persists even if the device undergoes configuration changes, like a screen rotation.</p><p>2. <strong>Centralized State Management:</strong> The ViewModel centralizes the state management logic, making it easier to maintain and test.</p><p>3. <strong>Reactive UI Updates:</strong> By using StateFlow, you ensure that the UI automatically reacts to state changes, keeping the UI in sync with the data.</p><p><strong>Conclusion</strong></p><p>In this blog, we explored how to manage state in Jetpack Compose using ViewModel and StateFlow. This approach is particularly beneficial for complex apps where state needs to survive configuration changes or be shared across multiple composables. By leveraging ViewModel for state management, you can build robust, responsive UIs that maintain consistency and reduce the risk of bugs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4515eb5169d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>