<?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 Shridhar Choudhari on Medium]]></title>
        <description><![CDATA[Stories by Shridhar Choudhari on Medium]]></description>
        <link>https://medium.com/@sribanavasi?source=rss-99d7ca92d2b2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rgPJxuw1DZ2ai-sF7VX5Qg.png</url>
            <title>Stories by Shridhar Choudhari on Medium</title>
            <link>https://medium.com/@sribanavasi?source=rss-99d7ca92d2b2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:43:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sribanavasi/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[Android App Components]]></title>
            <link>https://medium.com/@sribanavasi/android-app-components-618554cc10aa?source=rss-99d7ca92d2b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/618554cc10aa</guid>
            <category><![CDATA[androi̇d]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-app-components]]></category>
            <dc:creator><![CDATA[Shridhar Choudhari]]></dc:creator>
            <pubDate>Tue, 14 May 2024 12:41:43 GMT</pubDate>
            <atom:updated>2024-05-14T12:41:43.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*IVfQK4G0viGTG2wWDv6iRw.png" /></figure><p>These are the building blocks of the Android app<br>1. Activity<br>2. Services<br>3. Broadcast Receiver<br>4. Content Providers</p><h3><strong>Activity</strong></h3><ul><li>The entry point for interacting with users. Responsible for single screen: Keeping track of all processes that are going on, and handling these processes.<br> ex: user on the home screen, that maybe one activity</li><li>To activate this component:startActivity() or starActivityForResult() with intent</li></ul><h3><strong>Services</strong></h3><ul><li>The entry point for keeping the app running in the background: This component runs in the background to perform long-running operations or perform Remote operations.</li><li>To activate this component:startService() and bindService() with intent</li></ul><h4>Two Types Of Services</h4><ul><li>Started Services: it tells the System to keep them running until their work is completed.</li><li>Two types of Started Services: Foreground Services(Music player) and Background Services(Downloading the file).</li><li>Bound Services: it tells the system to keep them running because some processes (components) have a dependency on these services. Until all processes (components) are unbound, it keeps running.</li></ul><h3>Broadcast Receiver</h3><ul><li>Used to deliver system events to the apps outside of regular flow.Ex; aleram or calls.</li><li>In some cases, the broadcast receiver can schedule “JobService” to perform some work based on even using “JobScheduler”.And they are used to interact among the apps.</li><li>To activate this component:sendBroadcast() or sendOrderedBroadcast() with intent</li></ul><h3>Content Providers</h3><ul><li>It Manages a shared set of app data that you can store in the file system. Handle Permission to read/write these data.</li><li>To activate this component: Only Content providers are activated when Requested by Content Resolver with Query But not by Intent</li></ul><blockquote><strong><em>Note</em></strong></blockquote><ul><li>Intent activates 3 of 4 components (activity, service, broadcast receiver). The intent is Like a message that requests an action from one component to another.</li><li>Internet Object created with Message to activate specific component(Explicit Inetnt) or Type of Components(Implicit Intent)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=618554cc10aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practice for Handling API Calls Using Retrofit in Android Studio]]></title>
            <link>https://medium.com/@sribanavasi/best-practice-for-handling-api-calls-using-retrofit-in-android-studio-36fb5e53c08?source=rss-99d7ca92d2b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/36fb5e53c08</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[sealed-classes]]></category>
            <category><![CDATA[handling-api-call]]></category>
            <category><![CDATA[http-class]]></category>
            <dc:creator><![CDATA[Shridhar Choudhari]]></dc:creator>
            <pubDate>Fri, 21 Jul 2023 16:53:23 GMT</pubDate>
            <atom:updated>2023-07-21T16:56:02.585Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRxAkRdeqMAvAsfGqtHEiA.jpeg" /></figure><p>When making API calls in Android applications, it’s common to encounter three types of responses. First, you might receive a successful response with HTTP status codes like 200/201, indicating everything is functioning correctly. Second, due to various reasons such as incorrect headers, invalid tokens, or unavailable API calls, you may get failed responses with status codes like 400/401/500, among others. Lastly, there’s a scenario where network-related or technical issues cause exceptions.</p><p>Handling all these cases can result in boilerplate code, as developers often use the Response&lt;T&gt; interface of the Retrofit library along with try-catch blocks at each API call. Fortunately, Kotlin’s sealed class concept provides an elegant solution to reduce boilerplate code and handle API responses effectively.</p><p><strong>Implementing the Sealed Class</strong></p><p>To begin, let’s create a sealed class that encapsulates all three types of API response results:</p><pre>sealed class NetworkResult&lt;out T : Any&gt; {<br>    data class Success&lt;out T : Any&gt;(val code: Int, val data: T) : NetworkResult&lt;T&gt;()<br>    data class Error(val code: Int, val errorMsg: String?) : NetworkResult&lt;String&gt;()<br>    data class Exception(val e: Throwable) : NetworkResult&lt;Nothing&gt;()<br>}</pre><p>The sealed class NetworkResult includes three subclasses: Success, Error, and Exception. Each subclass carries the relevant information about the response, such as HTTP status codes and the response data.</p><p><strong>Creating an API Handler Interface</strong></p><p>Next, we’ll define an interface to handle API calls and convert the Response&lt;T&gt; wrapped result to our NetworkResult&lt;T&gt; wrapped result:</p><pre>interface ApiHandler {<br>    suspend fun &lt;T : Any&gt; handleApi(<br>        execute: suspend () -&gt; Response&lt;T&gt;<br>    ): NetworkResult&lt;T&gt; {<br>        return try {<br>            val response = execute()<br>            <br>            if (response.isSuccessful) {<br>                NetworkResult.Success(response.code(), response.body()!!)<br>            } else {<br>                NetworkResult.Error(response.code(), response.errorBody()?.string())<br>            }<br>        } catch (e: HttpException) {<br>            NetworkResult.Error(e.code(), e.message())<br>        } catch (e: Throwable) {<br>            NetworkResult.Exception(e)<br>        }<br>    }<br>}</pre><p>The ApiHandler interface provides a single handleApi function that takes a suspend lambda for executing the API call. It automatically wraps the response into the appropriate NetworkResult subclass based on the outcome of the call.</p><p><strong>Defining API Interface with Retrofit</strong></p><p>Now, we’ll create the API interface using Retrofit with the expected data model wrapped into the Response interface:</p><pre>interface ApiServices {<br>    @GET(&quot;/titles/utils/genres&quot;)<br>    suspend fun getGenres(): Response&lt;Genres&gt;<br><br><br>    @GET(&quot;/titles&quot;)<br>    suspend fun getMovieTitles(<br>        @Query(&quot;genre&quot;) genre: String?,<br>        @Query(&quot;page&quot;) page: Int?<br>    ): Response&lt;MovieTitles&gt;<br>}</pre><p><strong>Simplifying API Calls</strong></p><p>With the ApiHandler and API interface in place, making API calls becomes much simpler and cleaner. You no longer need to worry about the outcome of each API call, thanks to the power of sealed classes.</p><p>Here’s an example of how to make a network call using our handleApi function:</p><pre>class MovieRepository(private val apiServices: ApiServices) : ApiHandler {<br>    override suspend fun getMovieTitles(genre: String?, page: Int?): NetworkResult&lt;MovieTitles&gt; {<br>        return handleApi { apiServices.getMovieTitles(genre = genre, page = page) }<br>    }<br>}</pre><p><strong>Handling API Responses</strong></p><p>When you receive a NetworkResult from the API call, you can easily check and handle the response type:</p><pre>val response = movieRepository.getMovieTitles(&quot;action&quot;, 1)<br>when (response) {<br>    is NetworkResult.Success -&gt; {<br>        // Handle successful response with response.data<br>    }<br>    is NetworkResult.Error -&gt; {<br>        // Handle error response with response.errorMsg<br>    }<br>    is NetworkResult.Exception -&gt; {<br>        // Handle exception (e.g., show a generic error message)<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>Using a sealed class to handle API calls with Retrofit significantly reduces boilerplate code and promotes a more organized and robust codebase. By encapsulating different API response states in a sealed class, you gain compile-time safety and explicit handling of all possible scenarios. The result is a cleaner and more maintainable code, making your Android application development a smoother experience.</p><p>Happy coding!</p><p>Code Base: <a href="https://github.com/sribanavasi/Handling_Multiple_Api">Example App code base</a></p><p>Shridhar Choudhari. Software Developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36fb5e53c08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Multiple API Calls in Android: Best Practices]]></title>
            <link>https://medium.com/@sribanavasi/handling-multiple-api-calls-in-android-best-practices-a95227f5f314?source=rss-99d7ca92d2b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a95227f5f314</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[call-multiple-api]]></category>
            <category><![CDATA[multiple-http-calls]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Shridhar Choudhari]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 15:21:15 GMT</pubDate>
            <atom:updated>2023-07-07T15:21:15.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Handling multiple API calls in Android applications can sometimes be a challenging task due to the asynchronous nature of APIs. However, with the right approach, it can be managed effectively. In this article, we will explore different scenarios for handling multiple API calls and discuss best practices to ensure smooth execution and optimal performance.</p><h3>Scenario 1: Sequential API Calls with Dependency</h3><p>In certain cases, we may have API call B dependent on the result of API call A. To handle this scenario, we can utilize the power of async and await functionality. Consider the following code snippet:</p><pre>fun getResultAResultB() {<br>    viewModelScope.launch {<br>        _genres.postValue(DataState.Init)<br>        _movieTitle.postValue(DataState.Init)<br>        val resultA = async { repository.getGenres() }<br>        _genres.postValue(resultA.await().convertToDataState())<br>        val resultB = async { repository.getMovieTitles() }<br>        _movieTitle.postValue(resultB.await().convertToDataState())<br>    }<br>}</pre><p>In the above code, we use coroutines to perform the API calls asynchronously. The async function is used to initiate each API call, and the await function suspends the coroutine until the respective API call is complete. This ensures that the second API call (B) is executed only after the first API call (A) has finished.</p><h3>Scenario 2: Concurrent API Calls with Result Processing</h3><p>In some scenarios, we need to execute multiple API calls concurrently and process the results together. The awaitAll function can be used to achieve this efficiently. Consider the following code snippet:</p><pre>fun getGetResultAB() {<br>    viewModelScope.launch {<br>        _genres.postValue(DataState.Init)<br>        _movieTitle.postValue(DataState.Init)<br>        val resultA = async { repository.getGenres() }<br>        val resultB = async { repository.getMovieTitles() }<br>        val result = awaitAll(resultA, resultB)<br>        _genres.postValue(result[0].convertToDataState() as DataState&lt;Genres&gt;)<br>        _movieTitle.postValue(result[1].convertToDataState() as DataState&lt;MovieTitles&gt;)<br>    }<br>}</pre><p>In the above code, both API calls (A and B) are executed concurrently using coroutines and the awaitAll function. This allows us to await the completion of both API calls without any dependency. Once both results are available, they can be processed and assigned to their respective LiveData objects.</p><h3>Scenario 3: Independent API Calls for Performance</h3><p>In certain situations, we may need to execute API calls independently and obtain results as soon as possible, without any strict ordering or dependency. Consider the following code snippet:</p><pre>fun getPageAorPageB() {<br>    viewModelScope.launch {<br>        _genres.postValue(DataState.Init)<br>        repository.getGenres().let { result -&gt;<br>            _genres.postValue(result.convertToDataState())<br>        }<br>    }<br>    viewModelScope.launch {<br>        _movieTitle.postValue(DataState.Init)<br>        repository.getMovieTitles().let { result -&gt;<br>            _movieTitle.postValue(result.convertToDataState())<br>        }<br>    }<br>}</pre><p>In the above code, two coroutines are launched independently to execute API calls for genres and movie titles. This allows the calls to be made concurrently, maximizing performance by reducing waiting time. The results are then posted to their respective LiveData objects for further processing.</p><p>Conclusion:</p><p>Handling multiple API calls in Android applications requires careful consideration of dependencies, concurrency, and performance. By utilizing Kotlin coroutines and appropriate await functions, we can effectively manage sequential and concurrent API calls.</p><p>When API calls have dependencies, sequential execution using async and await ensures proper order. For concurrent execution with result processing, awaitAll simplifies handling multiple results. And when independent API calls are needed, launching coroutines independently optimizes performance.</p><p>By following these best practices, developers can build robust and efficient Android applications that effectively handle multiple API calls, providing users with a seamless experience.</p><p>Remember to adapt the provided code snippets to your specific project requirements and consider additional error handling, caching mechanisms, and best practices to ensure the reliability and performance of your application.</p><p>CodeBase: <a href="https://github.com/sribanavasi/Handling_Multiple_Api.git">Example Code of handling multiple API Calls</a></p><p>Happy coding!</p><p>Shridhar Choudhari. Software Developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a95227f5f314" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SSO(Single Sign On) in Native Android]]></title>
            <link>https://medium.com/@sribanavasi/sso-single-sign-on-in-native-android-154d3f69ccdb?source=rss-99d7ca92d2b2------2</link>
            <guid isPermaLink="false">https://medium.com/p/154d3f69ccdb</guid>
            <category><![CDATA[sso]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Shridhar Choudhari]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 18:36:03 GMT</pubDate>
            <atom:updated>2023-03-15T18:36:03.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*wugTgyus7hH-nI8p7KjfHg.png" /><figcaption>Single Sign On</figcaption></figure><p>A typical way of implementing SSO in your application is to use the web browser to do authentication and maintain Auth state locally in the application and use it for other API calls. You can refer to (https://github.com/openid/AppAuth-Android) these documents to see how to implement it. In this method, we save some data in the web browser, and since we use a web browser inside your application, UI maybe looks ugly.</p><p>One more way of Implementing SSO in a Native Android application is to use your app UI to take user credentials and do API calls to the SSO endpoint. After API calls, we save login states, manage credentials and do token refresh internally whenever a token expires. In this article, we will see how to implement the same.</p><p><strong>Step 1: Create a Data class</strong></p><p>Create a Data class witch can take SSO login responses. The typical structure of the data class is shown below. This data class contains many fields like token, refresh token, expire time for tokens, which we save in local storage (Shared preferences) as Auth status.</p><pre>data class SSOResponse(<br>    val access_token: String,<br>    val expires_in: Int,<br>    @SerializedName(&quot;not-before-policy&quot;) val notBeforePolicy: Int,<br>    val refresh_expires_in: Int,<br>    val refresh_token: String,<br>    val scope: String,<br>    val session_state: String,<br>    val token_type: String<br>) {<br>    private var expires_at: Long = –1<br>    private var refresh_expires_at: Long = –1<br>    val isAccessTokenExpired: Boolean<br>        get() {<br>            return expires_at &lt; System.currentTimeMillis()<br>        }<br>    val isRefreshTokenExpired: Boolean<br>        get() {<br>            return refresh_expires_at &lt; System.currentTimeMillis()<br>        }<br>    fun calculateExpiryTime() {<br>        expires_at = System.currentTimeMillis() + (expires_in * 1000)<br>        refresh_expires_at = System.currentTimeMillis() + (refresh_expires_in * 1000)<br>    }<br>}</pre><p><strong>Step 2: Set up API calls</strong></p><p>In this setup, you need to create an environment for HTTP API calls. Based on your preferences you can choose any of the API call libraries and add it in the build gradel. We will use the retrofit library in this example.</p><p>Build.gradel (app)</p><pre>dependencies {<br><br>    …<br><br>    def retrofit_version = “2.8.1”<br><br>    implementation “com.squareup.retrofit2:retrofit:$retrofit_version“<br><br>    implementation “com.squareup.retrofit2:converter-gson:$retrofit_version“<br><br>    …<br><br>}</pre><p>Crate retrofit interface to add the endpoints of the URL. We have two ways of getting responses. In the first method, we use the user credential along with the client id and <strong>“password”</strong> as grant type. In the second method, if we use a refresh token, which is not expired along with the client id and <strong>“refresh_token” </strong>grant type.</p><pre>interface RetrofitInterface {<br>    @FormUrlEncoded<br><br>    @POST(“/auth/realms/lsdev/protocol/openid-connect/token”)<br><br>    fun login(<br><br>        @Field(“client_id”) client_id: String,<br><br>    @Field(“username”) username: String,<br><br>    @Field(“password”) password: String,<br><br>    @Field(“grant_type”) grant_type: String,<br><br>    ): Call&lt;SSOResponse&gt;<br><br>    @FormUrlEncoded<br><br>    @POST(“/auth/realms/lsdev/protocol/openid-connect/token”)<br><br>    fun refreshToken(<br><br>        @Field(“client_id”) client_id: String,<br><br>    @Field(“refresh_token”) refresh_token: String,<br><br>    @Field(“grant_type”) grant_type: String,<br><br>    ): Call&lt;SSOResponse&gt;<br><br>}</pre><p>We will create a new file to get the Retrofit object. In this file, we will have a function that will return the Retrofit object.</p><pre>object RetrofitHelper {<br>    val baseUrl = “your_domain_base_url”<br><br>    fun getInstance(): Retrofit {<br><br>        return Retrofit.Builder().baseUrl(baseUrl)<br><br>            .addConverterFactory(GsonConverterFactory.create())<br><br>            .build()<br><br>    }<br><br>}</pre><p>Now we will link the Retrofit object and Retrofit interface file in the Activity</p><pre><br>val retrofitInstance = RetrofitHelper.getInstance().create(RetrofitInterface::class.java)</pre><p><strong>Step 3:</strong> <strong>Auth State management</strong></p><p>In this step, we need to handle Auth state which we will be saved in local storage. There are two scenarios that come into play. To check whether the user logs In or not we will use the below code.</p><pre>fun isUserLogin(loginDone: () -&gt; Unit, login: () -&gt; Unit) {<br>    viewModelScope.launch {<br>        OpenIdResp = dataStorePref.getOpenIdConnectRes.first()<br>        OpenIdResp.let {<br>            if (it != null) {<br>                if (it.isAccessTokenExpired) {<br>                    if (it.isRefreshTokenExpired) {<br>                        auth(USERNAME, PASSWORD, loginDone, login)<br>                    } else {<br>                        refreshToken(it.refresh_token, loginDone, login)<br>                    }<br>                } else {<br>                    Log.d(“login”, “done”)<br>                    loginDone()<br>                    saveToken(it.access_token, it.refresh_token)<br>                }<br>            } else {<br>                login()<br>            }<br>        }<br>    }<br>}</pre><p>In this code, we will check if the user previously logged in based on the response stored in shared preferences. If we have response data, we check for the token expired, if the token is not expired, the user allows to log in, and the saved token is used for authorized API calls. If the token is expired, we will check if the refresh token is expired, if it is not expired, we make a refresh token call using the stored refresh token and get the new response and save it in storage. If the refresh token is expired, we call login API call using saved credentials and store response. If we don’t have a stored response, consider it as the user has not logged in and ask the user to give credentials to log in.</p><p>In the Login API call, we use user credentials and login with login API with “password” as grant_type. After getting responses, we have to calculate the expiration time for both the token and refresh token, then save it in local storage along with the credential. The code for this is below. Use tokens in this response for authorized API calls in the application.</p><pre>retrofitInstance.auth(<br>client_id = CLIENT_ID,<br><br>username = userName,<br><br>password = password,<br><br>grant_type = GRANT_TYPE_LOGIN<br><br>).enqueue(object : Callback&lt;OpenIdConnectRes&gt; {<br><br>    override fun onResponse(<br><br>        call: Call&lt;OpenIdConnectRes&gt;,<br><br>        response: Response&lt;OpenIdConnectRes&gt;<br><br>    ) {<br><br>        response.body()?.let {<br><br>            Log.d(“auth”, ” ok ${it}“)<br><br>            viewModelScope.launch {<br><br>                it.calcExpiryTime()<br><br>                dataStorePref.setOpenIdConnectRes(it)<br><br>                dataStorePref.setUserCredential(it1)<br><br>            }<br><br>        }<br>        <br>        override fun onFailure(call: Call&lt;OpenIdConnectRes&gt;, t: Throwable) {<br>        }<br>    })</pre><p>In the Refresh token API call, we use the saved refresh token to do an API call with “refersh_token” as grant_type.In this case, also, calculate the expiry time for both the token and refresh token, then save it in local storage. The code for this is below.</p><pre>retrofitInstance.refreshToken(<br>   client_id = CLIENT_ID,<br><br>   refresh_token = refTok,<br><br>   grant_type = GRANT_TYPE_REFRESH_TOKEN<br><br>).enqueue(object :<br><br>   Callback&lt;OpenIdConnectRes&gt; {<br><br>   override fun onResponse(<br><br>       call: Call&lt;OpenIdConnectRes&gt;,<br><br>       response: Response&lt;OpenIdConnectRes&gt;<br><br>   ) {<br><br>       response.body()?.let {<br><br>           viewModelScope.launch {<br><br>               it.calcExpiryTime()<br><br>               dataStorePref.setOpenIdConnectRes(it)<br><br>           }<br><br>       } }<br><br>   override fun onFailure(call: Call&lt;OpenIdConnectRes&gt;, t: Throwable) {<br><br>     <br><br>   }<br><br>})</pre><p>Note*</p><ul><li>When users log out, delete the locally stored responses.</li><li>Before every API call, check for token expiration. If it is expired, do refresh the token API call.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=154d3f69ccdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>