<?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 Mobile Alchemist✨ on Medium]]></title>
        <description><![CDATA[Stories by Mobile Alchemist✨ on Medium]]></description>
        <link>https://medium.com/@aman1024?source=rss-d0a57d0703b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AG1THw7fnofc8Zjo-a1-Sw.png</url>
            <title>Stories by Mobile Alchemist✨ on Medium</title>
            <link>https://medium.com/@aman1024?source=rss-d0a57d0703b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 02:55:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aman1024/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[Bottom Nav integration in NewsApp | Part-1]]></title>
            <link>https://medium.com/@aman1024/bottom-nav-integration-in-newsapp-part-1-4bb868b8f62f?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4bb868b8f62f</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[bottomnavigationview]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 15:27:12 GMT</pubDate>
            <atom:updated>2025-08-17T15:59:52.219Z</atom:updated>
            <content:encoded><![CDATA[<p>🆒 so this is part 1 of building a compose News App based on clean Arch, <br> so i thought why not start with bottom Nav implementation, since Its going to be the base foundation of navigation in our News App.</p><p>going straight to the point&gt;&gt;&gt; <strong>Whats core component required in building a Bottom Navigation?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PU7LAkXRvD7a_mm0Kd8aAQ.jpeg" /><figcaption>photo by -<strong>IlonaBurschl</strong>(pixabay)</figcaption></figure><h3>There are 4 important pillars to implement a bottom navigation in Compose:</h3><ol><li><strong>Define a Route</strong> : use a Sealed class for flexible, type-safe navigation</li><li><strong>States Management : </strong>NavController is used tracking current screen</li><li><strong>Scaffold Integration</strong> — Predefined slots for UI components</li><li><strong>NavHost Container</strong> — Navigation graph linking routes to screens</li></ol><p>lets dig dive into those Pillar one by one…</p><blockquote>meanwhile if you are interested to dive into Src code Here is my repo link(<a href="https://github.com/aman1sr/Compose-NewsApp-CleanArchitecture/tree/feat/simple_bottom_nav_impl">https://github.com/aman1sr/Compose-NewsApp-CleanArchitecture/tree/feat/simple_bottom_nav_impl</a>)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*IxjujlvNJCyK35lsp8jQxw.gif" /></figure><h3>Route</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ebU9LontR2HjTzJAXhUQcQ.png" /><figcaption>sealed class Route</figcaption></figure><p>Route concept here is similar to that of <strong>url</strong>, it is a <strong>string corresponding to a destination</strong>.</p><p>Now the question is we can also define app route via Enum so <strong>why used Sealed class</strong>🤔🤔</p><p>Using Sealed class has an Advantage that the route can <strong>use different properties</strong> and along with some <strong>meta data</strong>, which allow us having <strong>type safe navigation</strong> unlike enum where ALL routes must have identical property types.</p><p>eg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkIGO51h5PVncY4T9b7pnQ.png" /><figcaption>sealed class Route</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hh2x6nZ5yTQj9hd3sM3lyw.png" /><figcaption>enum class Route</figcaption></figure><h3><strong>States Management</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFPoL2zVS6reZfHB4P8dUQ.png" /><figcaption>Navigation States</figcaption></figure><p>These 4 states work together to create a <strong>smart, reactive navigation system</strong>:</p><ol><li><strong>navController</strong> → Handles navigation operations</li><li><strong>navBackStackEntry</strong> → Tracks current navigation state</li><li><strong>currentDestination</strong> → Provides navigation metadata</li><li><strong>currentScreen</strong> → Maps to your custom Route objects for business logic</li></ol><h3>Scaffold</h3><p>so, why used Scaffold for bottom Navigation integration in our app, Why not Surface?</p><p>Scaffold is a layout structure that has some <strong>Pre-defined slots for common UI elements</strong>, Built-in padding handling for content and Automatic layout management for top bar, bottom bar, floating action button, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dkc69gZDZVN5cymwf71mRw.png" /><figcaption>Scaffold example</figcaption></figure><p>basically a go-to layout container for mobile app case scenario, and sorry! i’m a bit lazy to reinvent the wheel from scratch.</p><h3>NavHost Container</h3><p>NavHost is the final and most important ingredient of our BottomNavigation implementation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*Xheh1_y-mq6x2PZGWkHq7w.gif" /></figure><blockquote>NavHost glues all the route to respective screen together to builds the navigation graph and Shows screens based on NavController state.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k-EImWNfl8nOZUBqxsUXRw.png" /><figcaption>NavHost Container</figcaption></figure><p><strong>What NavHost Actually Does:</strong></p><ol><li><strong>Navigation Graph Builder </strong>— Creates the complete navigation structure</li><li><strong>Screen Router </strong>— Routes to correct screens based on state</li><li><strong>State Synchronizer</strong> — Keeps UI in sync with navigation state</li><li><strong>Lifecycle Manager</strong> — Handles screen lifecycle events</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqyFLfVyP2dPlOM2j8eBKA.gif" /></figure><p><strong>Src Code available</strong> -&gt; (<a href="https://github.com/aman1sr/Compose-NewsApp-CleanArchitecture/tree/feat/simple_bottom_nav_impl">https://github.com/aman1sr/Compose-NewsApp-CleanArchitecture/tree/feat/simple_bottom_nav_impl</a>)</p><h3>I HOPE YOUR GET BETTER INSITE ON BOTTOM NAVIGATION INTEGRATION</h3><p>let me know if theres some points which bother you…</p><p>Don’t Forget me to follow on <strong>Medium</strong>, you can also Follow me on <a href="https://x.com/aman1024_">Twitter</a> too :)<br>Happy Coding😊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*-rNiPOBfjR_Vm1X5Mnoo5w.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4bb868b8f62f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Network Calling in Android via Retrofit, Hilt DI | part-2]]></title>
            <link>https://medium.com/@aman1024/network-calling-in-android-via-retrofit-hilt-di-part-2-caa21afe2c39?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/caa21afe2c39</guid>
            <category><![CDATA[android-hilt]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[hilt-di]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 19:51:36 GMT</pubDate>
            <atom:updated>2025-02-25T10:19:44.122Z</atom:updated>
            <content:encoded><![CDATA[<p>In our previous blog, we explored a simple implementation of Retrofit. Today, we’ll see how the same can be achieved using Hilt in a Compose Project.</p><h3>Quick Recap on Integrating Retrofit</h3><ul><li><strong>Define the API Structure: </strong>Specify the endpoint and request method in your NetworkService interface.</li><li><strong>Create a Retrofit Instance: </strong>Use the Retrofit Builder, passing the following parameters: Base URL, API Key, Gson Converter Factory, Custom OkHttp (optional)</li><li><strong>Generate the NetworkService Instance: </strong>Finally, create an instance of NetworkService using Retrofit to make your request methods (GET/POST) available.</li></ul><blockquote>checkout p1 blog-&gt; <a href="https://medium.com/@aman1024/retrofit-network-calling-using-okhttp-client-authinterceptor-and-httplogginginterceptor-5c07f0063be6">Retrofit Network calling using OkHttp Client</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXRGVPeLvgEg2CHR7aEU-w.jpeg" /><figcaption>src: pixabay(DinydeKort<strong>)</strong></figcaption></figure><h3>Benefits of Hilt Dependency Injection</h3><ul><li>Hilt is built on top of the popular Dagger library</li><li>In Dagger, you would have to manually maintain components (such as those for Activity, Application, etc.), but Hilt provide these predefine binding components for common Android Framework classes (like: Application, Fragment, Activity) automcatically for you.</li><li>Hilt manages component lifecycles automatically for you via scope annotations</li><li>By using Hilt, our code is no longer tied to specific object instantiation. This ensures better reusability and greater flexibility across the application.</li><li>Hilt simplifies testing by making it easier to replace real dependencies with mocks or fakes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhRSWgXaSPabLF6J_-jo9w.png" /><figcaption>Hilt DI</figcaption></figure><h3>Hilt Setup</h3><p>To setup hilt in a Compose project we need to make ensure that Hilt Dependency , kotlin version and kotlinCompilerExtensionVersion must sync. This ensures that the Compose Compiler can process your composable functions correctly and that all dependencies are compatible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dX9Bb1MzF4NVRetgce7j1A.png" /><figcaption>Hilt DI setup</figcaption></figure><h4><strong>Compose BOM</strong>:</h4><ul><li>The Compose BOM pins the versions of all Jetpack Compose libraries so they are known to work together.</li><li>It helps prevent mismatches between different Compose artifacts (like ui, material3, tooling, etc.).</li></ul><h4><strong>kotlinCompilerExtensionVersion</strong></h4><ul><li>This version specifies the Compose Compiler plugin that processes your composable functions.</li><li>It is tightly coupled with the <strong>Kotlin version</strong> because the Compose Compiler is built to work with a specific Kotlin release.</li></ul><h4><strong>JVM Target</strong></h4><ul><li><strong>kotlinOptions { jvmTarget = “17” </strong>This setting configures the target Java bytecode version.</li><li>Compose, like many modern libraries, may use language features (such as inline classes or lambdas) that require a minimum JVM version.</li><li>The JVM target should be compatible with both the Kotlin version and the Compose Compiler, ensuring that the resulting bytecode runs correctly on your target devices.</li></ul><p>Before diving into the plethora of annotations, let’s take a moment to ask:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLg1_P85dUYU-UCL6f5V8w.png" /><figcaption>Core working of Hilt DI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOzvA9OWJ8pN04nD90Zc_w.png" /><figcaption>how Hilt know about Dependecies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMU_VG9VooKf5qIUPTBsDQ.png" /><figcaption>how Hilt provide dependencies</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9y96deqLsmt7RR2Lul15g.png" /><figcaption>Hilt Singleton scope Annotation</figcaption></figure><h3>Hilt implementation</h3><p>Lets see Hilt implementation in our Compose News App:</p><h4>Hilt Application Class</h4><ul><li>@HiltAndroidApp annotation initializes Hilt and triggers code generation for dependency injection in your application.</li></ul><pre>@HiltAndroidApp<br>class NewsApplication : Application() {  <br>    <br>}</pre><h4>Inject dependencies into common Android Fragment classes</h4><ul><li>@AndroidEntryPointgenerates an individual Hilt component for each Android class in your project.</li><li>below code ensures that MainActivity benefit from Hilt’s dependency injection by generating and attaching the proper component to each Android class.</li></ul><blockquote><em>checkout Hierarchy of the components that Hilt generates</em>: <a href="https://developer.android.com/training/dependency-injection/hilt-android#component-hierarchy">google_doc</a></blockquote><pre>@AndroidEntryPoint<br>class MainActivity : ComponentActivity() {<br>    @OptIn(ExperimentalMaterial3Api::class)<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>//        enableEdgeToEdge()<br>        setContent {<br>            ComposeNewsAppTheme {<br>            .....</pre><p>Hilt currently supports the following Android classes:</p><ul><li>Application (using @HiltAndroidApp)</li><li>ViewModel (using @HiltViewModel)</li><li>Activity (using @AndroidEntryPoint)</li><li>Fragment ( — — — — ll — — — — )</li><li>View(— — — — ll — — — — )</li><li>Service ( — — — — ll — — — — )</li><li>BroadcastReceiver ( — — — — ll — — — — )</li></ul><p>When you annotate an Android class with @AndroidEntryPoint, Hilt automatically generates a corresponding component under the hood.</p><p>However, @AndroidEntryPoint is not used for ViewModels and the Application class. For these, Hilt generates special components that are tailored to manage their unique lifecycle requirements.</p><blockquote><strong>Refer to the Google Hilt Cheatsheet: </strong><a href="https://developer.android.com/training/dependency-injection/hilt-cheatsheet">https://developer.android.com/training/dependency-injection/hilt-cheatsheet</a></blockquote><h4>Define Hilt bindings</h4><pre>@HiltViewModel<br>class NewsViewModel @Inject constructor(<br>    private val newsRepository: NewsRepository<br>) : ViewModel() {<br><br>     ....<br>     .......</pre><ul><li>Here, constructor injection is used to provide the NewsRepository dependency.</li></ul><h4>Component Scope</h4><p>By default, bindings in Hilt are unscoped; that is, each time you ask for an unscoped binding, a new instance is provided.<br>Hilt allows a binding to be scoped to a predefined scoped component, e.g.,</p><ul><li>@Singleton</li><li>@ActivityRetainedScoped</li><li>@ViewModelScoped</li><li>@ActivityScoped</li><li>@FragmentScoped</li><li>@ViewScoped</li><li>@ViewScoped</li></ul><pre>@Singleton<br>class NewsRepository @Inject constructor(<br>    private val network : ApiInterface<br>) {<br>    suspend fun getNewsByCountry(){<br>    ....<br>    ..</pre><ul><li>Here NewsRepository is annotated with @Singleton, ensuring that a single instance is used throughout the application&#39;s lifecycle.</li></ul><h4>Provide Hilt Binding information using @Module and @Binds</h4><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>class ApplicationModule {<br>....<br>..</pre><p>Sometimes a class cannot be constructor injected; therefore, we provide Hilt binding information via a Module class annotated with @Module and @InstallIn.</p><p><em>Use </em><em>@Module to define how to provide dependencies that cannot be directly injected via constructors.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8soJoLdwB1y-G8jSDiTeZg.png" /><figcaption>Provide vs Bind in hilt</figcaption></figure><p>Read more: <a href="https://developer.android.com/training/dependency-injection/hilt-android#inject-interfaces"><em>google_doc</em></a></p><h4>Qualifiers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7eIVh0Ngg3MxTEWWcu5Yg.png" /><figcaption>Hilt qualifier</figcaption></figure><pre>@Qualifier<br>annotation class ApiKey<br><br>@Qualifier<br>annotation class BaseUrl</pre><p>in the <a href="https://github.com/aman1sr/Compose-NewsApp/blob/feature_hilt_retrofit/app/src/main/java/com/pahadi/composenewsapp/di/ApplicationModule.kt">ApplicationModule class</a>provideBaseUrl() and provideApiKey() functions both return a String (which could confuse the Hilt compiler). Therefore, qualifiers act as a flag to specify which dependency to inject.</p><p>Qualifiers help Hilt distinguish between different dependencies of the same type by tagging them with unique annotations.</p><pre>    @Singleton<br>    @Provides<br>    fun provideNetworkService(<br>        @BaseUrl baseUrl: String,       // tells Hilt&#39;s compiler where to pick the dependency of BaseUrl<br>        gsonFactory: GsonConverterFactory,<br>        apiKeyInterceptor: ApiKeyInterceptor<br>    ): ApiInterface {</pre><h4>Provide binding information for Retrofit in the Module class</h4><pre>@Module<br>@InstallIn(SingletonComponent::class)<br>class ApplicationModule {<br><br>    @Singleton<br>    @Provides<br>    fun provideGsonConverterFactory(): GsonConverterFactory = GsonConverterFactory.create()<br><br>    @BaseUrl<br>    @Provides<br>    fun provideBaseUrl(): String = Const.BASE_URL<br><br>    @ApiKey<br>    @Provides<br>    fun provideApiKey(): String =<br>        &quot;xyz234234234234234234&quot;        // dummy API key</pre><p>In the code snippet, we provide the dependencies for GsonConverterFactory, BaseUrl, and ApiKey using @Provides methods. These dependencies serve as the three key parameters required by the provideNetworkService() method to create the Retrofit instance</p><blockquote><strong>check above ApplicationModule class</strong>: <a href="https://github.com/aman1sr/Compose-NewsApp/blob/feature_hilt_retrofit/app/src/main/java/com/pahadi/composenewsapp/di/ApplicationModule.kt">https://github.com/aman1sr/Compose-NewsApp/blob/feature_hilt_retrofit/app/src/main/java/com/pahadi/composenewsapp/di/ApplicationModule.kt</a></blockquote><pre>    @Singleton<br>    @Provides<br>    fun provideNetworkService(<br>        @BaseUrl baseUrl: String,<br>        gsonFactory: GsonConverterFactory,<br>        apiKeyInterceptor: ApiKeyInterceptor<br>    ): ApiInterface {<br>        val client = OkHttpClient<br>            .Builder()<br>            .addInterceptor(apiKeyInterceptor)<br>            .build()<br><br>        return Retrofit<br>            .Builder()<br>            .client(client)<br>            .baseUrl(baseUrl)<br>            .addConverterFactory(gsonFactory)<br>            .build()<br>            .create(ApiInterface::class.java)<br>    }</pre><p>The provideNetworkService() which provides the ApiInterface implementation using Retrofit, is scoped with singleton annotation ensuring single instance is used throughout the application’s lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1N2OZLRW8oa5_g-n_-JEg.png" /><figcaption>Hilt</figcaption></figure><p>In above code snippet we can see, the implementation of Constructor injected ApiInterface which is fetched by Hilt via provideNetworkService() present in ApplicationModule class.</p><blockquote>Full SourceCode : <a href="https://github.com/aman1sr/Compose-NewsApp/tree/feature_hilt_retrofit">https://github.com/aman1sr/Compose-NewsApp/tree/feature_hilt_retrofit</a></blockquote><p>Thank you for reading, stay tuned for amazing articles!</p><p>Catch me up on: <a href="https://x.com/aman1024_">x.com/aman1024</a></p><h4><strong>Don’t Forget to </strong>👏👏👏<strong>, and happy coding!</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*31Vknbs0GY0Z_gRa.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caa21afe2c39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nested RecyclerView Multi-ViewType | Part 4]]></title>
            <link>https://medium.com/@aman1024/nested-recyclerview-multi-viewtype-part-4-50fc723ce835?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/50fc723ce835</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[nestedrecyclerview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recylerview]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 17:40:24 GMT</pubDate>
            <atom:updated>2025-01-19T17:40:24.154Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! 🎉</p><p>It’s been an amazing journey exploring RecyclerView series together. We’re wrapping up this series with an exciting finale — a fantastic Spotify-inspired app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NIF4R2xgEeZYLG7HhDkOxQ.jpeg" /><figcaption>src: Pixabay(Nambasi)</figcaption></figure><p>As we discussed in the previous p3 blog about the Parent-Child Adapter relationship in Nested RecyclerView, here we are dealing with <strong>multiple ParentAdapters</strong> — namely, MixesAdapter, MoodAdapter, and RecentPlayedAdapter—each with its unique layout.</p><p>how the series is structured:</p><ol><li><a href="https://medium.com/@aman1024/recyclerview-101-basic-working-with-examples-part-1-58e05ab9bdc7"><strong>RecyclerView Basics 101 Working</strong></a></li><li><a href="https://medium.com/@aman1024/recyclerview-101-migrating-to-listadapter-f2ed4bf17270"><strong>RecyclerView with ListAdapter</strong></a></li><li><a href="https://medium.com/@aman1024/recyclerview-101-nested-recylerview-part-3-f682e40d802c"><strong>Nested RecyclerView Basic Example</strong></a></li><li><strong>Nested RecyclerView with Multiple Views</strong> (You are here 🚀)</li></ol><h3>What’s the Advantage of Nested RecyclerView with Multi-ViewType Compared to a Single ParentAdapter Nested RecyclerView?</h3><p><strong>Answer:</strong> Real-time UI inflation with respect to the viewType received in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*imjdmsx1WEEXBka0upB2Iw.gif" /><figcaption>Multi-ViewType Nested RecyclerView</figcaption></figure><p>will continue our p4 series considering the fact that you have understanding of Parent &amp; Child Adapter concept as discussed in <a href="https://medium.com/@aman1024/recyclerview-101-nested-recylerview-part-3-f682e40d802c"><strong>Nested RecyclerView Basic Example</strong></a></p><h3>Fundamental Concepts of Nested RecyclerView with Multi-ViewType:</h3><ol><li><strong>viewType received in data</strong></li><li><strong>Order of the list</strong></li></ol><h3>viewType Received in Data:</h3><p>If we examine the <a href="https://github.com/aman1sr/NestedRecyclerView_MultiViewType/blob/master/app/src/main/assets/spotify_home.json">spotify_home.json</a> data will notice a viewType field. This field determines the appropriate layout and Adapter assigned to the data.<br>Sample spotify_home json data:</p><pre>{<br>  &quot;viewType&quot;: 11,<br>  &quot;title&quot;: &quot;Mixes for You&quot;,<br>  &quot;items&quot;: [<br>    {<br>      &quot;imageBanner&quot;: &quot;https://i.scdn.co/image/ab67616d0000b27350904eaae45e83944df52cb8&quot;,<br>      &quot;musicName&quot;: &quot;Chill Vibes Mix&quot;,<br>      &quot;musicGenre&quot;: &quot;Lo-fi, Chill&quot;<br>    },<br>    {<br>      &quot;imageBanner&quot;: &quot;https://i.scdn.co/image/ab67616d0000b2730d15432c7d94dd8e5f18085a&quot;,<br>      &quot;musicName&quot;: &quot;Top Hits Mix&quot;,<br>      &quot;musicGenre&quot;: &quot;Pop, Rock&quot;<br>    },<br>    ...<br>  ]<br>}</pre><p>in Our Project after receiving the above spotify json data in MainActivity we pass it to our SpotifyHomeAdapter here:</p><p>The viewType value determines the layout to inflate before onCreateViewHolder() is called. This is achieved through getItemViewType():</p><pre>override fun getItemViewType(position: Int): Int {<br>    val data = getItem(position).viewType<br>    return data ?: 0<br>}</pre><p><strong>Key Points about </strong><strong>getItemViewType():</strong></p><ul><li>Determines the type of view to inflate for a given position in the RecyclerView.</li><li>The returned viewType is passed as a parameter to onCreateViewHolder().</li></ul><p>based on the viewType parameter received in OncreateViewHolder() appropriate item_layout is inflated and respective view references are stored in the ViewHolder.</p><pre> override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpotifyViewHolder {<br>        val view = when (viewType) {<br>            VIEW_TYPE_MIXES -&gt; LayoutInflater.from(parent.context)<br>                .inflate(R.layout.mixes_layout, parent, false)<br><br>            VIEW_TYPE_MOOD -&gt; LayoutInflater.from(parent.context)<br>                .inflate(R.layout.mood_layout, parent, false)<br><br>            VIEW_TYPE_RECENTLY_PLAYED -&gt; LayoutInflater.from(parent.context)<br>                .inflate(R.layout.recently_played_layout, parent, false)<br><br>            else -&gt; LayoutInflater.from(parent.context)<br>                .inflate(R.layout.mixes_layout, parent, false)<br>        }<br>        return SpotifyViewHolder(view, viewType)<br>    }</pre><p><strong>Real-Time Binding:</strong><br>When a user scrolls, RecyclerView dynamically binds the view and data at the corresponding position through onBindViewHolder().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqhIUuKNbJxdEbDEGgMfjw.jpeg" /></figure><h3>Order of List:</h3><p>The order of the received data plays a crucial role, The JSON structure directly affects the order in the UI.<br>lets understand this with an Example: given below default order of our spotify_home.json data, with view_type = 11 at top, followed by 22, 33 view type</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qwifmpTa6yA3mv_WqmmDA.jpeg" /></figure><p>lets shuffel the data a bit &amp; see the results:<br>the viewtype=22 (which represent recently_played_layout) is now at top followed by viewtype=11 &amp; so on…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hk1skYGIX3Ta_Ny_fQMYyA.jpeg" /></figure><p>The viewType determines which Respective item_layout is created based on order of json data recevied</p><p>&amp; Thats it!! <br> implementing above changes in a Simple NestedRecyclerView will make it Dynamic NestedRecyclerView with multi-viewType.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*imjdmsx1WEEXBka0upB2Iw.gif" /></figure><p>Src Code availabe -&gt; <a href="https://github.com/aman1sr/NestedRecyclerView_MultiViewType"><strong><em>gitHub_repo</em></strong></a></p><h3>I HOPE YOUR GET BETTER INSITE ON WORKING OF RecyclerView.</h3><h3>Thanks For Reading, Really appreciate your time.</h3><p>Don’t Forget me to follow on <strong>Medium</strong>, you can also Follow me on <a href="https://www.youtube.com/@mobile-alchemist">Youtube</a>, <a href="https://x.com/aman1024_">Twitter</a> too :)</p><p><strong>References:</strong></p><ul><li><a href="https://blog.mindorks.com/recyclerview-multiple-view-types-in-android/">Article Link: medium Amit Shekhar</a></li><li><a href="https://theminimaldev.medium.com/a-clean-way-to-do-multi-viewtype-recyclerviews-on-android-223510d2c65">Article Link: medium Abhishek Jangra</a></li><li><a href="https://medium.com/nerd-for-tech/nested-recyclerview-in-android-e5afb2b9771a">Article Link: medium</a></li><li><a href="https://github.com/aman1sr/NestedRecyclerView_MultiViewType/blob/master/app/src/main/assets/spotify_home.json">Spotify json Data:</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50fc723ce835" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView 101 : Nested RecylerView | Part-3]]></title>
            <link>https://medium.com/@aman1024/recyclerview-101-nested-recylerview-part-3-f682e40d802c?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f682e40d802c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[nestedrecyclerview]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 14:20:21 GMT</pubDate>
            <atom:updated>2025-01-20T10:27:18.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nested RecylerView with Basic Example | Part-3</h3><p><strong>Wola!</strong> Welcome to Part 3 of the RecyclerView series. <br>In the previous parts we have covered: Core components of RecyclerView, use of ListAdapter class to make RecyclerView more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiFOWj26HLWNzIE-IhUVrA.jpeg" /><figcaption>src: pixabay(rdur)</figcaption></figure><p>In this <strong>RecyclerView series</strong>, we’ll dive deep into the Nested RecylerView Concept. Here’s how the series is structured:</p><ol><li><a href="https://medium.com/@aman1024/recyclerview-101-basic-working-with-examples-part-1-58e05ab9bdc7"><strong>RecyclerView Basics 101 Working</strong></a></li><li><a href="https://medium.com/@aman1024/recyclerview-101-migrating-to-listadapter-f2ed4bf17270"><strong>RecyclerView with ListAdapter</strong></a></li><li><strong>Nested RecyclerView Basic Example</strong> (You are here 🚀)</li><li><a href="https://medium.com/@aman1024/nested-recyclerview-multi-viewtype-part-4-50fc723ce835"><strong>Nested RecyclerView with Multiple Views</strong></a></li></ol><h3>Fundamental Idea of Nested RecyclerView</h3><p>One RecyclerView (parent) contains another RecyclerView (child) inside its items.</p><p>For a nested RecyclerView, your JSON data must support hierarchical relationships. Typically, a <strong>List&lt;List&lt;Data&gt;&gt;</strong> format works best.</p><p>In GOT project, used a <strong>custom JSON file</strong> (<a href="https://github.com/aman1sr/basic-NestedRecylerView/blob/master/app/src/main/assets/got_quotes.json">got_quotes.json</a> stored in the assets folder) converted into the respective model classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*EIRJ_ESk9_6vepmrmEMpZQ.gif" /><figcaption>Nested RecyclerView</figcaption></figure><h3>Project Structure</h3><p><strong>GOT app Nested RecyclerView</strong> setup involves two primary adapters:</p><ol><li><strong>ParentAdapter</strong>: Manages the parent RecyclerView (vertical scrolling).</li><li><strong>ChildAdapter</strong>: Manages the child RecyclerView within each parent item (horizontal scrolling).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoKkIdGZ2EuisMKnI8WOXg.jpeg" /></figure><h3>UI Structure</h3><p><strong>MainActivity Layout</strong>:<br>Acts as the base container, hosting the parent RecyclerView (parent_recycler_view) with a vertical layout.</p><p><strong>ParentAdapter Layout</strong>:<br>Contains a TextView (e.g., House name) and another RecyclerView (rv_child) with a horizontal layout.</p><p><strong>ChildAdapter Layout</strong>:<br>Displays individual child items, such as member names</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSqteLzXe3Rl6vIIpx2Vmg.jpeg" /></figure><h3>Model Class</h3><p>We create three data models:</p><ol><li><strong>GotResponse</strong> : contains List&lt;GOTResponseItem&gt; <br>- we extract this data from <a href="https://github.com/aman1sr/basic-NestedRecylerView/blob/master/app/src/main/assets/got_quotes.json">got_quotes.json</a> in MainActivity<br>- passing List&lt;GOTResponseItem&gt; to initialize ParentAdapter</li><li><strong>GOTResponseItem</strong>: Represents each house containing a List&lt;Members&gt; in ParentAdapter.</li><li><strong>Member</strong>: Represents individual members of a house in ChildAdapter</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3TeoQrxO3H6tc4pwWPR1LQ.jpeg" /><figcaption>got_quotes.json</figcaption></figure><h3>Adapter Implementation</h3><p><strong>MainActivity</strong>:<br>Fetches data (from JSON or API) and initializes the ParentAdapter.</p><pre>private fun setUpParentHouseAdapter(gotResponse: List&lt;GOTResponseItem&gt;) {<br>    val adapter = ParentHouseAdapter()<br>    adapter.submitList(gotResponse)<br>    binding.parentRecyclerView.layoutManager = LinearLayoutManager(this)<br>    binding.parentRecyclerView.adapter = adapter<br>}</pre><p><strong>ParentAdapter</strong>:<br>Sets up the child RecyclerView with a horizontal layout inside its ViewHolder.</p><pre>inner class ParentViewHolder(view: ItemRowParentBinding) : RecyclerView.ViewHolder(view.root) {<br>    private val childAdapter = ChildMemberAdapter()<br><br>    init {<br>        view.rvChild.layoutManager = LinearLayoutManager(view.root.context, LinearLayoutManager.HORIZONTAL, false)<br>        view.rvChild.adapter = childAdapter<br>    }<br><br>    fun bind(houseItem: GOTResponseItem) {<br>        view.txtHouseName.text = houseItem.name<br>        childAdapter.submitList(houseItem.members)<br>    }<br>}</pre><p><strong>ChildAdapter</strong>:<br>Handles the member data and binds it to the TextView.</p><pre>override fun onBindViewHolder(holder: ChildViewHolder, position: Int) {<br>    holder.txtName.text = getItem(position).name<br>}</pre><p>AND Wola!!! Our Basic Implementation of Nested RecylerView is Ready.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*EIRJ_ESk9_6vepmrmEMpZQ.gif" /><figcaption>Basic Nested RecyclerView</figcaption></figure><p>Src Code availabe -&gt; <a href="https://github.com/aman1sr/basic-NestedRecylerView"><strong><em>gitHub_repo</em></strong></a></p><h3>I HOPE YOUR GET BETTER INSITE ON WORKING OF RecyclerView, Stay tuned for Part-4.</h3><p>Don’t Forget me to follow on <strong>Medium</strong>, you can also Follow me on <a href="https://www.youtube.com/@mobile-alchemist">Youtube</a>, <a href="https://x.com/aman1024_">Twitter</a> too :)</p><p><strong>References:</strong></p><ul><li><a href="https://medium.com/nerd-for-tech/nested-recyclerview-in-android-e5afb2b9771a">Article Link: medium NestedRecView</a></li><li><a href="https://medium.com/androiddevelopers/adapting-to-listadapter-341da4218f5b">Article Link: medium ListAdapter</a></li><li><a href="https://developer.android.com/reference/androidx/recyclerview/widget/ListAdapter">Article Link: listAdpater doc</a></li><li><a href="https://gameofthronesquotes.xyz/">GOT json Data:</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f682e40d802c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView 101: Migrating to ListAdapter]]></title>
            <link>https://medium.com/@aman1024/recyclerview-101-migrating-to-listadapter-f2ed4bf17270?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2ed4bf17270</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[listadapter]]></category>
            <category><![CDATA[recylerview-adapter]]></category>
            <category><![CDATA[recylerview]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 10:23:09 GMT</pubDate>
            <atom:updated>2025-01-20T10:31:37.531Z</atom:updated>
            <content:encoded><![CDATA[<p>In <strong>Part 1</strong>, we explored the core components of RecyclerView, focusing on how the Adapter class plays a crucial role in creating and binding views.</p><p>In this <strong>RecyclerView series</strong>, we’ll dive deep into the ListAdapter API. Here’s how the series is structured:</p><ol><li><a href="https://medium.com/@aman1024/recyclerview-101-basic-working-with-examples-part-1-58e05ab9bdc7"><strong>RecyclerView Basics 101 Working</strong></a></li><li><strong>RecyclerView with ListAdapter</strong> (You are here 🚀)</li><li><a href="https://medium.com/@aman1024/recyclerview-101-nested-recylerview-part-3-f682e40d802c"><strong>Nested RecyclerView Basic Example</strong></a></li><li><a href="https://medium.com/@aman1024/nested-recyclerview-multi-viewtype-part-4-50fc723ce835"><strong>Nested RecyclerView with Multiple Views</strong></a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPw1I_oNNwrhqDLfwzBv3g.jpeg" /><figcaption>src: pixabay-andreasgoellner</figcaption></figure><p>To recap briefly, we passed the list data via the NewsAdapter constructor. which is ok as long as our List deals with static data, for some simple operation of addition/deletion of item, we can notify the adapter by some build-in functions like notifyDataSetChanged(), notifyItemInserted(position), or notifyItemRemoved(position).</p><blockquote>particularly <strong>notifyDataSetChanged</strong>() is an expensive operation since it redraws the entire view, even the unchanged parts.</blockquote><p>But when dealing dynamic data which changes real time, such as news fetched from APIs of NDTV, above approch is inefficient.</p><p>This is where Google’s <strong>ListAdapter</strong> steps in to simplify and optimize the process.</p><h3>Benefits of Using ListAdpater:</h3><ol><li><strong>ListAdpater automatically handles list</strong> addition and removal with smooth animation, eliminating the need for manual handling via notifyDataSetChanges()</li><li><strong>Leverages DiffUtils for List Comparision</strong><br>- DiffUtils is a wrapper around AsyncDiffUtils which computes difference between 2 list in background thread keeping UI responsive.<br>- Uses Mayer’s Algorithm to calculate difference between 2 list with time complexity O(ND), where N is the list size &amp; D is the number of differences.<br>- Determines the <strong>minimal set of changes</strong> (insertions, deletions, updates) required to transform the old list into the new one.</li><li><strong>Simplify Data Handling</strong><br>- No need to pass data through the adapter’s constructor anymore; you can simply update the list using the submitList() function.</li><li><strong>No Need for getItemCount() </strong><br>- the size of the list is automatically managed by DiffUtils</li></ol><p>Too much taking lets see what changes we needed to make in previous project (<a href="https://github.com/aman1sr/SimpleRecycleView/tree/simple_rec_view">gitHub</a>) to migrate from a regular Adapter to ListAdapter</p><h3>we need to make four key changes in our project:</h3><h4>1. Update Adapter Class Structure</h4><pre>// Old Adapter<br>class NewsAdapter(val newsList: List&lt;NewsResponse&gt;) : RecyclerView.Adapter&lt;NewsViewHolder&gt;()<br><br>// New Adapter<br>class NewsAdapter() : ListAdapter&lt;NewsResponse, NewsViewHolder&gt;(diffUtils)  // ListAdapter constructor requires a DiffUtil.ItemCallback implementation to compare list items.</pre><h4>2. Implement DiffUtil</h4><blockquote><strong>NOTE</strong>: wrt Part1 project i have added an <strong>id</strong> field in NewsResponse Model, which is used in given below <strong>areItemsTheSame</strong>() for comarison between 2 list</blockquote><p>updated static Data : <a href="http://areitemsthesame/">link</a><br>updated modal class: <a href="https://github.com/aman1sr/SimpleRecycleView/blob/listadapter/app/src/main/java/com/example/recinrecview/model/NewsResponse.kt">link</a></p><pre>object diffUtils : DiffUtil.ItemCallback&lt;NewsResponse&gt;() {<br>    override fun areItemsTheSame(oldItem: NewsResponse, newItem: NewsResponse): Boolean {<br>        return oldItem.id == newItem.id // Compare unique identifiers<br>    }<br><br>    override fun areContentsTheSame(oldItem: NewsResponse, newItem: NewsResponse): Boolean {<br>        return oldItem == newItem // Check if content has changed<br>    }<br>}</pre><h4>3. Update onBindViewHolder &amp; Remove getItemCount</h4><pre>override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {<br>    val news = getItem(position) // Fetch the current item<br>    ...<br>}<br><br>// override fun getItemCount(): Int {<br>//     return newsList.size<br>// }</pre><h4>4. Update the Data Input Process</h4><pre>private fun setupRecyclerView() {<br>    Utils.getStaticNewsData()?.let {<br>        binding.recView.adapter = NewsAdapter().apply {<br>            submitList(it)      // Update the list<br>        }<br>        binding.recView.layoutManager = LinearLayoutManager(this@MainActivity)<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*30x26p66LOHYxo1oFMV8Vg.png" /></figure><p>AND Wola!!! Our ListAdapter based RecylerView is Ready.</p><p>Src Code availabe -&gt; <a href="https://github.com/aman1sr/SimpleRecycleView/tree/listadapter"><strong><em>gitHub_repo</em></strong></a></p><h3>I HOPE YOUR GET BETTER INSITE ON WORKING OF RecyclerView,</h3><p><a href="https://medium.com/@aman1024/recyclerview-101-nested-recylerview-part-3-f682e40d802c"><strong>Visit Part-3 to understand Basic concept of NestedRecylerView</strong></a><strong> </strong>👈</p><h3>Don’t Forget me to follow on <strong>Medium</strong>, you can also Follow me on <a href="https://www.youtube.com/@mobile-alchemist">Youtube</a>, <a href="https://x.com/aman1024_">Twitter</a> too :)</h3><p><strong>References:</strong></p><ul><li><a href="https://medium.com/geekculture/android-listadapter-a-better-implementation-for-the-recyclerview-1af1826a7d21">https://medium.com/geekculture/android-listadapter-a-better-implementation-for-the-recyclerview-1af1826a7d21</a></li><li><a href="https://medium.com/androiddevelopers/adapting-to-listadapter-341da4218f5b">https://medium.com/androiddevelopers/adapting-to-listadapter-341da4218f5b</a></li><li><a href="https://bignerdranch.com/blog/efficient-lists-with-diffutil-and-listadapter/">https://bignerdranch.com/blog/efficient-lists-with-diffutil-and-listadapter/</a></li><li><a href="https://medium.com/tech-carnot/making-recyclerview-efficient-using-list-adapter-with-diffutil-4a06d4583ea4">https://medium.com/tech-carnot/making-recyclerview-efficient-using-list-adapter-with-diffutil-4a06d4583ea4</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2ed4bf17270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerView 101: Basic Working with Examples | Part 1]]></title>
            <link>https://medium.com/@aman1024/recyclerview-101-basic-working-with-examples-part-1-58e05ab9bdc7?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/58e05ab9bdc7</guid>
            <category><![CDATA[recylerview-adapter]]></category>
            <category><![CDATA[recyclerview-101]]></category>
            <category><![CDATA[recylerview]]></category>
            <category><![CDATA[viewholder]]></category>
            <category><![CDATA[recyclerview-basics]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Thu, 12 Dec 2024 11:18:24 GMT</pubDate>
            <atom:updated>2025-01-19T18:02:38.347Z</atom:updated>
            <content:encoded><![CDATA[<p>RecyclerView is a <strong>modern approach</strong> in Android for efficiently displaying lists or grids of views. It <strong>reuses views</strong>, reducing memory overhead, and provides a much smoother experience compared to its predecessor, <strong>ListView</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQgZzvpEaqMGzxV7T_mNgA.png" /></figure><p>In this <strong>RecyclerView series</strong>, we’ll dive deep into the RecyclerView API. Here’s how the series is structured:</p><ol><li><strong>RecyclerView Basics 101 Working</strong> (You are here 🚀)</li><li><a href="https://medium.com/@aman1024/recyclerview-101-migrating-to-listadapter-f2ed4bf17270"><strong>RecyclerView with ListAdapter</strong></a></li><li><a href="https://medium.com/@aman1024/recyclerview-101-nested-recylerview-part-3-f682e40d802c"><strong>Nested RecyclerView Basic Example</strong></a></li><li><a href="https://medium.com/@aman1024/nested-recyclerview-multi-viewtype-part-4-50fc723ce835"><strong>Nested RecyclerView with Multiple Views</strong></a></li></ol><blockquote>Before we jump into the playground, let’s take a moment to familiarize ourselves with the tools we’ll be using.</blockquote><h3>The 3 Core Components of RecyclerView</h3><ol><li><strong>RecylerView.Adapter</strong> (the bridge bw data and View)</li><li><strong>LayoutManager </strong>(the manager who decides how views will be positioned on the Screen)</li><li><strong>ViewHolder</strong> (the real beauty of RecylerView =&gt; ReUsing Views)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cj1QqyU1DltM0FSG2R7pEA.png" /><figcaption>src: Google</figcaption></figure><h3>RecylerView.Adapter</h3><p>The <strong>Adapter</strong> in RecyclerView is responsible for:</p><ol><li><strong>Inflating the item layout</strong> (the individual views in the list/grid).</li><li><strong>Creating ViewHolder objects</strong> to hold references to the views.</li><li><strong>Binding data to these views.</strong></li></ol><p>It provides three key methods:</p><ul><li><strong>onCreateViewHolder()</strong>:<br> inflate the item-layout <strong>once</strong>, and it returns a ViewHolder that holds references to the views inside the layout.</li></ul><blockquote>NOTE: <br>In RecyclerView, the term <strong>View</strong> refers to an individual element of the list, which here is defined by an <strong>item-layout</strong> XML file, I sometime uses <strong>item-layout </strong>more often for better convenience for beginners understanding.</blockquote><ul><li><strong>onBindViewHolder()</strong>:<br>It is the <strong>final step </strong>in Adapter where the data binds to the views referenced by the ViewHolder. after binding process the particular View/item-layout is ready to be displayed on Screen.</li><li><strong>getItemCount()</strong>:<br>This tells the Adapter how many items are in the list. Based on this, RecyclerView calculates how many views are needed and ensures only the visible ones are created or updated.</li></ul><p>The views created by the Adapter are handed over to the <strong>LayoutManager</strong>, which determines their alignment and positioning on the screen.</p><h3>LayoutManager:</h3><p>The <strong>LayoutManager</strong> is like a <strong>manager</strong> of a restaurant, ensuring everything is in order:</p><ol><li><strong>Positioning the items</strong> — Linear/Grid/Staggered Grid</li><li>While <strong>aligning items</strong>, it works with the Adapter methods to get the data and bind it to the views.</li></ol><h4>ViewHolder: The Key to Efficiency</h4><p>The <strong>ViewHolder</strong> is where RecyclerView shines. It:</p><ul><li>Holds references to the views in an item-layout, reducing the need to call findViewById repeatedly.</li><li>Reuses these views when they move off-screen, eliminating the need to create new views for every item in OnBindViewHolder.</li></ul><blockquote>To put it simply, <strong>ViewHolder acts like a data class for views</strong>.</blockquote><p>Too Much Theory lets get our hand on Code:</p><p>here will provide the code Snippet along with Explanation of imp component, you can anytime refer to the <strong>full SrcCode -&gt;</strong><a href="https://github.com/aman1sr/RecycleInRecyclerView/tree/simple_rec_view"><strong> droid-aman</strong></a></p><h3>SetUP RecylerView xml:</h3><pre>&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>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/main&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br>&lt;androidx.recyclerview.widget.RecyclerView<br>    android:id=&quot;@+id/recView&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:listitem=&quot;@layout/news_item&quot;<br>    /&gt;<br><br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><h3>The Data Source:</h3><p>After we are fetching our list of dummy News data from Utils file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z30ulsQByfADqJfy9vfEQA.png" /></figure><h3>SetUp LayoutManger &amp; pass Data to Adapter</h3><p>we provide the list of News data to <strong>Adapter class</strong> for binding it with our Views and set our <strong>LayoutManger</strong> to LinearLayoutManager ( to position our item on screen in Linear order)</p><pre>    private fun setupRecyclerView() {<br>        Utils.getStaticNewsData()?.let {<br>         binding.recView.adapter = NewsAdapter(it)<br>        binding.recView.layoutManager = LinearLayoutManager(this@MainActivity)<br>        }<br>    }</pre><h3>Adapter class:</h3><p><strong>onCreateViewHolder</strong> -&gt; inflate <strong>news_item.xml </strong>and pass the reference to ViewHolder for holding the reference for binding.</p><p><strong>onBindViewHolder</strong> -&gt; takes the news item specific position data (laid on Screen) and binds it with the ViewHolder reference view</p><p><strong>getItemCount</strong> -&gt; tells Adapter how many items are in the list</p><pre> class NewsAdapter(val newsList: List&lt;NewsResponse&gt;): RecyclerView.Adapter&lt;NewsViewHolder&gt;() {<br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {<br>        val view = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false)<br>        return NewsViewHolder(view)<br>    }<br><br>    override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {<br>       val news = newsList.get(position)<br>        holder.newsTitle.text = news.newsTitle<br>        holder.newsDesc.text = news.newsDesc<br>        Glide.with(holder.newsimg.context)<br>            .load(news.img)<br>            .placeholder(R.drawable.news_placeholder)<br>            .centerCrop()<br>            .into(holder.newsimg)<br>    }<br><br>    override fun getItemCount(): Int {<br>        return newsList.size<br>    }<br>}</pre><h3><strong>ViewHolder class</strong></h3><p>The ViewHolder class holds the references to some of the views from <strong>news_item.xml, </strong>reducing the need to call findViewById repeatedly.</p><p>It is a good pratice to place precompute frequently used values resources code inside ViewHolder class so to minimise heavy operation inside onBindViewHolder.</p><pre>class NewsViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){<br>    val newsTitle = itemView.findViewById&lt;TextView&gt;(R.id.txt_title)<br>    val newsDesc = itemView.findViewById&lt;TextView&gt;(R.id.txt_desc)<br>    val newsimg = itemView.findViewById&lt;ImageView&gt;(R.id.img_news)<br>}</pre><p>AND Wola!!! Our RecylerView is Ready.</p><figure><img alt="RecylerView List" src="https://cdn-images-1.medium.com/max/727/1*VTMcuAlDpLoiQnrcTdirQA.png" /></figure><p>Src Code availabe -&gt; <a href="https://github.com/aman1sr/RecycleInRecyclerView/tree/simple_rec_view"><strong>GitHub_repo</strong></a></p><h3>I HOPE YOUR GET BETTER INSITE ON WORKING OF RecyclerView,</h3><p><a href="https://medium.com/@aman1024/recyclerview-101-migrating-to-listadapter-f2ed4bf17270"><strong>Visit Part-2 to understand concept of ListAdapter </strong></a>👈</p><p>Don’t Forget me to follow on <strong>Medium</strong>, you can also Follow me on <a href="https://www.youtube.com/@mobile-alchemist">Youtube</a>, <a href="https://x.com/aman1024_">Twitter</a> too :)</p><h3>References:</h3><ul><li><a href="https://medium.com/1mgofficial/how-recyclerview-works-internally-71290de5d2c4">https://medium.com/1mgofficial/how-recyclerview-works-internally-71290de5d2c4</a></li><li><a href="https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/RecyclerView">https://developer.android.com/reference/kotlin/androidx/recyclerview/widget/RecyclerView</a></li><li><a href="https://guides.codepath.com/android/using-the-recyclerview">https://guides.codepath.com/android/using-the-recyclerview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58e05ab9bdc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bottom Navigation Playground: creating dynamic menu (Part 3)]]></title>
            <link>https://medium.com/@aman1024/bottom-navigation-playground-creating-dynamic-menu-part-3-a242f7499541?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a242f7499541</guid>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 17:57:38 GMT</pubDate>
            <atom:updated>2024-11-26T18:13:02.926Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the third installment of the <strong>Bottom Navigation Playground</strong> series! In this article We’ll explore how to dynamically inflate menu items, manage their checked/unchecked states, and customize the text label and icon appearances programmatically. Let’s get started!</p><p>in Part2 of series we see BottomNavigationView uses XML attributes to define menu items, text, and icon states. However, this approach can be limiting, especially when your app needs dynamic updates like real-time menu changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5FebGGorPHSGIa7zbcn1w.jpeg" /></figure><h3>Removing Static XML Attributes</h3><p>To dynamically control the appearance of the BottomNavigationView, first, we need to strip away static XML attributes. Here’s an example of what needs to be commented out:</p><pre>&lt;!--<br>    app:itemIconTint=&quot;@drawable/nav_icon_color&quot;<br>    app:itemTextAppearanceActive=&quot;@style/BottomNavigationTextView.Active&quot;<br>    app:itemTextAppearanceInactive=&quot;@style/BottomNavigationTextView&quot;<br>    app:labelVisibilityMode=&quot;labeled&quot;<br>--&gt;<br>&lt;com.google.android.material.bottomnavigation.BottomNavigationView<br>    android:id=&quot;@+id/bottom_navigation&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_gravity=&quot;bottom&quot; /&gt;</pre><blockquote>GitHub sourcecode: <a href="https://github.com/aman1sr/bottomNavigation-playground/tree/dynamic_menu">https://github.com/aman1sr/bottomNavigation-playground/tree/dynamic_menu</a></blockquote><h3>Dynamically Adding Menu Items</h3><p>Here’s how we can add items dynamically to the BottomNavigationView using Kotlin</p><pre>lifecycleScope.launch {<br>    getBottomNavData().collect { menuDataList -&gt;<br>        setupDynamicBottomNavMenu(menuDataList)<br>    }<br>}<br><br>private fun setupDynamicBottomNavMenu(menuDataList: List&lt;NavMenuData&gt;) {<br>    val bottomNavView = binding?.bottomNavigation<br><br>    bottomNavView?.menu?.clear()<br><br>    menuDataList.forEachIndexed { index, navMenuData -&gt;<br>        bottomNavView?.menu?.add(0, index, index, navMenuData.title)?.apply {<br>            setIcon(navMenuData.image) // Set the icon<br>            isCheckable = true         // Ensure the item is checkable<br>        }<br>    }<br>}</pre><h4><strong>Let’s break down the </strong><strong>menu.add method:</strong></h4><ul><li><strong>groupId (0)</strong>: Identifies the group for the menu item. Use 0 for no grouping.</li><li><strong>itemId (index)</strong>: A unique ID for the menu item, essential for callbacks.</li><li><strong>order (index)</strong>: Defines the menu item&#39;s order in the list.</li><li><strong>title (</strong><strong>navMenuData.title)</strong>: Sets the visible title for the menu item.</li></ul><p><strong>Wolaa!!</strong> The menu is now dynamically populated with items fetched at runtime.</p><h3>Customizing Active and Inactive States</h3><p>Customizing how the menu looks when items are active or inactive adds polish to your app’s UI. Here’s how you can do this dynamically.</p><h3>Icon Tint Customization</h3><p>We use the ColorStateList class to create color states for active and inactive icons:</p><pre>private fun createIconTintStateList(<br>    activeColor: Int,<br>    inactiveColor: Int<br>): ColorStateList {<br>    val states = arrayOf(<br>        intArrayOf(android.R.attr.state_checked), // Active state<br>        intArrayOf()                              // Inactive state<br>    )<br>    val colors = intArrayOf(<br>        activeColor,  // Active icon color<br>        inactiveColor // Inactive icon color<br>    )<br>    return ColorStateList(states, colors)<br>}<br><br>// Apply to BottomNavigationView<br>val iconTintList = createIconTintStateList(<br>    activeColor = ContextCompat.getColor(this, R.color.primaryColor),<br>    inactiveColor = ContextCompat.getColor(this, R.color.black)<br>)<br>bottomNavView?.itemIconTintList = iconTintList</pre><h3>Text Label Customization</h3><p>Text label colors can also be set programmatically using a similar approach:</p><pre>private fun assignTextColorsToMenu(txtCheckColor: Int, txtUncheckedColor: Int) {<br>    val bottomNavView = binding?.bottomNavigation<br><br>    val states = arrayOf(<br>        intArrayOf(android.R.attr.state_checked),  // Active state<br>        intArrayOf()                              // Inactive state<br>    )<br><br>    val colors = intArrayOf(<br>        ContextCompat.getColor(this, txtCheckColor),   // Active text color<br>        ContextCompat.getColor(this, txtUncheckedColor) // Inactive text color<br>    )<br><br>    val colorStateList = ColorStateList(states, colors)<br>    bottomNavView?.setItemTextColor(colorStateList)<br>}</pre><p><strong>Outcome:</strong> Icons and text labels dynamically reflect active/inactive states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*RJX2UuheTec6fopjN607Mg.png" /></figure><h3>What’s Next? Part 4 Teaser</h3><p>In <strong>Part 4</strong>, we’ll take this to the next level! where menus are not tinted based on ColorStateList but are provided with separate icons for active and inactive states. We’ll explore handling a more complex six-menu system, ensuring seamless updates and real-time state changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a242f7499541" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bottom Navigation Playground: Handling Various Scenarios (Part 1)]]></title>
            <link>https://medium.com/@aman1024/bottom-navigation-playground-handling-various-scenarios-part-1-60cea5223f08?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/60cea5223f08</guid>
            <category><![CDATA[bottomnavigationview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[bottomnavigationbar]]></category>
            <category><![CDATA[bottom-navigation]]></category>
            <category><![CDATA[material-design]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 18:16:15 GMT</pubDate>
            <atom:updated>2024-11-26T17:44:04.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Bottom navigation is a staple in modern mobile app design, providing users with quick access to top-level destinations in an intuitive manner. Most applications adopt it as a core navigation component, thanks to its alignment with Material Design principles and ease of use. In this guide, we’ll explore a three-step implementation of bottom navigation, comparing the old and new approaches to handling menu click events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SQ-oQZWCImf_b2rid2l1Vw.png" /><figcaption>Android BottomNavigation</figcaption></figure><h3>Table of Contents</h3><ol><li><a href="#step-1-creating-the-menu-resource">Creating the Menu Resource</a></li><li><a href="#step-2-adding-the-bottom-navigation-view-in-xml">Adding the Bottom Navigation View in XML</a></li><li><a href="#step-3-inflating-and-setting-click-events">Inflating and Setting Click Events</a></li></ol><h3>3 steps implementation of Bottom Navigation:</h3><ol><li>creating an xml menu resource ( which contain your bottom navigation items)</li><li>adding an xml resource of BottomNavigationView &amp; setting menu atttibute</li><li>inflating botom Navigation view &amp; setting its onMenu click event</li></ol><blockquote><strong>Github Src code </strong>: <a href="https://github.com/aman1sr/bottomNavigation-playground/tree/master">https://github.com/aman1sr/bottomNavigation-playground/tree/master</a></blockquote><h3>Step 1: Creating the Menu Resource</h3><p>The first step in implementing a bottom navigation bar is creating an XML menu resource. This file defines the items that will appear in the navigation bar.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br><br>    &lt;item<br>        android:id=&quot;@+id/item_rose&quot;<br>        android:icon=&quot;@drawable/ic_rose&quot;<br>        android:title=&quot;Rose&quot; /&gt;<br><br>    &lt;item<br>        android:id=&quot;@+id/item_lilly&quot;<br>        android:icon=&quot;@drawable/ic_lilly&quot;<br>        android:title=&quot;Lilly&quot; /&gt;<br><br>    &lt;item<br>        android:id=&quot;@+id/item_tulip&quot;<br>        android:icon=&quot;@drawable/ic_tulip&quot;<br>        android:title=&quot;Tulip&quot; /&gt;<br><br>&lt;/menu&gt;</pre><h3>Step 2: Adding the Bottom Navigation View in XML</h3><p>Next, include a BottomNavigationView in your layout XML file and link it to the menu resource created earlier.</p><pre>&lt;com.google.android.material.bottomnavigation.BottomNavigationView<br>    android:id=&quot;@+id/bottom_navigation&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_gravity=&quot;bottom&quot;<br>    app:menu=&quot;@menu/bottom_menu&quot;<br>/&gt;</pre><h3>Step 3: Inflating and Setting Click Events</h3><p>Inflating the bottom navigation view is straightforward, especially if you use view binding. However, the real task lies in handling menu item clicks.</p><h4>Old Approach: Using OnNavigationItemSelectedListener</h4><p>Old way of setting menu item click involve implementing BottomNavigationView.OnNavigationItemSelectedListener</p><p>giving the reference of current activity as:</p><p>binding?.bottomNavigation?.setOnItemSelectedListener(this)</p><p>then ovveride onNavigationItemSelectedfunction to handle the menu click event:</p><pre>override fun onNavigationItemSelected(item: MenuItem): Boolean {<br>    when (item.itemId) {<br>        R.id.item_rose -&gt; { /* Handle Rose */ return true }<br>        R.id.item_lilly -&gt; { /* Handle Lilly */ return true }<br>        R.id.item_tulip -&gt; { /* Handle Tulip */ return true }<br>    }<br>    return false<br>}</pre><blockquote>NOTE: OnNavigationItemSelectedListener is depricated</blockquote><h4>New Approach: Directly Setting the Listener</h4><p>The recommended approach is to directly set an OnItemSelectedListener on the BottomNavigationView. Here’s the implementation:</p><pre>binding?.bottomNavigation?.setOnItemSelectedListener { menu -&gt;<br>    when (menu.itemId) {<br>        R.id.item_rose -&gt; {<br>            supportFragmentManager.beginTransaction()<br>                .replace(R.id.main_container, RoseFragment())<br>                .commit()<br>            true<br>        }<br>        R.id.item_tulip -&gt; {<br>            supportFragmentManager.beginTransaction()<br>                .replace(R.id.main_container, TulipFragment())<br>                .commit()<br>            true<br>        }<br>        R.id.item_lilly -&gt; {<br>            supportFragmentManager.beginTransaction()<br>                .replace(R.id.main_container, LilyFragment())<br>                .commit()<br>            true<br>        }<br>        else -&gt; false<br>    }<br>}</pre><p>To set the default item selection (e.g., Rose), add this line after the listener:</p><pre>binding?.bottomNavigation?.selectedItemId = R.id.item_rose</pre><figure><img alt="BottomNavigation items" src="https://cdn-images-1.medium.com/max/770/1*RJX2UuheTec6fopjN607Mg.png" /></figure><h3>Conclusion</h3><p>Bottom navigation is a crucial component of modern Android apps, offering users seamless navigation with minimal effort.</p><p>Stay tuned for Part 2, where we’ll tackle advanced scenarios, including dynamic menu updates and deep-linking integration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60cea5223f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit Network calling using OkHttp Client, AuthInterceptor, and HttpLoggingInterceptor]]></title>
            <link>https://medium.com/@aman1024/retrofit-network-calling-using-okhttp-client-authinterceptor-and-httplogginginterceptor-5c07f0063be6?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c07f0063be6</guid>
            <category><![CDATA[authinterceptor]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[httplogginginterceptor]]></category>
            <category><![CDATA[okhttpclient]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 12:33:09 GMT</pubDate>
            <atom:updated>2024-08-09T13:01:24.242Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of Android development, network communication is a fundamental aspect of most applications. Whether it’s fetching data from a server, posting user-generated content, or syncing information, network calls are an integral part of the user experience. Handling these network operations efficiently and securely can be a complex task, but fortunately, there are powerful libraries like <strong>Retrofit </strong>that make this process much more manageable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGu3QN9ZIwGPmTwY7CzXIQ.jpeg" /></figure><h3>Retrofit Library Introduction</h3><p><strong>Retrofit</strong> is a sophisticated type-safe HTTP client for Android that simplifies network communication.</p><p>One of the key reasons developers prefer Retrofit is its inbuilt support for handling asynchronous requests using <strong>Coroutines</strong>. This allows for cleaner and more readable code, avoiding the complexities of managing threads and callbacks. Additionally, Retrofit’s integration with the<strong> Flow API</strong> opens up a world of reactive programming, enabling developers to handle data streams in a straightforward and declarative manner.</p><p>In this blog post, we’ll explore how to use Retrofit with OkHttp’s AuthInterceptor for handling authentication and HttpLoggingInterceptor for logging network calls. We’ll delve into the setup, configuration, and practical use cases to help you get started with implementing network calls in your applications efficiently.</p><p>We will also Test our Network Calling in 2 Different ways, so Don’t worry Will understand complete working of Retorfit Network calling today.</p><blockquote><strong><em>Src Code availabe at end.</em></strong></blockquote><h3>Setting up Retrofit dependency &amp; Internet permission</h3><p>Add <strong>Retrofit </strong>along with some other libraries in build.gradle.</p><p><em>Don’t worry will let u know the use case of gson-converter and okHttp interceptor library.</em></p><pre>dependencies {<br>    implementation (&quot;com.squareup.retrofit2:retrofit:2.9.0&quot;)<br>    implementation (&quot;com.squareup.retrofit2:converter-gson:2.9.0&quot;)<br>    implementation(&quot;com.squareup.okhttp3:logging-interceptor:4.10.0&quot;)<br>...</pre><p>Add Internet permission in Manifest:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;</pre><h3>Defining the structure of API: endpoint and Request Methods</h3><pre>interface NetworkService {<br><br>    @GET(&quot;top-headlines&quot;)<br>    suspend fun getTopHeadLines(@Query(&quot;country&quot;) country: String, @Query(&quot;page&quot;) page: Int =1, @Query(&quot;pageSize&quot;) pageSize: Int =20) : TopHeadlinesResponse<br><br>}</pre><ul><li>herein <strong>NetworkService</strong>interface we define our HTTP method &amp; endpoint URL which represent our API structure ie, the type of data we want from our server</li><li>we have created the data class (<strong>TopHeadlinesResponse</strong>)in which our data will be stored</li></ul><h3>Creating Retrofit Instance</h3><pre>object RetrofitClient{<br>    private const val BASE_URL = &quot;https://newsapi.org/v2/&quot;<br><br>    val retrofit : Retrofit by lazy {<br>        Retrofit.Builder()<br>            .baseUrl(BASE_URL)<br>            .client(HttpClient.okHttpClient)<br>            .addConverterFactory(GsonConverterFactory.create())<br>            .build()<br>    }<br>}</pre><p>Retrofit object is created using builder pattern, in which we to pass the <strong>Convertor factory </strong>and some additional configuration can also be added like <strong>okHttpClient</strong></p><h3><strong>Use case of Converter Factory:</strong></h3><p>Most modern APIs communicate using JSON. Converter Factory determines how data is converted between Java objects and the HTTP request/response body.</p><p>Retrofit can automatically parse JSON responses into Java/Kotlin objects and serialize Java/Kotlin objects into JSON for requests.</p><h3>Use case of OkHttp Client</h3><ul><li>okHttp is a type-safe powerful HTTP client for Android and Java</li><li>It serves as an underlying network layer that handles HTTP requests and responses.</li><li>The instance of okHttpClient can be customized with various configurations such as interceptors, connection timeout ,settings and more…</li></ul><pre>object HttpClient {<br>    private val httpLoggingInterceptor = HttpLoggingInterceptor().apply {<br>        HttpLoggingInterceptor.Level.NONE<br>    }<br><br><br><br>    val okHttpClient : OkHttpClient =<br>        OkHttpClient()<br>            .newBuilder()<br>            .addInterceptor(AuthTokenInterceptor())<br>            .addInterceptor(httpLoggingInterceptor)<br>            .build()<br>}</pre><p>In our Project, we have used AuthTokenInterceptorand HttpLoggingInterceptorare used as part of the OkHttp client configuration for network calls</p><p><strong>AuthTokenInterceptor</strong>:</p><pre>class AuthTokenInterceptor : Interceptor{<br>    override fun intercept(chain: Interceptor.Chain): Response {<br>        val originalReq = chain.request()<br>        val reqBuilder = originalReq.newBuilder().header(&quot;X-Api-Key&quot;,AppConstant.apiKey)<br>        val request = reqBuilder.build()<br><br>        return chain.proceed(request)<br>    }<br>}</pre><ul><li>it is responsible for adding an authentication token (or any other necessary headers) to each network request.</li><li>ensure that every request made by the Retrofit client includes the necessary authentication details</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9U3iwdD_W28hCogTE7QkWg.png" /><figcaption>News Headline API</figcaption></figure><p>Here, In Above Postman you can see we pass the API key as a query in our API endpoint and We have passed the API as a header via OKhttp Interceptor Therefore we no longer need to pass the redundant API key on every Network call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iWouxt7gJzsFenjTOhtXew.png" /><figcaption>News API key</figcaption></figure><p>get your News API key -&gt; (<a href="https://newsapi.org/">https://newsapi.org/</a>)</p><p><strong>HttpLoggingInterceptor</strong>:</p><ul><li>it logs the details of HTTP requests and responses. It can be useful for debugging and monitoring network calls.</li><li>it’s helpful during development to inspect the network traffic, ensure the requests are correctly formatted, and verify the responses from the server</li><li>You can adjust the logging level (NONE, BASIC, HEADERS, BODY) depending on the amount of detail you need.</li></ul><h3>Final Step: Creating instance of Network Service interface</h3><pre>object ApiClient {<br>    val networkService: NetworkService by lazy {<br>        RetrofitClient.retrofit.create(NetworkService::class.java)<br>    }<br>}</pre><p>we use the retrofit object and create the instance of our NetworkService interface. this instance would be used to call the HTTP method we have defined in our NetworkService interface i.e, @GET getTopHeadLines()</p><h3>Test Network Call via JUnit:</h3><pre>    @Test<br>    fun `GET newsTopHeadLine check status`() {<br>        runBlocking {<br>            val response = ApiClient.networkService.getTopHeadLines(&quot;us&quot;)<br>            assertEquals(&quot;ok&quot;, response.status)<br>        }<br>    }<br><br>    @Test<br>    fun `GET newsTopHeadLine check totalResults`() {<br>        runBlocking {<br>            val response = ApiClient.networkService.getTopHeadLines(&quot;us&quot;)<br>            assertTrue(response.count &gt;= 0)<br>        }<br>    }</pre><p>We have used<strong> an instance of Network service</strong> as discussed in Final Step to fetch data from Server. This whole process is done under run blocking scope</p><p>As show below, we created our NewsUnitTest class in the (test) folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*zyLQd6dSseGjmgTGqEKezA.png" /></figure><p>Unit Test cases are the easiest way to know if our APIs are working or not based on certain assertion we watned to check like is News count &gt;0 or is News Image Url not null in the list. They are tested in isolation of the Main App.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FEQg_Gp2eBkp-C-EELWkOw.png" /></figure><h3>Fetch Data from Network Call via ViewModel</h3><pre>class NewsViewModel : ViewModel() {<br>    val networkService = ApiClient.networkService<br><br>    val _data = MutableStateFlow&lt;TopHeadlinesResponse?&gt;(null)<br>            val data : StateFlow&lt;TopHeadlinesResponse?&gt; = _data<br><br>    init {<br>        fetchNewsData()<br>    }<br><br>    private fun fetchNewsData() {<br>        viewModelScope.launch {<br>            val response = networkService.getTopHeadLines(&quot;us&quot;)<br>            _data.value = response<br>        }<br>    }<br>}</pre><p>Inside viewModel we use the instance of Network service to call getTopHeadLine() and store the data in our StateFlow, which is being observed in our MainActivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*UHQuTZZZby802tKod3VAbg.png" /></figure><h3>Conclusion</h3><p>In this article, we’ve explored the working of network calling in Android using Retrofit, enhanced by the powerful capabilities of OkHttp.</p><p>To summarse we have</p><ol><li>Added the necessary Retrofit dependencies in our Gradle</li><li>Setup a network service interface .</li><li>Created a Retrofit object with GsonConverterFactory for JSON parsing, along with additional configurations using OkHttp’s AuthInterceptor for secure API access and HttpLoggingInterceptor for transparent request and response logging.</li><li>Created instace of Network Service interface using retrofit object</li></ol><p>Moreover, we Have tested the Network calling process using <strong>JUnit test cases</strong>, ensuring the reliability of our network calls. And showcased how to <strong>fetch data in a ViewModel </strong>and manage it using StateFlow, offering an efficient way to handle state in a reactive manner.</p><p>Src Code availabe -&gt; <a href="https://github.com/aman1sr/BaseRetrofitNetworkCalling"><strong>GitHub_repo</strong></a></p><h4>I HOPE YOUR GET BETTER INSITE ON WORKING OF RETROFIT.</h4><p>Don’t Forget me to follow on <strong>Medium</strong>, you can also Follow me on <a href="https://www.linkedin.com/in/aman1024/">LinkedIN </a>, Insta, <a href="https://x.com/aman1024_">Twitter </a>too :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c07f0063be6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Location runtime permission in Android | Kotlin]]></title>
            <link>https://medium.com/@aman1024/handling-location-permission-in-android-kotlin-a1bc4c1cd9da?source=rss-d0a57d0703b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1bc4c1cd9da</guid>
            <category><![CDATA[location-permission]]></category>
            <category><![CDATA[permission]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-permissions]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mobile Alchemist✨]]></dc:creator>
            <pubDate>Fri, 31 May 2024 11:23:05 GMT</pubDate>
            <atom:updated>2025-05-06T04:39:07.101Z</atom:updated>
            <content:encoded><![CDATA[<p>Android app often requires a lot of permission for certain features to work and the developer&#39;s worst nightmare is handling the case when the User declines permission and clicks on <strong>Don’t ask again</strong> checkbox.</p><p>in this Blog, We will deal with a scenario where location permission is essential. After granting this permission, we will send the user to the Next screen or show an Alert Dialog. We will also deal with Don’t show Again Dialog Case.</p><blockquote><strong>Full sourceCode</strong>: <a href="https://github.com/aman1sr/locationPermissionDemo">https://github.com/aman1sr/locationPermissionDemo</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUWELZFSxz0EmMwCF8pBKg.jpeg" /><figcaption>Android Location Permission Dialog</figcaption></figure><h3>Creating a Location Helper Class</h3><p>For handling Location permission we have used a Helper class (<strong>LocationPermissionHelper</strong>) which required the context and would be able to perform location-based actions.</p><h3>Checking and Requesting Location Permission</h3><p>Let on the Button click we need to check if location permission is granted, based on which we move to Next Screen, else show Location Permission Dialog.</p><pre>     binding.btnLocation.setOnClickListener {<br>            if (!LocationPermissionHelper.hasAccessFinePermission(this)) {<br>                LocationPermissionHelper.requestFineLocationPermission(this)<br>            } else {<br>                Toast.makeText(this, &quot;Location Permission Granted&quot;, Toast.LENGTH_SHORT).show()<br>                // PERMISSION is Already granted ((navigate to Next Screen...))<br>            }<br>        }</pre><p><strong>LocationPermissionHelper</strong></p><pre>object LocationPermissionHelper {    <br>private val BASIC_PERMISSION = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)<br>    val BASIC_PERMISSION_REQUESTCODE = 0<br><br>    fun hasAccessFinePermission(activity: Activity): Boolean {<br>        return ContextCompat.checkSelfPermission(<br>            activity,<br>            Manifest.permission.ACCESS_FINE_LOCATION<br>        ) == PackageManager.PERMISSION_GRANTED<br>    }<br><br>    fun requestFineLocationPermission(activity: Activity?) {<br>        ActivityCompat.requestPermissions(activity!!, BASIC_PERMISSION, BASIC_PERMISSION_REQUESTCODE)<br>    }<br>}</pre><p>but what happens if the user accepts/declines the location permission. We can track that info via overriding <strong>onRequestPermissionsResult()</strong> in our Activity.</p><h3>Handling User Response to Location Dialog</h3><pre><br>    override fun onRequestPermissionsResult(<br>        requestCode: Int,<br>        permissions: Array&lt;out String&gt;,<br>        grantResults: IntArray<br>    ) {<br>        super.onRequestPermissionsResult(requestCode, permissions, grantResults)<br>        when (requestCode) {<br>            LocationPermissionHelper.BASIC_PERMISSION_REQUESTCODE -&gt; {<br>                if (!LocationPermissionHelper.hasAccessFinePermission(this)) {<br>                    // Permission deneid<br>     <br>                }else {<br>            Toast.makeText(this, &quot;Woola!!! Camera permission is granted&quot;, Toast.LENGTH_SHORT).show()<br>              //Permission GRANTED by user  move to NEXT Screen&gt;&gt;&gt;<br>        }<br>            }<br>        }<br>    }</pre><p>till now handling accept/decline permission was fine but whatiff the user selects <strong>Don’t ask again </strong>checkBox.</p><p>Now requestFineLocationPermission() will NO longer be able to show the Location permission dialog and as discussed the Location permission is an important checkpoint in our flow, based on which will move to next screen.</p><p>don’t worry Thanks to shouldShowRequestPermissionRationale() comes to rescue.</p><h3>Handling permission: Do not ask again✅</h3><p><strong>Case scenario:</strong> The user is trying to access the Location Specific feature but has denied and checked don’t ask again, so he is stuck in the current screen, Now he tries again to access the Location Specific feature, we redirect the User to the SETTING Screen. (where users have to manually grant permission)</p><blockquote>we can track if the checkbox is being checked or not by shouldShowRequestPermissionRationale()</blockquote><pre>    override fun onRequestPermissionsResult(<br>        requestCode: Int,<br>        permissions: Array&lt;out String&gt;,<br>        grantResults: IntArray<br>    ) {<br>        super.onRequestPermissionsResult(requestCode, permissions, grantResults)<br>        when (requestCode) {<br>            LocationPermissionHelper.BASIC_PERMISSION_REQUESTCODE -&gt; {<br>                if (!LocationPermissionHelper.hasAccessFinePermission(this)) {<br>                    Toast.makeText(<br>                        this,<br>                        &quot;Location permission is needed to run this application&quot;,<br>                        Toast.LENGTH_LONG<br>                    ).show();<br>                    <br>                    if (!LocationPermissionHelper.shouldShowRequestPermissionRationale(this)) {  // checking if don&#39;t show Again box checked and denied<br>                        // Location permission denied with Do not ask again<br>                        LocationPermissionHelper.launchPermissionSettings(this)   // redirect user to Setting screen <br>                        finish()<br>                    }else{<br>                        showAlertDialog()<br>                    }<br>                }else {<br>            Toast.makeText(this, &quot;Woola!!! Location permission is granted&quot;, Toast.LENGTH_SHORT).show()<br>        }<br>            }<br>        }<br>    }</pre><h3>Full code of LocationPermissionHelper:</h3><pre>object LocationPermissionHelper {<br>    private val BASIC_PERMISSION = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)<br>    val BASIC_PERMISSION_REQUESTCODE = 0<br><br>    // todo: android 11 vs 12 AccessFineLocation (https://g.co/gemini/share/21fbd05d0120)<br>    fun hasAccessFinePermission(activity: Activity): Boolean {<br>        return ContextCompat.checkSelfPermission(<br>            activity,<br>            Manifest.permission.ACCESS_FINE_LOCATION<br>        ) == PackageManager.PERMISSION_GRANTED<br>    }<br><br>    fun requestFineLocationPermission(activity: Activity?) {<br>        ActivityCompat.requestPermissions(activity!!, BASIC_PERMISSION, BASIC_PERMISSION_REQUESTCODE)<br>    }<br><br>    fun shouldShowRequestPermissionRationale(activity: Activity): Boolean{<br>        return ActivityCompat.shouldShowRequestPermissionRationale(activity, BASIC_PERMISSION.get(0))<br>    }<br>    fun launchPermissionSettings(activity: Activity) {<br>        val intent = Intent()<br>        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS<br>        intent.data = Uri.fromParts(&quot;package&quot;, activity.packageName, null)<br>        activity.startActivity(intent)<br>    }<br><br>}</pre><h3>Conclusion</h3><p>The above way of handling Permission is like a Framework, the same LocationPermissionHelper could also be replaced with CameraPermissionHelper or MusicPlayerPermissionHelper where we can ask for Camera, audio, and location simultaneously.</p><p>Please feel free to reach out to me on <a href="https://www.linkedin.com/in/aman1024/"><strong>LinkedIn</strong></a> , <a href="https://twitter.com/aman1024_"><strong>Twitter</strong></a>, <a href="https://studio.youtube.com/channel/UCjovVgJcJc1A3DbAlw4cc3g"><strong>Youtube</strong></a></p><h3>If you liked this blog, don’t forget to hit the 👏 . Stay tuned for the next one!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1bc4c1cd9da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>