<?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 Pranshu Gupta on Medium]]></title>
        <description><![CDATA[Stories by Pranshu Gupta on Medium]]></description>
        <link>https://medium.com/@iampranshu2003?source=rss-f7f188a5a803------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JdMXvdv063EMyzPLxHB0iw.png</url>
            <title>Stories by Pranshu Gupta on Medium</title>
            <link>https://medium.com/@iampranshu2003?source=rss-f7f188a5a803------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:13:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iampranshu2003/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[Kotlin Coroutines & Flow Part 1]]></title>
            <link>https://medium.com/@iampranshu2003/kotlin-coroutines-flow-part-1-4a16ed6f2d18?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a16ed6f2d18</guid>
            <category><![CDATA[asynctask]]></category>
            <category><![CDATA[kotlin-coroutines-flow]]></category>
            <category><![CDATA[kotlin-coroutines]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 15:27:57 GMT</pubDate>
            <atom:updated>2025-11-09T15:27:57.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome This article is the first in a series for anyone new to Kotlin Coroutines or who just wants a quick revision. We’ll start from the very basics and move to advanced topics in later parts. In this first article, we’re going to explore how asynchronous programming in Android began the old ways before coroutines came. If you’re not interested in the history and want to jump straight into Coroutines and Flow, <strong>feel free to skip this and head over to Part 2</strong></p><p>So basically why we need kotlin Coroutines. we all want smooth apps without any lag but long tasks like fetching from the internet or a database can freeze your app’s main thread. This leads to frustrated users tapping on a frozen screen and, worst of all, the dreaded “Application Not Responding” (ANR) crash.</p><p>The solution is asynchronous programming basically, telling your app to do that heavy lifting in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*rm4MUNhbdprGWzpL_8_8Ew.png" /></figure><p>In the give figure Task 1 and Task 2 are running on the main thread. Task 2 starts Task 3 on the background thread.While Task 3 is running, the main thread can continue to perform other tasks, such as Task 4. After Task 3 is done, it will return to the main thread. This how asynchronous programming works.</p><h3>Key Concepts for Asynchronous Programming</h3><h4>Thread:</h4><p>A thread is a unit of execution that runs code concurrently. In Android, the UI thread is the main thread. You can perform a task on another thread by using the java.lang.Thread class<br>You can easily start a new thread to do background work (like a network call) by wrapping your code in Thread { ... }.start()</p><h4>Handler</h4><p>A handler (android.os.Handler) allows you to communicate between threads, such as from the background thread to the main thread, You can pass a looper into the Handler constructor to specify the thread where the task will be run. A looper is an object that runs the messages in the thread’s queue.</p><p><strong>Here is an Example for it</strong></p><pre>private fun fetchSomethingWithThreadAndHandler() {<br>Thread {<br>// get something from network<br>val something = getSomethingFromNetwork()<br>Handler(Looper.getMainLooper()).post {<br>// Display on UI<br>displaySomething(something)<br>   }<br>  }.start()<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YEg4ak4zmv5U1eLXS8wHg.png" /><figcaption>A thread’s handler allows you to send a message to the thread’s message queue. The handler’s looper will execute the messages in the queue</figcaption></figure><h4>Using threads and handlers works for background processing, but they have the following disadvantages:</h4><ol><li>Every time you need to run a task in the background, you should create a new thread and use runOnUiThread or a new handler to post back to the main thread.</li><li>Creating threads can consume a lot of memory and resources.</li><li>It can also slow down your app.</li><li>Multiple threads make your code harder to debug and test.</li><li>Code can become complicated to read and maintain.</li></ol><h3>Callbacks</h3><p>Another common approach to asynchronous programming in Android is using callbacks. A callback is a function that will be run when the asynchronous code has finished executing</p><pre>/**<br> * You placing the order.<br> */<br>fun placePizzaOrder() {<br>    println(&quot;You: I&#39;m ordering a pizza.&quot;)<br><br>    // Call the &quot;pizza place&quot; and give them your &quot;phone number&quot; (the callback)<br>    // The code in { ... } is your callback.<br>    orderPizza(topping = &quot;Pepperoni&quot;) { pizza -&gt; <br>        // This code runs LATER, when the callback is triggered<br>        println(&quot;You: Awesome, my $pizza is here!&quot;)<br>    }<br>    <br>    println(&quot;You: Order placed. Now I&#39;ll wait...&quot;)<br>}<br><br><br><br>/**<br> * The &quot;Pizza Place&quot; that does the slow work.<br> * It takes an order and a &quot;phone number&quot; (the onReady callback).<br> */<br>fun orderPizza(topping: String, onReady: (String) -&gt; Unit) {<br>    println(&quot;Pizza Place: Got your $topping order. We&#39;ll call you back.&quot;)<br><br>    // Start a background thread (the &quot;kitchen&quot;) to bake<br>    Thread {<br>        Thread.sleep(2000) // Simulate 2 seconds of baking<br>        val finishedPizza = &quot;Hot $topping Pizza 🍕&quot;<br><br>        // Work is done! Call the &quot;phone number&quot; (the callback)<br>        onReady(finishedPizza)<br>        <br>    }.start()<br>}</pre><p><em>In the preceding example, after fetching the pizza in the background, the onReady callback will be called and will display the text</em></p><h4>however Callbacks can become complicated easily, especially when nesting callback functions and handling errors. This makes it hard to read and test.</h4><h3>AsyncTask</h3><p>AsyncTask was used for running background tasks in Android. It makes it easier to do background processing and post data to the main thread. With AsyncTask, you don’t have to manually handle threads. To use it you have to create it’s subclass with 3 generic type</p><ol><li>Params: This is the type of input for AsyncTask or is void if there’s no input needed.</li><li>Progress: This argument is used to specify the progress of the background operation or void if there’s no need to track the progress.</li><li>Result: This is the type of output of AsyncTask or is void if there’s no output to be displayed.</li></ol><p><strong>AsyncTask&lt;Params?, Progress?, Result?&gt;()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*dX-K6v2pevXGg0gV.png" /></figure><p><strong>Example:</strong></p><pre>private class FetchUserTask : AsyncTask&lt;String, Void, String&gt;() {<br><br>    // 1. Runs on MAIN thread first<br>    override fun onPreExecute() {<br>        // Show loading spinner...<br>    }<br><br>    // 2. Runs on BACKGROUND thread<br>    override fun doInBackground(vararg urls: String): String {<br>        // This is a fake 2-second network call<br>        Thread.sleep(2000)<br>        return &quot;Alex Johnson&quot; // The result<br>    }<br><br>    // 3. Runs on MAIN thread last, with the result<br>    override fun onPostExecute(result: String) {<br>        // Hide loading spinner...<br>        // textView.text = result<br>    }<br>}</pre><p>It consist of 4 events</p><ol><li><strong>doInBackground</strong>: This event specifies the actual task that will be run in the background, such as fetching/saving data to a remote server. This is the only event that you are required to override.</li><li><strong>onPostExecute</strong>: This event specifies the tasks that will be run in the UI thread after the background operation finishes, such as displaying the result.</li><li><strong>onPreExecute</strong>: This event runs on the UI thread before doing the actual task, usually displaying a progress loading indicator.</li><li><strong>onProgressUpdate</strong>: This event runs in the UI thread to denote progress on the background process, such as displaying the amount of time remaining to finish the task.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPuGYPnV9nKrm5zV7b356A.png" /></figure><p><strong>AsyncTask was simple, but it had big problems If you rotated your screen (a “configuration change”), the Activity was destroyed. But the Async task would keep running. When it finished, it would try to update the old destroyed Activity leading to memory leaks and crashes. Because of this, AsyncTask is now deprecated.</strong></p><h3>Executors</h3><p>executers are a Java API that acts as a Job Manager for threads. Instead of creating a new threads manually, you give your job (a runnable) to an Executor , which runs it on a background thread from a thread pool.</p><p><strong>However, this was still complicated. You’d either have to use a Handler to post the result back to the main thread, or you&#39;d get a Future (a &quot;receipt&quot; for your job) which would block your code if you tried to .get() the result.</strong></p><h3>Kotlin coroutines</h3><p>Kotlin Coroutines are Google’s official, recommended way to handle asynchronous programming in Android. They replace old, complex methods like AsyncTask and callbacks. The main goal is to make your code <strong>simple and easy to read</strong>. You can write complex background tasks (like network calls or database access) as if they were simple, sequential code.</p><p>This works by using suspend functions. A suspend function has the special power to pause its work (e.g., while waiting for a network response) <strong>without blocking the main thread</strong>. This keeps your app&#39;s UI perfectly smooth and responsive.</p><p>When you start a coroutine, you use <strong>Dispatchers</strong> to decide which thread it runs on:</p><ul><li><strong>Dispatchers.IO</strong>: For background work (networking, disk).</li><li><strong>Dispatchers.Main</strong>: For updating the UI.</li></ul><p>You can easily launch a coroutine in a background thread and then switch back to the main thread to show the result, all in a few clean, readable lines.</p><h3>Kotlin Flows</h3><p>Kotlin flow is the second key part of modern Android async, built <em>on top</em> of Coroutines. It’s an asynchronous stream designed to handle multiple value over time, not just a single value.</p><p>Think of the difference like this:</p><ul><li>A suspend function is like ordering a package: you make one request, wait, and get one single result back.</li><li>A flow is like a stream : you collect it, and it can emit multiple results over time (like getting live database updates, or receiving new chat messages as they arrive).</li></ul><p>Flows are cold meaning they are just a blueprint and don’t actually run or do any work until you call a function like .collect() to start listening for values.</p><p><strong>In this article we covered different ways how we did asynchronous programming in the second part of this series we will dive deeper in kotlin coroutines and kotlin flows as they are the modern approach for programming asynchronously today <br>thank you for reading my article i hope you liked it 😊</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a16ed6f2d18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending HTTP POST Requests with Retrofit in Android]]></title>
            <link>https://medium.com/@iampranshu2003/sending-http-post-requests-with-retrofit-in-android-81e119d785a8?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e119d785a8</guid>
            <category><![CDATA[retrofit2]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[retrofit-android-example]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 12:23:09 GMT</pubDate>
            <atom:updated>2025-02-07T12:23:09.302Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Welcome back to another Android development tutorial. In this article, we’ll learn how to send an <strong>HTTP POST request</strong> using <strong>Retrofit</strong>, one of the most popular libraries for handling network operations in Android. We’ll use the a free REST API for testing and prototyping, to demonstrate how to create a new resource on the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FTLFA2oR9K-bXgaX.jpg" /></figure><p>By the end of this guide, you’ll know how to:</p><ul><li>Define a POST request in Retrofit.</li><li>Send data to a server using an HTTP POST request.</li><li>Handle the server’s response and display it in your app.</li></ul><h3>Why Use POST Requests?</h3><p>HTTP POST requests are used to send data to a server to create or update a resource. Unlike GET requests, which append data to the URL, POST requests send data in the <strong>request body</strong>, making them more secure for sensitive information.</p><p>Here’s a quick comparison:</p><ul><li><strong>GET</strong>: Used to retrieve data. Data is visible in the URL. Not suitable for sensitive data.</li><li><strong>POST</strong>: Used to send data. Data is hidden in the request body. Ideal for creating or updating resources.</li></ul><h3>Setting Up the Project</h3><h3>Step 1: Add Retrofit Dependencies</h3><p>To use Retrofit, add the following dependencies to your build.gradle file:</p><pre>dependencies {<br>    implementation &#39;com.squareup.retrofit2:retrofit:2.9.0&#39;<br>    implementation &#39;com.squareup.retrofit2:converter-gson:2.9.0&#39;<br>    implementation &#39;com.squareup.okhttp3:logging-interceptor:4.9.1&#39;<br>}</pre><ul><li><strong>Retrofit</strong>: The core library for network requests.</li><li><strong>Gson Converter</strong>: Converts JSON responses into Kotlin objects.</li><li><strong>Logging Interceptor</strong>: Logs network requests and responses for debugging.</li></ul><h3>Step 2: Define the Data Model</h3><p>We’ll use the AlbumsItem data class to represent an album. This class matches the structure of the JSON response from the API.</p><pre>package com.example.retrofitdemo<br>import com.google.gson.annotations.SerializedName<br>data class AlbumsItem(<br>    @SerializedName(&quot;id&quot;)<br>    val id: Int,<br>    @SerializedName(&quot;title&quot;)<br>    val title: String,<br>    @SerializedName(&quot;userId&quot;)<br>    val userId: Int<br>)</pre><h3>Step 3: Create the Retrofit Service</h3><p>Define an interface called AlbumService to specify the API endpoints. We’ll add a POST method to upload a new album.</p><pre>package com.example.retrofitdemo<br>import retrofit2.Response<br>import retrofit2.http.Body<br>import retrofit2.http.GET<br>import retrofit2.http.POST<br>interface AlbumService {<br>    @GET(&quot;/albums&quot;)<br>    suspend fun getAlbums(): Response&lt;Albums&gt;<br>    @POST(&quot;/albums&quot;)<br>    suspend fun uploadAlbum(@Body album: AlbumsItem): Response&lt;AlbumsItem&gt;<br>}</pre><ul><li>@POST(&quot;/albums&quot;): Specifies the endpoint for creating a new album.</li><li>@Body: Indicates that the AlbumsItem object will be sent in the request body.</li></ul><h3>Step 4: Set Up Retrofit Instance</h3><p>Create a RetrofitInstance class to configure the Retrofit client.</p><pre>package com.example.retrofitdemo<br>import com.google.gson.GsonBuilder<br>import retrofit2.Retrofit<br>import retrofit2.converter.gson.GsonConverterFactory<br>class RetrofitInstance {<br>    companion object {<br>        val BASE_URL = &quot;https://jsonplaceholder.typicode.com/&quot;<br>        fun getRetrofitInstance(): Retrofit {<br>            return Retrofit.Builder()<br>                .baseUrl(BASE_URL)<br>                .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))<br>                .build()<br>        }<br>    }<br>}</pre><h3>Step 5: Send a POST Request</h3><p>In the MainActivity, we’ll create a function called uploadAlbum() to send a POST request and handle the response.</p><pre>package com.example.retrofitdemo<br>import android.os.Bundle<br>import android.util.Log<br>import android.widget.TextView<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.lifecycle.LiveData<br>import androidx.lifecycle.liveData<br>import retrofit2.Response<br>class MainActivity : AppCompatActivity() {<br>    private lateinit var textView: TextView<br>    private lateinit var retService: AlbumService<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        retService = RetrofitInstance.getRetrofitInstance().create(AlbumService::class.java)<br>        textView = findViewById(R.id.textView)<br>        uploadAlbum()<br>    }<br>    private fun uploadAlbum() {<br>        val album = AlbumsItem(0, &quot;myTitle&quot;, 3) // ID will be ignored by the server<br>        val postResponse: LiveData&lt;Response&lt;AlbumsItem&gt;&gt; = liveData {<br>            val response = retService.uploadAlbum(album)<br>            emit(response)<br>        }<br>        postResponse.observe(this) { response -&gt;<br>            if (response.isSuccessful) {<br>                val receivedAlbumsItem = response.body()<br>                val result = &quot;&quot;&quot;<br>                    Album title: ${receivedAlbumsItem?.title}<br>                    Album id: ${receivedAlbumsItem?.id}<br>                    Album userId: ${receivedAlbumsItem?.userId}<br>                &quot;&quot;&quot;.trimIndent()<br>                textView.text = result<br>            } else {<br>                Log.e(&quot;API_ERROR&quot;, &quot;Failed to fetch data: ${response.errorBody()?.string()}&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Step 6: Run the App</h3><p>When you run the app, the uploadAlbum() function will:</p><ol><li>Create a new AlbumsItem object.</li><li>Send it to the server using a POST request.</li><li>Display the server’s response in a TextView.</li></ol><p>Here’s what you’ll see in Logcat:</p><ul><li><strong>Request</strong>: A POST request with the album data in the body.</li><li><strong>Response</strong>: A 201 Created status code and the newly created album object with an ID of 101.</li></ul><h3>Key Takeaways</h3><ol><li><strong>POST Requests</strong>: Use POST to send data to a server securely.</li><li><strong>Retrofit</strong>: Simplifies network operations and integrates seamlessly with Kotlin.</li><li><strong>JSONPlaceholder</strong>: A great tool for testing REST APIs.</li></ol><p>the code for this project is (<a href="https://github.com/iampranshu2003/RetrofitPostDemo">https://github.com/iampranshu2003/RetrofitPostDemo</a>)</p><h3>Conclusion</h3><p>In this tutorial, we learned how to send an HTTP POST request using Retrofit in Android. We covered:</p><ul><li>Setting up Retrofit and defining a POST method.</li><li>Sending data to a server and handling the response.</li><li>Displaying the results in the app.</li></ul><p>With this knowledge, you can now create, update, or delete resources on a server using Retrofit. Stay tuned for more tutorials on advanced Retrofit features!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e119d785a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering WorkManager in Android: Sequential and Parallel Chaining, and Periodic Work Requests]]></title>
            <link>https://medium.com/@iampranshu2003/mastering-workmanager-in-android-sequential-and-parallel-chaining-and-periodic-work-requests-e8b853ba1735?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b853ba1735</guid>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[android-workmanager]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 06:26:46 GMT</pubDate>
            <atom:updated>2025-02-07T06:26:46.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Welcome back to another deep dive into Android development. In this article, we’ll explore two powerful features of <strong>WorkManager</strong>: <strong>chaining tasks sequentially and in parallel</strong>, and <strong>scheduling periodic work requests</strong>. By the end of this guide, you’ll know how to schedule complex background tasks efficiently and reliably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SRyW8QOd9UAobjAa" /></figure><h3>Chaining Tasks with WorkManager</h3><h3>Why Chain Tasks?</h3><p>In real-world apps, background tasks often depend on each other. For example, you might need to:</p><ol><li>Filter images.</li><li>Compress them.</li><li>Upload them to a server.</li></ol><p>WorkManager allows you to chain these tasks <strong>sequentially</strong> or <strong>in parallel</strong>, ensuring they execute in the correct order or simultaneously, depending on your requirements.</p><h3>Step 1: Creating Worker Classes</h3><p>Let’s start by creating three worker classes:</p><ol><li><strong>FilteringWorker</strong>: Filters images.</li><li><strong>CompressingWorker</strong>: Compresses the filtered images.</li><li><strong>UploadWorker</strong>: Uploads the compressed images to the server.</li></ol><h4>FilteringWorker</h4><pre>class FilteringWorker(context: Context, params: WorkerParameters) : Worker(context, params) {<br>    override fun doWork(): Result {<br>        return try {<br>            for (i in 0..3000) {<br>                Log.d(&quot;FilteringWorker&quot;, &quot;Filtering $i&quot;)<br>            }<br>            Result.success()<br>        } catch (e: Exception) {<br>            Result.failure()<br>        }<br>    }<br>}</pre><h4>CompressingWorker</h4><pre>class CompressingWorker(context: Context, params: WorkerParameters) : Worker(context, params) {<br>    override fun doWork(): Result {<br>        return try {<br>            for (i in 0..3000) {<br>                Log.d(&quot;CompressingWorker&quot;, &quot;Compressing $i&quot;)<br>            }<br>            Result.success()<br>        } catch (e: Exception) {<br>            Result.failure()<br>        }<br>    }<br>}</pre><h4>UploadWorker</h4><pre>class UploadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {<br>    override fun doWork(): Result {<br>        return try {<br>            for (i in 0..3000) {<br>                Log.d(&quot;UploadWorker&quot;, &quot;Uploading $i&quot;)<br>            }<br>            Result.success()<br>        } catch (e: Exception) {<br>            Result.failure()<br>        }<br>    }<br>}</pre><h3>Step 2: Sequential Chaining</h3><p>To execute these tasks sequentially, use the beginWith() and then() methods provided by WorkManager.</p><pre>val filteringRequest = OneTimeWorkRequest.Builder(FilteringWorker::class.java).build()<br>val compressingRequest = OneTimeWorkRequest.Builder(CompressingWorker::class.java).build()<br>val uploadRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java).build()<br>WorkManager.getInstance(applicationContext)<br>    .beginWith(filteringRequest)<br>    .then(compressingRequest)<br>    .then(uploadRequest)<br>    .enqueue()</pre><p>When you run the app, you’ll see logs in Logcat showing the tasks executing in the correct order:</p><ol><li>FilteringWorker</li><li>CompressingWorker</li><li>UploadWorker</li></ol><h3>Step 3: Parallel Chaining</h3><p>Sometimes, you may need to execute tasks in parallel. For example, while filtering images on the device, you might also want to download additional images from a server.</p><p>To achieve this, create a MutableList of OneTimeWorkRequest objects and pass it to the beginWith() method.</p><pre>val filteringRequest = OneTimeWorkRequest.Builder(FilteringWorker::class.java).build()<br>val downloadRequest = OneTimeWorkRequest.Builder(DownloadingWorker::class.java).build()<br>val parallelWorkers = mutableListOf&lt;OneTimeWorkRequest&gt;()<br>parallelWorkers.add(filteringRequest)<br>parallelWorkers.add(downloadRequest)<br>WorkManager.getInstance(applicationContext)<br>    .beginWith(parallelWorkers)<br>    .then(compressingRequest)<br>    .then(uploadRequest)<br>    .enqueue()</pre><p>In this example:</p><ul><li>FilteringWorker and DownloadingWorker run in parallel.</li><li>Once both are complete, CompressingWorker and UploadWorker run sequentially.</li></ul><h3>Scheduling Periodic Work Requests</h3><h3>Why Use Periodic Work Requests?</h3><p>Some tasks need to run repeatedly at fixed intervals, such as syncing data or downloading updates. WorkManager’s PeriodicWorkRequest is perfect for these scenarios.</p><h3>Step 1: Creating a Periodic Work Request</h3><p>Let’s schedule the DownloadingWorker to run every 16 minutes.</p><pre>private fun setPeriodicWorkRequest() {<br>    val periodicWorkRequest = PeriodicWorkRequest.Builder(<br>        DownloadingWorker::class.java,<br>        16, TimeUnit.MINUTES<br>    ).build()<br>WorkManager.getInstance(applicationContext).enqueue(periodicWorkRequest)<br>}</pre><p><strong>Note</strong>: The minimum interval for a PeriodicWorkRequest is <strong>15 minutes</strong>.</p><h3>Step 2: Testing the Periodic Work Request</h3><p>To verify that the task runs at the specified interval, add a timestamp to the DownloadingWorker logs.</p><pre>class DownloadingWorker(context: Context, params: WorkerParameters) : Worker(context, params) {<br>    override fun doWork(): Result {<br>        return try {<br>            for (i in 0..3000) {<br>                Log.d(&quot;DownloadingWorker&quot;, &quot;Downloading $i at ${SimpleDateFormat(&quot;HH:mm:ss&quot;, Locale.getDefault()).format(Date())}&quot;)<br>            }<br>            Result.success()<br>        } catch (e: Exception) {<br>            Result.failure()<br>        }<br>    }<br>}</pre><p>Run the app and observe Logcat. You’ll see the task executing every 16 minutes.</p><h3>Key Takeaways</h3><ol><li><strong>Sequential Chaining</strong>: Use beginWith() and then() to execute tasks in a specific order.</li><li><strong>Parallel Chaining</strong>: Use a MutableList of OneTimeWorkRequest objects to run tasks simultaneously.</li><li><strong>Periodic Work Requests</strong>: Use PeriodicWorkRequest for tasks that need to run at fixed intervals (minimum 15 minutes).</li></ol><h3>Conclusion</h3><p>WorkManager is an incredibly versatile library for managing background tasks in Android. Whether you need to chain tasks sequentially or in parallel, or schedule periodic work, WorkManager has you covered. With these tools, you can build robust and efficient apps that handle complex background operations seamlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b853ba1735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering WorkManager in Android: A Comprehensive Guide 2]]></title>
            <link>https://medium.com/@iampranshu2003/mastering-workmanager-in-android-a-comprehensive-guide-2-f529f362ad28?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/f529f362ad28</guid>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-workmanager]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 06:19:25 GMT</pubDate>
            <atom:updated>2025-02-07T06:19:25.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone! Welcome back to another deep dive into Android development. Today, we’re going to explore <strong>WorkManager</strong>, one of the most powerful libraries for managing background tasks in Android. Whether you’re uploading files, syncing data, or performing other deferrable tasks, WorkManager ensures your tasks are executed reliably, even if the app exits or the device restarts.</p><p>In this article, we’ll walk through the basics of WorkManager, how to set constraints, and how to handle input and output data. By the end, you’ll have a solid understanding of how to use WorkManager effectively in your Android apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aC7rju9l1JtUFgtQ" /></figure><h3>Getting Started with WorkManager</h3><h3>Step 1: Setting Up the Project</h3><p>Let’s start by creating a new Android Studio project. Select <strong>Empty Activity</strong> and name it WorkManagerDemo1. Choose <strong>Kotlin</strong> as the language and set the minimum API level to <strong>26</strong>.</p><p>Once the project is created, the first thing we need to do is add the WorkManager dependencies to the app-level build.gradle file. You can find the latest dependencies on the <a href="https://developer.android.com/topic/libraries/architecture/workmanager">official WorkManager documentation</a>.</p><pre>dependencies {<br>    implementation &quot;androidx.work:work-runtime-ktx:2.8.1&quot;<br>}</pre><h3>Step 2: Creating a Worker Class</h3><p>The core component of WorkManager is the <strong>Worker class</strong>. This is where you define the background task you want to execute. Let’s create a new class called UploadWorker that extends androidx.work.Worker.</p><pre>class UploadWorker(context: Context, params: WorkerParameters) : Worker(context, params) {<br>override fun doWork(): Result {<br>        return try {<br>            // Simulate a background task<br>            for (i in 0..1000) {<br>                Log.d(&quot;UploadWorker&quot;, &quot;Processing $i&quot;)<br>            }<br>            Result.success()<br>        } catch (e: Exception) {<br>            Result.failure()<br>        }<br>    }<br>}</pre><p>The doWork() function is where you write the code for your background task. It must return a Result object, which can be either success(), failure(), or retry().</p><h3>Step 3: Scheduling a One-Time Work Request</h3><p>Now that we have our UploadWorker, let’s schedule it to run using WorkManager. In the MainActivity, create a function called setOneTimeWorkRequest().</p><pre>private fun setOneTimeWorkRequest() {<br>    val uploadRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java).build()<br>    WorkManager.getInstance(applicationContext).enqueue(uploadRequest)<br>}</pre><p>This creates a one-time work request and enqueues it using WorkManager. To trigger this task, let’s add a button to the activity_main.xml layout and set an OnClickListener in the MainActivity.</p><pre>button.setOnClickListener {<br>    setOneTimeWorkRequest()<br>}</pre><p>Run the app and check Logcat to see the logs from the UploadWorker.</p><h3>Observing Work Status with LiveData</h3><p>WorkManager provides a LiveData object called WorkInfo that allows you to observe the status of your work. Let’s modify our code to display the current state of the work in a TextView.</p><pre>val workManager = WorkManager.getInstance(applicationContext)<br>workManager.getWorkInfoByIdLiveData(uploadRequest.id).observe(this) { workInfo -&gt;<br>    textView.text = workInfo.state.name<br>}</pre><p>The WorkInfo object contains information about the work, such as its current state. WorkManager has four states:</p><ol><li><strong>BLOCKED</strong>: The work is blocked by other work in a chain.</li><li><strong>ENQUEUED</strong>: The work is waiting to run.</li><li><strong>RUNNING</strong>: The work is actively executing.</li><li><strong>SUCCEEDED</strong>: The work has completed successfully.</li></ol><p>To see the RUNNING state, increase the loop count in the UploadWorker.</p><h3>Adding Constraints to Work Requests</h3><p>One of the most powerful features of WorkManager is the ability to set <strong>constraints</strong> for your tasks. For example, you might want to run a task only when the device is charging or connected to Wi-Fi.</p><p>Let’s modify our UploadWorker to run only when the device is charging.</p><pre>val constraints = Constraints.Builder()<br>    .setRequiresCharging(true)<br>    .build()<br>val uploadRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java)<br>    .setConstraints(constraints)<br>    .build()</pre><p>To test this, change the battery status of your emulator. You’ll notice that the task only runs when the device is charging.</p><h3>Handling Input and Output Data</h3><p>Sometimes, you need to pass data to your worker or receive data back from it. WorkManager makes this easy with Data objects.</p><h3>Passing Input Data</h3><p>To pass input data, create a Data object and add it to the work request.</p><pre>val data = Data.Builder()<br>    .putInt(&quot;count&quot;, 1000)<br>    .build()<br>val uploadRequest = OneTimeWorkRequest.Builder(UploadWorker::class.java)<br>    .setInputData(data)<br>    .build()</pre><p>In the UploadWorker, retrieve the input data using inputData.</p><pre>val count = inputData.getInt(&quot;count&quot;, 0)</pre><h3>Receiving Output Data</h3><p>To send output data from the worker, create a Data object and pass it to the Result.</p><pre>val outputData = Data.Builder()<br>    .putString(&quot;finishTime&quot;, SimpleDateFormat(&quot;HH:mm:ss&quot;, Locale.getDefault()).format(Date()))<br>    .build()<br>return Result.success(outputData)</pre><p>In the MainActivity, retrieve the output data from the WorkInfo object.</p><pre>workManager.getWorkInfoByIdLiveData(uploadRequest.id).observe(this) { workInfo -&gt;<br>    if (workInfo.state == WorkInfo.State.SUCCEEDED) {<br>        val finishTime = workInfo.outputData.getString(&quot;finishTime&quot;)<br>        Toast.makeText(this, &quot;Task finished at $finishTime&quot;, Toast.LENGTH_SHORT).show()<br>    }<br>}</pre><h3>Conclusion</h3><p>WorkManager is an essential tool for managing background tasks in Android. It ensures your tasks are executed reliably, even under challenging conditions. In this article, we covered:</p><ul><li>Setting up WorkManager in a project.</li><li>Creating and scheduling workers.</li><li>Observing work status with LiveData.</li><li>Adding constraints to work requests.</li><li>Handling input and output data.</li></ul><p>you can check the code on my github repo(<a href="https://github.com/iampranshu2003/WorkManagerDemo">https://github.com/iampranshu2003/WorkManagerDemo</a>)</p><p>With these skills, you’re ready to tackle complex background tasks in your Android apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f529f362ad28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Background Tasks in Android with WorkManager: A Comprehensive Guide 1]]></title>
            <link>https://medium.com/@iampranshu2003/mastering-background-tasks-in-android-with-workmanager-a-comprehensive-guide-1-89c571a9f686?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c571a9f686</guid>
            <category><![CDATA[android-workmanager]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 05:50:13 GMT</pubDate>
            <atom:updated>2025-02-06T05:50:13.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8vwTgLUWeApxtPzW" /></figure><h3>Why WorkManager?</h3><p>Before WorkManager, developers had to rely on a combination of tools like <strong>Firebase JobDispatcher</strong>, <strong>JobScheduler</strong>, and <strong>AlarmManager</strong> with <strong>BroadcastReceiver</strong> to schedule background tasks. This approach was not only complex but also time-consuming, requiring developers to handle various constraints and requirements manually. WorkManager changes all that. Now, all you need to do is pass your task to WorkManager, and it will handle the rest. It intelligently decides which scheduler to use based on the device’s API level and other constraints.</p><ul><li><strong>For devices with API level less than 23</strong>, WorkManager uses a combination of <strong>BroadcastReceiver</strong> and <strong>AlarmManager</strong>.</li><li><strong>For devices with API level 23 or higher</strong>, it leverages <strong>JobScheduler</strong>.</li><li><strong>If your task involves Firebase</strong>, WorkManager will opt for <strong>Firebase JobDispatcher</strong>.</li></ul><h3>Advanced Features of WorkManager</h3><p>WorkManager isn’t just about simplifying task scheduling; it also offers a range of advanced features:</p><ul><li><strong>Chained Tasks</strong>: You can chain multiple tasks together, ensuring they run in a specific sequence.</li><li><strong>LiveData Support</strong>: WorkManager provides real-time status updates using <strong>LiveData</strong>, making it easier to monitor the progress of your tasks.</li><li><strong>Constraints</strong>: You can set constraints like requiring a network connection or sufficient battery level before a task runs.</li><li><strong>Resource Efficiency</strong>: WorkManager is designed to use minimal system resources, such as battery power, ensuring your app remains efficient.</li><li><strong>Compatibility</strong>: It handles compatibility across different Android versions seamlessly.</li><li><strong>Asynchronous Tasks</strong>: WorkManager supports asynchronous tasks, making it ideal for operations that need to run in the background without blocking the main thread.</li><li><strong>Periodic Tasks</strong>: It also supports periodic tasks, allowing you to schedule tasks that need to run at regular intervals.</li></ul><h3>When to Use WorkManager</h3><p>WorkManager is perfect for tasks that need to survive process death — meaning they should run even if the app is closed or the device is restarted. However, for tasks that don’t need to survive process death and can run in a background thread, you might not need WorkManager. In such cases, simpler solutions like <strong>coroutines</strong> or <strong>RxJava</strong> might be more appropriate.</p><h3>Types of Work Requests</h3><p>WorkManager supports two types of work requests:</p><ol><li><strong>Periodic Work Requests</strong>: These are tasks that need to run repeatedly at fixed intervals. For example, imagine an app for a sales team that needs to update the stock count every 30 minutes. WorkManager can handle this effortlessly by scheduling a periodic work request.</li><li><strong>One-Time Work Requests</strong>: These are tasks that need to run once, but with specific constraints. For instance, consider an app for a survey team where each member uploads survey records, including images, to a web server. WorkManager can schedule this task to run when the device has an internet connection and sufficient battery life.</li></ol><h3>Scheduling a Task with WorkManager</h3><p>Scheduling a task with WorkManager involves four basic steps:</p><ol><li><strong>Create a Subclass of the Worker Class</strong>: Define the task you want to execute.</li><li><strong>Create a WorkRequest</strong>: Specify whether it’s a one-time or periodic request.</li><li><strong>Enqueue the Request</strong>: Add the task to WorkManager’s queue.</li><li><strong>Get Status Updates</strong>: Monitor the task’s progress using LiveData.</li></ol><h3>Conclusion</h3><p>WorkManager is a powerful tool that simplifies background task management in Android apps. Whether you need to run tasks periodically or just once, WorkManager handles the complexities for you, ensuring your tasks run reliably and efficiently. In the next lesson, we’ll dive into scheduling our first task using WorkManager. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c571a9f686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Android Notifications: A Step-by-Step Guide 2]]></title>
            <link>https://medium.com/@iampranshu2003/mastering-android-notifications-a-step-by-step-guide-2-fda45518038a?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/fda45518038a</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[notification-button]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 21:48:13 GMT</pubDate>
            <atom:updated>2025-02-02T21:48:13.585Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous lessons, we learned how to create basic notifications and add tap actions to them. Now, let’s take it a step further and add <strong>action buttons</strong> to notifications. These buttons appear beneath the notification message and allow users to perform specific actions directly from the notification drawer, such as opening another activity or performing a task.</p><p>In this article, we’ll walk through how to add action buttons to notifications, configure them to trigger specific intents, and handle user interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*v73c0R1FHZg0fsKW.jpg" /></figure><h3>Step 1: Create New Activities</h3><p>To demonstrate action buttons, create two new activities: DetailsActivity and SettingsActivity.</p><ol><li>In Android Studio, right-click on your package name in the java directory.</li><li>Go to <strong>New &gt; Activity &gt; Empty Activity</strong>.</li><li>Name the first activity DetailsActivity and click <strong>Finish</strong>.</li><li>Repeat the process to create a second activity named SettingsActivity.</li></ol><h3>Design the Layouts</h3><ol><li>Open activity_details.xml and add a TextView :</li><li>just add text details in the text view</li></ol><h3>Step 2: Add Action Buttons to the Notification</h3><p>Action buttons are added to notifications using NotificationCompat.Action. Each action consists of:</p><ul><li>An <strong>icon</strong> (optional).</li><li>A <strong>title</strong> (displayed on the button).</li><li>A PendingIntent to handle the button click.</li></ul><h3>Step 2.1: Create Intents for the Actions</h3><ol><li>Create an Intent to open DetailsActivity:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8iNqRLOIOLUhH90Iy3TCQ.png" /></figure><h3>Step 2.2: Create PendingIntents for the Actions</h3><ol><li>Create a PendingIntent for DetailsActivity:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*Hbbp9xBUgVo6xf_LSSuT0A.png" /></figure><h3>Step 2.3: Create Notification Actions</h3><ol><li>Create an action for DetailsActivity:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7ARIn3kWCbK7v5Y8BX-Ww.png" /></figure><h3>Step 2.4: Add Actions to the Notification</h3><p>Update the NotificationCompat.Builder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KVDRdSw50V1CkgrYDWPUtA.png" /></figure><h3>Step 3: Run the App</h3><ol><li>Launch the app on an emulator or physical device.</li><li>Click the button to trigger the notification.</li><li>Swipe down to view the notification and its action buttons.</li><li>Tap the <strong>Details</strong> button to open DetailsActivity.</li></ol><p>you can check complete code on my github repo (<a href="https://github.com/iampranshu2003/notificationdemo2">https://github.com/iampranshu2003/notificationdemo2</a>)</p><p>Adding action buttons to notifications is a simple yet powerful way to make your app more interactive and user-friendly. In this article, we covered how to create actions, configure them to trigger specific intents, and handle user interactions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fda45518038a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Android Notifications : A Step-by-Step Guide 1]]></title>
            <link>https://medium.com/@iampranshu2003/mastering-android-notifications-a-step-by-step-guide-1-d1d1f8f63f29?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1d1f8f63f29</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[notification-service]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 08:30:44 GMT</pubDate>
            <atom:updated>2025-02-02T08:30:44.269Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Android Notifications : A Step-by-Step Guide 1</h3><p>Notifications are a crucial part of modern mobile applications. They allow apps to communicate with users outside of their main user interface, providing timely information, reminders, or even enabling users to take actions directly from the notification itself.</p><p>In this article, we’ll explore how to create basic notifications in Android , and then gradually dive into more advanced features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0Xeg_XY1GqCgQLY7.jpg" /></figure><h3>What Are Notifications?</h3><p>Notifications are messages that apps display outside of their main UI. They are used for:</p><ul><li><strong>Reminders</strong>: Notify users about upcoming events or tasks.</li><li><strong>Communication</strong>: Deliver messages or updates.</li><li><strong>Timely Information</strong>: Provide real-time information, such as weather alerts or news updates.</li></ul><p>When an app issues a notification, it first appears as an icon in the status bar. Users can swipe down to open the notification drawer, where they can view more details and take actions. Notifications remain visible until dismissed by the app or the user.</p><p>With Android 5.0 (Lollipop) and later, notifications can also appear as <strong>heads-up notifications</strong> (floating windows) or on the <strong>lock screen</strong>, depending on the app’s settings and the device’s state.</p><h3>Getting Started: Creating a Basic Notification</h3><p>Let’s start by creating a simple Android project to demonstrate how to create and display a basic notification.</p><h3>Step 1: Set Up the Project</h3><ol><li>Open Android Studio and create a new project.</li><li>Name the project NotificationDemo.</li><li>Set the <strong>minimum SDK to API 26 (Android 8.0)</strong>. This is important because many modern notification features require at least API 26.</li><li>add permission in manifest file</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*KE2hT9tmza88sDOSIdyqpg.png" /></figure><h3>Step 2: Design the Layout</h3><ol><li>Open activity_main.xml and add a button</li><li>This button will trigger the notification when clicked.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*aP9-r0bsmRqAXfbXfrVAhw.png" /></figure><h3>Step 3: Implement the Notification Logic</h3><ol><li>Open MainActivity.kt.</li><li>In the onCreate function, set an OnClickListener for the button:</li></ol><pre>binding.button.setOnClickListener {<br>    displayNotification()<br>}</pre><ol><li>Create a displayNotification() function to handle the notification logic.</li></ol><h3>Step 4: Create a Notification Manager</h3><p>Starting from Android 8.0 (API 26), notifications must be assigned to a <strong>notification channel</strong>. A channel groups notifications with similar behavior and importance.</p><ol><li>Define a channel ID and then define a notificationManager instance</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zlH2ofbMyDc1YIxu5Wt4g.png" /></figure><ol><li>create notificationManager instance</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4t5FSOa5CPVD5NwXcIxH4w.png" /></figure><ol><li>Create a function to set up the notification channel:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qVanmNjCH_ZIJK63ccM2g.png" /></figure><ol><li>Call this function in onCreate to create the channel when the app starts:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9KKBuTvvsU3mL70QsJk1Q.png" /></figure><h3>Step 5: Build and Display the Notification</h3><p>Now, let’s implement the displayNotification() function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xmUdSfy4eMU0SN-QO669pw.png" /></figure><h3>Step 6: Request Notification Permissions (Android 13+)</h3><p>Starting from Android 13 (API 33), apps need to explicitly request the POST_NOTIFICATIONS permission. Add the following code to request the permission:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKoYW2hZsjfKkf6VC-SuZQ.png" /></figure><h3>Step 7: Run the App</h3><ol><li>Launch the app on an emulator or physical device.</li><li>Click the button to trigger the notification.</li><li>You should see a notification icon in the status bar. Swipe down to view the full notification</li></ol><h3>Conclusion</h3><p>Notifications are a powerful way to keep users informed and engaged with your app. With Android, creating and managing notifications has been easier. In this article, we covered the basics of creating a notification channel and displaying a simple notification. you can see complete code on my repo <a href="https://github.com/iampranshu2003/NotificationDemo1">https://github.com/iampranshu2003/NotificationDemo1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1d1f8f63f29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit with Coroutines : Query and Path Parameters, and HttpLoggingInterceptor]]></title>
            <link>https://medium.com/@iampranshu2003/retrofit-with-coroutines-query-and-path-parameters-and-httplogginginterceptor-9d3d6f0c9014?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3d6f0c9014</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[retrofit2]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 07:45:03 GMT</pubDate>
            <atom:updated>2025-01-31T15:25:54.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Retrofit with Coroutines : Query and Path Parameters, and HttpLoggingInterceptor and Timeout Settings</h3><p>In this article, we’ll explore how to use Retrofit with Coroutines to handle <strong>query parameters</strong>, <strong>path parameters</strong>,how to log network operations using <strong>HttpLoggingInterceptor</strong>, and configure <strong>timeout settings</strong> to handle slow or unstable network connections.(here we will continue from my last article on retrofit with coroutines project <a href="https://medium.com/@iampranshu2003/retrofit-with-kotlin-coroutines-37a3fc11b881">https://medium.com/@iampranshu2003/retrofit-with-kotlin-coroutines-37a3fc11b881</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ur79eoNGq-ylXxuW.jpg" /></figure><h3>1. Query Parameters in Retrofit</h3><h3>Use Case: Fetching Sorted Data</h3><p>Imagine you want to display all the albums belonging to a specific user, say the third user. To achieve this, you’ll need to make an HTTP GET request with a <strong>query parameter</strong> to filter the data.</p><h3>How Query Parameters Work</h3><p>A query parameter is added to the URL after a question mark (?). For example:</p><pre>https://jsonplaceholder.typicode.com/albums?userId=3</pre><p>This URL fetches all albums where the userId is 3.</p><h3>Implementing Query Parameters in Retrofit</h3><h4>Step 1: Define the API Interface</h4><p>In your AlbumService interface, declare a function to fetch sorted albums by userId:</p><pre>interface AlbumService {<br>    @GET(&quot;albums&quot;)<br>    suspend fun getSortedAlbums(@Query(&quot;userId&quot;) userId: Int): Response&lt;List&lt;Album&gt;&gt;<br>}</pre><ul><li>@GET(&quot;albums&quot;): Specifies the endpoint.</li><li>@Query(&quot;userId&quot;): Adds the query parameter userId to the request.</li><li>suspend: Marks the function as a Coroutine.</li></ul><h4>Step 2: Call the Function</h4><p>In your MainActivity, call the getSortedAlbums function:</p><pre>val response = retService.getSortedAlbums(3)<br>if (response.isSuccessful) {<br>    val albums = response.body()<br>    // Display albums in the UI<br>}</pre><p>When you run the app, you’ll see only the albums with userId = 3.</p><h3>2. Path Parameters in Retrofit</h3><h3>Use Case: Fetching a Single Album</h3><p>Sometimes, you may need to fetch a single resource using its unique identifier. For example, fetching an album by its id. This is where <strong>path parameters</strong> come into play.</p><h3>How Path Parameters Work</h3><p>Path parameters are defined as named replacements in the URL. For example:</p><pre>https://jsonplaceholder.typicode.com/albums/3</pre><p>This URL fetches the album with id = 3.</p><h3>Implementing Path Parameters in Retrofit</h3><h4>Step 1: Define the API Interface</h4><p>In your AlbumService interface, declare a function to fetch a single album by id:</p><pre>interface AlbumService {<br>    @GET(&quot;albums/{id}&quot;)<br>    suspend fun getAlbum(@Path(&quot;id&quot;) albumId: Int): Response&lt;Album&gt;<br>}</pre><ul><li>@GET(&quot;albums/{id}&quot;): Specifies the endpoint with a path parameter {id}.</li><li>@Path(&quot;id&quot;): Replaces {id} in the URL with the provided albumId.</li></ul><h4>Step 2: Call the Function</h4><p>In your MainActivity, call the getAlbum function and display the result:</p><pre>val response = retService.getAlbum(3)<br>if (response.isSuccessful) {<br>    val album = response.body()<br>    Toast.makeText(this, album?.title, Toast.LENGTH_SHORT).show()<br>}</pre><p>When you run the app, a Toast message will display the title of the album with id = 3.</p><h3>3. HttpLoggingInterceptor</h3><h3>Why Use HttpLoggingInterceptor?</h3><p>When debugging network operations, it’s crucial to see the details of the requests and responses. The HttpLoggingInterceptor from OkHttp helps you log these details, making it easier to identify issues.</p><h3>Implementing HttpLoggingInterceptor</h3><h4>Step 1: Add Dependency</h4><p>Ensure you have the following dependency in your build.gradle file:</p><pre>implementation &quot;com.squareup.okhttp3:logging-interceptor:4.9.3&quot;</pre><h4>Step 2: Configure the Interceptor</h4><p>In your RetrofitInstance class, set up the HttpLoggingInterceptor:</p><pre>val interceptor = HttpLoggingInterceptor().apply {<br>    level = HttpLoggingInterceptor.Level.BODY<br>}<br>val client = OkHttpClient.Builder()<br>    .addInterceptor(interceptor)<br>    .build()<br>val retrofit = Retrofit.Builder()<br>    .baseUrl(BASE_URL)<br>    .client(client)<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><ul><li>HttpLoggingInterceptor.Level.BODY: Logs the request and response bodies along with headers.</li><li>Other levels include BASIC (request/response lines) and HEADERS (request/response lines and headers).</li></ul><h4>Step 3: View Logs in Logcat</h4><p>When you run the app, open Logcat to see the logs generated by the interceptor. For example:</p><pre>--&gt; GET https://jsonplaceholder.typicode.com/albums/3<br>&lt;-- 200 OK https://jsonplaceholder.typicode.com/albums/3<br>Content-Type: application/json; charset=utf-8<br>{<br>  &quot;userId&quot;: 1,<br>  &quot;id&quot;: 3,<br>  &quot;title&quot;: &quot;omnis laborum odio&quot;<br>}</pre><p>These logs provide insights into the network operations, including the request URL, response code, headers, and body.</p><h3>4. Configuring Timeout Settings in Retrofit</h3><h3>Why Configure Timeouts?</h3><p>In real-world scenarios, network conditions can vary significantly. For example:</p><ul><li>High-speed internet: Works fine with default settings.</li><li>Slow or unstable internet: May cause timeouts, leading to failed requests.</li></ul><h3>Solution: Increase Timeout Settings</h3><p>By increasing the <strong>connection timeout</strong>, <strong>read timeout</strong>, and <strong>write timeout</strong>, the app was able to handle slower connections effectively.</p><h3>Implementing Timeout Settings</h3><h4>Step 1: Define Custom Timeouts</h4><p>In your RetrofitInstance class, configure the OkHttpClient with custom timeouts:</p><pre>val client = OkHttpClient.Builder()<br>    .connectTimeout(30, TimeUnit.SECONDS) // 30 seconds to connect<br>    .readTimeout(20, TimeUnit.SECONDS)    // 20 seconds to read data<br>    .writeTimeout(25, TimeUnit.SECONDS)   // 25 seconds to write data<br>    .build()<br>val retrofit = Retrofit.Builder()<br>    .baseUrl(BASE_URL)<br>    .client(client) // Attach the custom OkHttpClient<br>    .addConverterFactory(GsonConverterFactory.create())<br>    .build()</pre><h4>Step 2: Explanation of Timeout Parameters</h4><ul><li><strong>Connect Timeout</strong>: Time to establish a connection with the server.</li><li><strong>Read Timeout</strong>: Maximum time between data packets when waiting for a response.</li><li><strong>Write Timeout</strong>: Maximum time between data packets when sending data to the server.</li></ul><h4>Step 3: Best Practices</h4><ul><li>Use default timeouts (10 seconds) unless specific requirements demand longer durations.</li><li>Adjust timeouts based on:</li><li><strong>Internet speed</strong> in target regions.</li><li><strong>Server performance</strong>.</li><li><strong>Device performance</strong>.</li></ul><h3>5. Refactoring for Readability</h3><p>To make your MainActivity code cleaner, you can refactor it into separate functions:</p><pre>class MainActivity : AppCompatActivity() {<br>private lateinit var retService: AlbumService<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        retService = RetrofitInstance.getRetrofitInstance().create(AlbumService::class.java)<br>        fetchSortedAlbums()<br>        fetchAlbumById()<br>    }<br>    private fun fetchSortedAlbums() {<br>        lifecycleScope.launch {<br>            val response = retService.getSortedAlbums(3)<br>            if (response.isSuccessful) {<br>                val albums = response.body()<br>                // Update UI with albums<br>            }<br>        }<br>    }<br>    private fun fetchAlbumById() {<br>        lifecycleScope.launch {<br>            val response = retService.getAlbum(3)<br>            if (response.isSuccessful) {<br>                val album = response.body()<br>                Toast.makeText(this@MainActivity, album?.title, Toast.LENGTH_SHORT).show()<br>            }<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>In this article, we explored how to use <strong>query parameters</strong> and <strong>path parameters</strong> in Retrofit with Coroutines. We also learned how to log network operations using HttpLoggingInterceptor and configure <strong>timeout settings</strong> to handle slow or unstable network connections.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3d6f0c9014" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrofit with kotlin coroutines]]></title>
            <link>https://medium.com/@iampranshu2003/retrofit-with-kotlin-coroutines-37a3fc11b881?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a3fc11b881</guid>
            <category><![CDATA[coroutines-in-kotlin]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[retrofit]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 22:53:48 GMT</pubDate>
            <atom:updated>2025-01-30T22:53:48.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello every one today we will revise Retrofit. Retrofit removes the complexities of network communication, allowing developers to focus on defining API endpoints and handling responses. With the latest versions of Retrofit, <strong>Kotlin Coroutines</strong> are fully supported, eliminating the need for callbacks and reducing the amount of code significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zns07nfoA7AeQQl1.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*WMj_jTXnbSi7_q0yaRtFCw.png" /><figcaption>link for the gson and retrofit dependency (<a href="https://square.github.io/retrofit/">https://square.github.io/retrofit/</a>)</figcaption></figure><p>then add dependency for coroutines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drXHb94mDRImJlM0AHuILw.png" /><figcaption>link for coroutines dependency(<a href="https://github.com/Kotlin/kotlinx.coroutines">https://github.com/Kotlin/kotlinx.coroutines</a>)</figcaption></figure><p>then add dependency for viewmodel ,livedata don’t add ksp</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*S9QhW9vOxm7yrzG3j_0p8w.png" /><figcaption><a href="https://developer.android.com/jetpack/androidx/releases/lifecycle">https://developer.android.com/jetpack/androidx/releases/lifecycle</a></figcaption></figure><p>then add okhttp3:logging-interceptor dependency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*uN1-kykeiG9RdSIatz3K5w.png" /><figcaption><a href="https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor">https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor</a></figcaption></figure><p>now in manifest file add three permissions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*OOqliXREnWYBXWwPjyQ7og.png" /></figure><p>now we will be using an album api <a href="https://jsonplaceholder.typicode.com/albums">https://jsonplaceholder.typicode.com/albums</a><br>it contains userId, id and title</p><p>now we will convert json to coresponding data class using json to kotlin class android studio plugin</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R2Kjyv5Yz6Vjy3L8OER3RQ.png" /></figure><p>Now create a new kotlin data class file from JSON , copy the json format and paste inside it give it a name (Albums) then click generate two data classes will be generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KiiaYTKGHlamv12mTxvwlw.png" /></figure><p>now we will create interface with functions and url endpoints <br>create an interface (AlbumService) and add function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*16BF2f9cTrRHMkU0G6dONg.png" /></figure><p>now we will create a Retrofit instance using the Builder function of the Retrofit class .<br>create a kotlin class (retrofit Instance) then add companion object</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sqDRYIPml0PYm9NYuloG4Q.png" /></figure><p>now we will write code to fetch the albums from the api in main Activity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBK1wh0mUEqY_dV2Qton9Q.png" /></figure><p>you can see the output on screen by appending it on text view</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weBSqfM8DwIWpixxqc_kLw.png" /><figcaption>in activity_main.xml file add a scroll view and add textview to it with id textView</figcaption></figure><p>you can check the code on my github repo (<a href="https://github.com/iampranshu2003/RetrofitDemo1">https://github.com/iampranshu2003/RetrofitDemo1</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a3fc11b881" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Room Database Migrations : AutoMigrations part 1]]></title>
            <link>https://medium.com/@iampranshu2003/room-database-migrations-automigrations-part-1-56fe18c8e03a?source=rss-f7f188a5a803------2</link>
            <guid isPermaLink="false">https://medium.com/p/56fe18c8e03a</guid>
            <category><![CDATA[android-room-database]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[database-migration]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Pranshu Gupta]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 13:18:38 GMT</pubDate>
            <atom:updated>2025-01-30T13:18:38.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Room Database Migrations : AutoMigrations part 1</h3><p>When developing Android applications, adding new features or modifying existing ones often requires changes to the database schema. These changes can range from simple tasks like adding a new column to a table, to more complex operations like splitting a table. However, it’s crucial to ensure that user data is preserved during these updates. Careless migrations can lead to data loss, resulting in a poor user experience.</p><p>In this article, we’ll explore how to use Room’s automated migrations to add a new column to an existing table. We’ll start with a simple Room database app and walk through the steps required to perform the migration.</p><h3>Lets start implementing Room Database Migration by taking a project as example !!</h3><p>The project is a basic Room database app with the following components:</p><ol><li><strong>Entity Class (</strong><strong>Student.kt)</strong>:</li></ol><ul><li>A data class named Student marked with the @Entity annotation.</li><li>Creates a table named student_info with two fields: student_id (primary key, auto-generated) and student_name.</li></ul><p><strong>2. DAO Interface (</strong><strong>StudentDao.kt)</strong>:</p><ul><li>Contains a single function, insertStudent, to insert a student into the database.</li></ul><p><strong>3. Room Database Class (</strong><strong>AppDatabase.kt)</strong>:</p><ul><li>Defines the database with version number 1.</li><li>Includes a singleton pattern for database instantiation (best practice).</li></ul><p><strong>4. MainActivity</strong>:</p><ul><li>Retrieves the DAO instance and saves student names to the database.</li><li>The UI consists of an EditText for entering a name and a Button to submit the data.</li></ul><h3>Step 1: Export the Current Schema</h3><p>Before making any changes, we need to export the current database schema as a JSON file. This schema serves as the blueprint for the database structure.</p><ol><li>In the app-level build.gradle file.</li><li>Ensure the Room version is at least 2.4.0-alpha01</li><li>Add the following code under the defaultConfig section to specify the schema export location:</li></ol><pre>kapt {<br>    arguments {<br>        arg(&quot;room.schemaLocation&quot;, &quot;$projectDir/schemas&quot;)<br>    }<br>}</pre><ol><li>Sync the project and rebuild it.</li><li>Switch to <strong>Project Files</strong> mode and navigate to the schemas directory. You’ll find a 1.json file representing the schema of the current database version.</li></ol><h3>Step 2: Modify the Entity Class</h3><p>Next, update the Student entity class to include the new email field:</p><pre>@Entity(tableName = &quot;student_info&quot;)<br>data class Student(<br>    @PrimaryKey(autoGenerate = true) val student_id: Int,<br>    @ColumnInfo(name = &quot;student_name&quot;) val name: String,<br>    @ColumnInfo(name = &quot;student_email&quot;, defaultValue = &quot;No Email&quot;) val email: String<br>)</pre><ul><li>The defaultValue ensures that existing records have a placeholder value for the new column.</li></ul><h3>Step 3: Update the Database Version</h3><p>In the AppDatabase class, increment the database version number to 2 and define the auto-migration:</p><pre>@Database(<br>    entities = [Student::class],<br>    version = 2,<br>    autoMigrations = [<br>        AutoMigration(from = 1, to = 2)<br>    ]<br>)<br>abstract class AppDatabase : RoomDatabase() {<br>    // Database code...<br>}</pre><h3>Step 4: Update the UI and Logic</h3><ol><li>Modify the activity_main.xml layout to include an EditText for the email address.</li><li>Update MainActivity to handle the new email field:</li></ol><pre>val email = emailEditText.text.toString()<br>val student = Student(name = name, email = email)<br>studentDao.insertStudent(student)</pre><ol><li>Rebuild the project and check the schemas directory. You should now see a 2.json file representing the updated schema.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56fe18c8e03a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>