<?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 Sandeep Kamath on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Kamath on Medium]]></description>
        <link>https://medium.com/@mssandeepkamath?source=rss-a514c7d38193------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*upNt6DuLm856DgBJPmpKcg.jpeg</url>
            <title>Stories by Sandeep Kamath on Medium</title>
            <link>https://medium.com/@mssandeepkamath?source=rss-a514c7d38193------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:37:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mssandeepkamath/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[Why Most Monitoring Dashboards Are Useless]]></title>
            <link>https://medium.com/@mssandeepkamath/why-most-monitoring-dashboards-are-useless-b3dd1f6d989d?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3dd1f6d989d</guid>
            <category><![CDATA[site-reliability-engineer]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 15:24:24 GMT</pubDate>
            <atom:updated>2026-03-01T15:31:58.751Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me say this straight. Most monitoring dashboards look very impressive.</p><p>50 panels.<br>colors.<br>Graphs dancing every 5 seconds. CPU, memory, disk, network, threads, load, temperature of Mars probably.</p><p>And yet… When something actually breaks? Nobody knows what to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*86_hQJSsAjFotVO544B4cA.png" /></figure><h3>The “Looks Good” Problem</h3><p>I have seen dashboards that look like a cockpit of a spaceship.</p><p>But during an incident the conversation usually goes like this:</p><p>“CPU is high.” Okay… but is that the problem? Memory looks fine.<br>“Okay… so why are users screaming? Network spike? Normal or abnormal?”</p><p>We collect everything. But we understand nothing and <strong>That’s the problem.</strong></p><h3>Data Is Not The Same As Decisions</h3><p>A dashboard should help you make a decision, Not admire colorful graphs.</p><p>Ask this simple question:</p><p>If this panel goes red, what exactly will I do? If the answer is:</p><ul><li>“Hmm let’s see more metrics”</li><li>“Maybe restart the service? Not sure actually”</li></ul><p>Then that panel is decoration. Harsh, but true.</p><h3>The Graph Hoarding Habit</h3><p>Engineers love adding panels. I know because I’ve done it.</p><p>“Oh this metric might be useful one day. Let’s also add per-core CPU. Also per-thread. Also per-process :D”</p><p>Before you know it, you need a 32-inch monitor just to see the dashboard. More panels do not mean more clarity. They mean more cognitive load.</p><p>And during an incident, cognitive load is the real enemy.</p><h3>Stop Monitoring CPU Like It’s The Final Boss</h3><p>Let’s talk about the most abused metric ever.</p><p><strong>CPU usage.</strong></p><p>People see 90% CPU and panic, But wait.</p><p>Is the system throttling?<br>Is latency increasing?<br>Are requests failing?<br>Is queue depth increasing? Or is it just doing its job efficiently?</p><p>High CPU is not a problem, but High CPU + user impact is a problem and There is a difference.</p><p>We alert on symptoms without checking if users even care. That’s how alert fatigue is born.</p><h3>Dashboards Without Context Are Useless</h3><p>Imagine this:<br>CPU: 70%<br>Memory: 65%<br>Disk: 40%<br>Network: fluctuating</p><p>Is that good? Is that bad? You don’t know. Because there is no baseline.</p><p>No SLO.<br>No “normal range”.<br>No historical comparison.</p><p>We show raw numbers without meaning. It’s like showing someone heart rate without telling them if they’re running or sleeping.<strong> Context is everything.</strong></p><h3>Monitoring vs Observability</h3><p>Monitoring should answer one question: Is something broken enough to act on?</p><blockquote>Observability is for exploration. Monitoring is for action.</blockquote><p>When we mix both into one mega-dashboard, we confuse everyone.</p><p>Developers want debugging signals.<br>SREs want reliability signals.<br>Management wants uptime summary.</p><p>But we give everyone the same chaos.</p><h3>What Actually Makes a Good Dashboard</h3><p>Here’s what I’ve learned the hard way:</p><ol><li>Every panel must <strong>justify </strong>its existence.</li><li>Show <strong>trends</strong>, not just current values.</li><li><strong>Percentiles (p95, p50, p30..) </strong>are better than averages.</li><li>Organize by user <strong>impact</strong>, not by system component.</li><li>If an alert exists, it should <strong>map </strong>clearly to a dashboard view.</li><li><strong>Fewer </strong>panels &gt; more panels.</li></ol><p>If removing a panel changes nothing about how you operate the system, remove it. Brutal rule, Very effective.</p><h3>The Real Test</h3><p>Next time you open your dashboard, ask:</p><ul><li>What question is this dashboard answering?</li><li>If users complain right now, where do I look first?</li><li>If everything turns red, do I actually know the priority?</li><li>Can a new engineer understand this in 2 minutes?</li></ul><p>If the answer is no, your dashboard is just a wall of graphs.</p><h3>Final Thought</h3><p>Monitoring is not about collecting data. It is about reducing uncertainty during chaos. <strong>If your dashboard doesn’t help during chaos, it’s just a colorful wallpaper.</strong></p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3dd1f6d989d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a simple Discord bot using Go]]></title>
            <link>https://medium.com/@mssandeepkamath/building-a-simple-discord-bot-using-go-12bfca31ad5d?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/12bfca31ad5d</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[bots]]></category>
            <category><![CDATA[discord]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sat, 15 Apr 2023 19:00:18 GMT</pubDate>
            <atom:updated>2023-04-15T19:00:18.048Z</atom:updated>
            <content:encoded><![CDATA[<p>This article offers tutorials on how to build a Discord `Hello World` bot using Golang.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQmcAHc-r9t0pXqZlYC1qg.png" /><figcaption>Self made image</figcaption></figure><p>We will be using DiscordGo to build our very first bot, DiscordGo is a <a href="https://golang.org/">Go</a> package that provides low level bindings to the <a href="https://discord.com/">Discord</a> chat client API. DiscordGo has nearly complete support for all of the Discord API endpoints, WebSocket interface, and voice interface.</p><blockquote>GitHub repository: <a href="https://github.com/bwmarrin/discordgo">https://github.com/bwmarrin/discordgo</a></blockquote><p>First, you need to create a application by logging into your Discord developer portal.</p><p>Discord Setup Steps:</p><p>1. Redirect to : h<a href="https://discord.com/developers/applications">ttps://discord.com/developers/application</a>s<br>2. Click on New Application button and provide any name to your application. <br><em>Note: The application is not the bot</em><br>3. On the left menu, select Bot and then click on Add Bot button.<br>4. Uncheck the public bot check box.<br>5. Click the Reset Token button, to generate a Token ID.<br>6. Go to URL Generator under OAuth2 on the left, and provide scope as Bot, and permissions such as Receive Message, Send Message, Send Message in Thread.<br>7. Copy the URL generated at the bottom, after the permission are set.<br>8. Go to that URL and add the bot to any of your server, after all these steps you should be having a Token ID and Bot(offline) in your server.</p><p>Lets now build a Hello world bot using Golang, so for that create a project with two files, main.go and bot.go</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*dztmmGXmQbYfgUpEScqumg.png" /><figcaption>project structure</figcaption></figure><p>Open the terminal and intialize a module,</p><pre>go mod init example.com/hello_world_bot</pre><p>The go.mod file that got generated defines the module’s module path, which is also the import path used for the root directory, and its dependency requirements, which are the other modules needed for a successful build.</p><p>Next, add the DiscordGo dependency using the following command,</p><pre>go get github.com/bwmarrin/discordgo</pre><p>In main.go ,</p><pre>package main<br><br>import bot &quot;example.com/hello_world_bot/Bot&quot;<br><br>func main() {<br> bot.BotToken = &quot;DISCORD TOKEN ID&quot;<br> bot.Run() // call the run function of bot/bot.go<br>}</pre><p>In bot/bot.go ,</p><pre>package bot<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;os&quot;<br> &quot;os/signal&quot;<br> &quot;strings&quot;<br><br> &quot;github.com/bwmarrin/discordgo&quot;<br>)<br><br>var BotToken string<br><br>func checkNilErr(e error) {<br> if e != nil {<br>  log.Fatal(&quot;Error message&quot;)<br> }<br>}<br><br>func Run() {<br><br> // create a session<br> discord, err := discordgo.New(&quot;Bot &quot; + BotToken)<br> checkNilErr(err)<br><br> // add a event handler<br> discord.AddHandler(newMessage)<br><br> // open session<br> discord.Open()<br> defer discord.Close() // close session, after function termination<br><br> // keep bot running untill there is NO os interruption (ctrl + C)<br> fmt.Println(&quot;Bot running....&quot;)<br> c := make(chan os.Signal, 1)<br> signal.Notify(c, os.Interrupt)<br> &lt;-c<br><br>}<br><br>func newMessage(discord *discordgo.Session, message *discordgo.MessageCreate) {<br><br> /* prevent bot responding to its own message<br> this is achived by looking into the message author id<br> if message.author.id is same as bot.author.id then just return<br> */<br> if message.Author.ID == discord.State.User.ID {<br>  return<br> }<br><br> // respond to user message if it contains `!help` or `!bye`<br> switch {<br> case strings.Contains(message.Content, &quot;!help&quot;):<br>  discord.ChannelMessageSend(message.ChannelID, &quot;Hello World😃&quot;)<br> case strings.Contains(message.Content, &quot;!bye&quot;):<br>  discord.ChannelMessageSend(message.ChannelID, &quot;Good Bye👋&quot;)<br>  // add more cases if required<br> }<br><br>}</pre><p>I have added few comments for better understanding, but most of the functions and lines are self explanatory.</p><p>Finally its time to run the bot, for that use the following command,</p><pre>go run main.go</pre><p>We can also first build the project and then run the executable file using following command,</p><pre>go build<br>.\hello_world_bot.exe</pre><p>When you run the project, the bot turns toonline state on discord. Just type !help or !bye and the bot should respond without error.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMb5mCndN44mDwHDNgB4DA.png" /><figcaption>Bot response image</figcaption></figure><p>That’s pretty much all for the Hello World Discord bot. Here is a more better example of Discord Weather Bot.</p><p><a href="https://github.com/mssandeepkamath/discord-go-weather">GitHub - mssandeepkamath/discord-go-weather</a></p><p>It’s also recommended to use environment variable rather than exposing the TOKEN ID’s. Have a look at the .envfile implementation in the above example.</p><p>The article’s main goal was to show how straightforward it is to develop a simple Discord bot. I sincerely apologise if the article had any inaccuracies. If you found it helpful, kindly give it an upvote.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12bfca31ad5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Morris Tree Traversal — The  O(N) Time and O(1) Space Algorithm]]></title>
            <link>https://medium.com/@mssandeepkamath/morris-tree-traversal-the-o-n-time-and-o-1-space-algorithm-5d2d2d47814a?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d2d2d47814a</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[in-order-traversal]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[trees]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 20:23:45 GMT</pubDate>
            <atom:updated>2025-08-21T21:08:13.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>Morris Tree Traversal — The O(N) Time and O(1) Space Algorithm</h3><p>This article is about the Morris Traversal Algorithm, which is a tree traversal algorithm that eliminates the use of recursion or stack.</p><p>So before proceeding, its important to ask yourself a question.</p><blockquote>Why do we want a recursion or a stack to implement In-order tree traversal?</blockquote><p>The core logic behind in-order tree traversal is to process left subtree first, then the root and then finally process the right subtree!.<br>Once you have processed the left subtree there a need to return back to root, and since we have only “left” and “right” pointers in the tree and there is no such pointer as “top” we need to store the root. That’s the reason why we use stack or recursion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YXco5pVeOYNrwwYN.png" /><figcaption>Source: AlgoDaily</figcaption></figure><p>Ok, so now how do we eliminate the process of returning back to root after we process the left subtree? The whole point of Morris Traversal Algorithm for in-order traversal is “Eliminating the need of returning back to root”.</p><p>We know for sure that in in-order traversal, the root of the tree is processed only after completely processing the left subtree, Therefore we move the root to right of left subtree until we find that there is a left tree. If we continuously follow the process we come to a condition where our tree is a right skewed tree! Thus we can conclude that Morris Traversal is all about converting a binary tree to right skewed tree. Lets understand it with diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3-TQCbKhCZvngLM26PDd7A.png" /><figcaption>morris traversal</figcaption></figure><p><strong>Algorithm:</strong></p><ol><li>Keep hold of current_root, and check if left child exists.</li></ol><ul><li>If Yes, then go to the right most node of left child and make it point to the current_root .</li><li>Make current_root’s left null.</li><li>If No, then print the value of node and move to right.</li></ul><p>2. Follow this until current_root exists.</p><p><strong>Implementation:</strong></p><pre>vector&lt;int&gt; inorderTraversal(TreeNode *root)<br>{<br><br>    vector&lt;int&gt; v;<br>    TreeNode *cur = root;<br>    TreeNode *prev = NULL;<br>    TreeNode *temp = NULL;<br><br>  // run algorithm until root exists<br>    while (cur)<br>    {<br>        // if left child exists<br>        if (cur-&gt;left)<br>        {<br>            prev=cur-&gt;left; // catch hold of left child<br>           <br>            while(prev-&gt;right) // go to right most node of left child<br>                prev=prev-&gt;right;<br>        <br>            prev-&gt;right=cur; // make it point to the root<br><br>            temp=cur;<br>            cur=cur-&gt;left;<br><br>            temp-&gt;left=NULL; // make left of root null<br>        }<br>        else<br>        {<br>            v.push_back(cur-&gt;val); // print the node value<br>            cur=cur-&gt;right; // move to right child (because left child doesn&#39;t exist)<br>        }<br>    }<br><br>    return v;<br>}</pre><p><strong>Time and Space Complexity</strong>:</p><p>TC: O(N) // where N is the number of nodes in the tree<br>ASC: O(1) // no use of stack or recursion</p><p>That’s all for the article, I sincerely apologies if the article had any inaccuracies. If you found it helpful, kindly give it an upvote.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d2d2d47814a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Augmented-Reality Android application]]></title>
            <link>https://levelup.gitconnected.com/building-a-augmented-reality-android-application-4d14619559d1?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d14619559d1</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 16:18:52 GMT</pubDate>
            <atom:updated>2023-07-18T18:58:18.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Augmented-Reality Android Application</h3><p>This article offers tutorials on how to build an Android AR application using Google’s Sceneform SDK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FwkKxZ5JTnl7VYHAPp-VA.png" /></figure><blockquote>Note: Google SceneForm is now deprecated, we will be using its continuation SceneView (<a href="https://github.com/SceneView/sceneform-android">https://github.com/SceneView/sceneform-android</a>)</blockquote><p>Here’s some previews of what we are going to build,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*o4EIzjoKWg9jZqdUQJrCQQ.png" /><figcaption>Preview</figcaption></figure><p>Sceneform is a 3D framework that makes it easy for you to build ARCore apps without OpenGL. It makes it straightforward to render realistic 3D scenes in AR and non-AR apps, without having to learn OpenGL.</p><p>In this article we will focus on developing a Android application using Java &amp; Kotlin which renders a 3D t-shirt.</p><blockquote>Here’s the github repository for source code, <br><a href="https://github.com/mssandeepkamath/ar-sceneview-example.">https://github.com/mssandeepkamath/ar-sceneview-example.</a></blockquote><p>First, we need to add the sceneform dependency in gradle.build module level.</p><p><em>gradle.build (Module:app)</em></p><pre>implementation &quot;com.gorisse.thomas.sceneform:sceneform:1.21.0&quot;</pre><p>Allow your application to ask for camera access and also add meta-data so that your application can detect the need of ar-core.</p><p><em>AndroidManifest.xml</em></p><pre>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;<br><br>&lt;application&gt;<br>   ...<br>   &lt;meta-data<br>        android:name=&quot;com.google.ar.core&quot;<br>        android:value=&quot;optional&quot; /&gt;<br>&lt;/application&gt;</pre><p>Create a empty activity named ARActivity, and add the following fragment to activity_ar.xml file</p><p><em>activity_ar.xml</em></p><pre>&lt;androidx.fragment.app.FragmentContainerView<br>        android:id=&quot;@+id/arFragment&quot;<br>        android:name=&quot;com.google.ar.sceneform.ux.ArFragment&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot; /&gt;</pre><p>Its important to check whether the android device is compatible for AR, so create a function inside ARActivity.java</p><pre>public static boolean checkSystemSupport(Activity activity) {<br>      // checking whether the API version of the running Android &gt;= 24<br>      // that means Android Nougat 7.0<br>      if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.N) {<br>          String openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion();<br>          // checking whether the OpenGL version &gt;= 3.0<br>          if (Double.parseDouble(openGlVersion) &gt;= 3.0) {<br>              return true;<br>          } else {<br>              Toast.makeText(activity, &quot;App needs OpenGl Version 3.0 or later&quot;, Toast.LENGTH_SHORT).show();<br>              activity.finish();<br>              return false;<br>          }<br>      } else {<br>          Toast.makeText(activity, &quot;App does not support required Build Version&quot;, Toast.LENGTH_SHORT).show();<br>          activity.finish();<br>          return false;<br>      }<br>  }</pre><p>If your device passes the compatibility check, you need to start with the 3D model rendering process, thus add the following code inside the onCreate function of ARActivity.java</p><pre>if (checkSystemSupport(this)) {<br>          //Connecting to the UI<br>          // ArFragment is linked up with its respective id used in the activity_main.xml<br>          arCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arFragment);<br><br>          assert arCam != null;<br>          arCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -&gt; {<br>              clickNo++;<br>              //rendering the model when click is 1<br>              if (clickNo == 1) {<br>                  //fixing the coordinates in the detected plane<br>                  Anchor anchor = hitResult.createAnchor();<br>                  ModelRenderable.builder()<br>                          .setSource(this,R.raw.tshirt) // set glb model<br>                          .setIsFilamentGltf(true)<br>                          .build()<br>                          .thenAccept(modelRenderable -&gt; addModel(anchor, modelRenderable))<br>                          .exceptionally(throwable -&gt; {<br>                              AlertDialog.Builder builder = new AlertDialog.Builder(this);<br>                              builder.setMessage(&quot;Something is not right&quot; + throwable.getMessage()).show();<br>                              return null;<br>                          });<br>              }<br>          });<br>      }</pre><blockquote>Note: The 3D model should be in .glb format and I have placed it in res/drawable/raw folder.</blockquote><p>Create a function to render a 3D model and add it into ARActivity.java,</p><pre>private void addModel(Anchor anchor, ModelRenderable modelRenderable) {<br>          // Creating a AnchorNode with a specific anchor<br>          AnchorNode anchorNode = new AnchorNode(anchor);<br><br>          // attaching the anchorNode with the ArFragment<br>          anchorNode.setParent(arCam.getArSceneView().getScene());<br><br>          // attaching the anchorNode with the TransformableNode<br>          TransformableNode model = new TransformableNode(arCam.getTransformationSystem());<br>          model.setParent(anchorNode);<br>          // attaching the 3d model with the TransformableNode<br>          // that is already attached with the node<br>          model.setRenderable(modelRenderable);<br>          model.select();<br>      }</pre><p>That’s pretty much all. For complete implementation have a look at,</p><p><a href="https://github.com/mssandeepkamath/ar-sceneview-example">GitHub - mssandeepkamath/ar-sceneview-example</a></p><p>Here’s some more example projects,</p><ul><li><a href="https://github.com/mssandeepkamath/AR-Ecommerce-Application-">GitHub - mssandeepkamath/AR-Ecommerce-Application-: Ecommerce with Augmented reality</a></li><li><a href="https://github.com/mssandeepkamath/HeapSort-Visualizer">GitHub - mssandeepkamath/HeapSort-Visualizer: AR Android application for heap sort visualization.</a></li></ul><p>The article’s main goal was to show how straightforward it is to develop an augmented reality application using Google’s sceneform SDK. I sincerely apologise if the article had any inaccuracies. If you found it helpful, kindly give it an upvote.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🧠 AI Tools ⇒ <a href="https://www.aimind.so/">View Now</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d14619559d1" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-augmented-reality-android-application-4d14619559d1">Building Augmented-Reality Android application</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Goroutines]]></title>
            <link>https://levelup.gitconnected.com/understanding-goroutines-6b1c4bc463df?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b1c4bc463df</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 16:39:06 GMT</pubDate>
            <atom:updated>2023-07-18T18:58:35.132Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, lets try to understand goroutines and also implement the same.</p><h3>Theory:</h3><p>Before understanding Goroutines, Its must to understand Threads.</p><h4>Threads:</h4><p>In simple words, Threads are<strong> light weight process</strong>. Within a program, a thread is a separate execution path.</p><blockquote><strong>Note: System Threads are managed by Operating System.</strong></blockquote><p>Although its called light-weight process, every single thread consumes ~<strong>1MB</strong> of memory. Thus if your application creates 1000 threads then it would consume ~<strong>1GB</strong>, which is huge. Some people call threads lightweight processes because they have their own stack but can access shared data.<br>Learn more about Threads from <a href="https://www.geeksforgeeks.org/thread-in-operating-system/">here</a>.</p><h4>Goroutines:</h4><p>In simple words, We can call Goroutines as <strong>light weight threads</strong>. Anyways right way to define it is,</p><blockquote>“A Goroutine is a function or method which executes independently and simultaneously in connection with any other Goroutines present in your program.</blockquote><blockquote><strong>Note: Goroutines are managed by Go Runtime.</strong></blockquote><p>Every single goroutine consume ~<strong>2KB</strong>, which is significantly negligible compared to that of thread stack size.</p><p>Lets understand Goroutines with a diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*35m_cq7MJq70V1zq4xN5pg.gif" /><figcaption>Self made image (single core)</figcaption></figure><p>A CPU can have multiple cores, lets focus on one of them for simplicity.<br>These CPU cores are assigned to the threads/process for their execution. Since Goroutines are functions which are executed in a thread, we say “Goroutines are multiplexed onto multiple OS threads” i.e. A single thread can have multiple Goroutines which are classified into <em>Running Goroutines</em> and <em>Runnable Goroutines</em>.</p><p>A <em>Running Goroutine </em>are the ones which are currently running/executing in the thread. Whereas <em>Runnable Goroutines</em> are the ones waiting in the local queue to get executed in a thread.</p><p>If a<em> running Goroutine</em> blocks a thread by waiting for I/O, a new thread is created and is assigned with a <em>CPU core</em> +<em> Runnable Goroutine</em> that was waiting in the local queue, thus continuing execution. When I/O is done, the Goroutine waits in the local queue for its round.</p><p>Lets consider a quad-core CPU:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzojTHwqtWDR1CEmTZJKnw.gif" /><figcaption>Self made image (quad core)</figcaption></figure><p>Its clear from the above image that the local queue of 1st core is empty. Thus Half of the Goroutines from other local queue are migrated/moved to the empty local queue. If every local queue are empty, then Goroutines from global queue (ones waiting to move to local queue) are picked.</p><h3>Implementation:</h3><p>Creating a Goroutine is way easier than creating <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#:~:text=A%20thread%20is%20a%20thread,to%20threads%20with%20lower%20priority.\">Thread</a> in Java / <a href="https://developer.android.com/kotlin/coroutines#:~:text=A%20coroutine%20is%20a%20concurrency,established%20concepts%20from%20other%20languages.">Coroutine</a> in Kotlin. Just use the keyword <strong>“go”</strong> as prefix to the function or method.</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;time&quot;<br>)<br><br>func main() {<br>  go greeterOne() //Goroutine<br>  greeterTwo()    //Function<br>}<br><br>func greeterOne() {<br> for i := 0; i &lt; 5; i++ {<br>  fmt.Println(&quot;Hello&quot;)<br> }<br>}<br><br>func greeterTwo() {<br> for i := 0; i &lt; 5; i++ {<br>  time.Sleep(5 * time.Microsecond) // Slowing it down so that main won&#39;t terminate before goroutines execute and return.<br>  fmt.Println(&quot;World&quot;)<br> }<br>}</pre><pre>//Output:<br>Hello                  <br>Hello<br>Hello<br>Hello<br>Hello<br>World<br>World<br>World<br>World<br>World</pre><p>Here, since we will have to wait for goroutine to return, we slow down the execution of <em>greeterTwo()</em> using <em>time.Sleep(). </em>Using Sleep is a standard approach is Java and other programming language, but Golang comes with a more cleaner and efficient approach i.e.<em> </em><strong><em>Wait Groups</em></strong></p><p>Lets consider a example, where we will perform 5 Get requests to different domains using <em>Goroutine</em> and <em>Wait Groups</em>.</p><blockquote>The idea of <em>Wait Group</em><strong> </strong>is simple, Imagine <em>Wait Group</em> to a person who keeps track of Goroutine count. Before creating Goroutine you ask him to increment the count, and after goroutines finishes the execution you ask him to decrement count. <em>Wait Group </em>makes sure that main Goroutine doesn’t terminate until count turns 0 i.e. all the Goroutines are executed.</blockquote><pre>package main<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;sync&quot;<br>)<br><br>var wg = &amp;sync.WaitGroup{} //pointer to wait group<br><br><br>func main() {<br><br> urls := []string{&quot;https://google.com&quot;, &quot;https://medium.com&quot;, &quot;https://go.dev&quot;, &quot;https://facebook.com&quot;, &quot;https://studybear.tech&quot;} //domains<br><br> for _, url := range urls {<br>  wg.Add(1) // incrementing count of goroutines (similar to goroutine_count++)<br>  go GetRequest(url) // creating goroutines<br> }<br><br> wg.Wait() //waits until goroutines count becomes 0<br>}<br><br><br>func GetRequest(url string) {<br><br> response, err := http.Get(url) // get request<br><br> if err != nil {<br>  panic(err) // error handing<br> }<br><br> fmt.Printf(&quot;Status code for %s is %s\n&quot;, url, response.Status) //print status<br><br> wg.Done() // decrementing count of goroutines (similar to goroutine_count--)<br>}</pre><pre>//Output:<br>Status code for https://studybear.tech is 200 OK<br>Status code for https://medium.com is 200 OK<br>Status code for https://google.com is 200 OK<br>Status code for https://go.dev is 200 OK<br>Status code for https://facebook.com is 200 OK</pre><p>The order of execution of Goroutines cannot be predicted similar to thread execution and performance of goroutines are much more faster than threads.</p><p>That’s all from my side, My sincere apologies for any errors in the article, and I hope that was helpful, Thank you.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🧠 AI Tools ⇒ <a href="https://www.aimind.so/">View Now</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b1c4bc463df" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-goroutines-6b1c4bc463df">Understanding Goroutines</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spring Boot Architecture]]></title>
            <link>https://levelup.gitconnected.com/understanding-spring-boot-architecture-6083e2631bc6?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/6083e2631bc6</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 13:26:04 GMT</pubDate>
            <atom:updated>2023-07-18T18:58:57.375Z</atom:updated>
            <content:encoded><![CDATA[<p>The content in the article aids in understanding Java Spring Boot Framework’s layers.</p><blockquote><strong>Instead of heading for a big breakdown, I decided to have a small breakdown every Tuesday evening.”</strong> <strong>― Graham Parke</strong></blockquote><p>The best way to examine any software is to separate it into layers, then merge those layers back together, So Lets follow the same here.</p><p>Before diving into Java Spring Boot, let’s have a look at a well-known example the <a href="https://www.cloudflare.com/learning/ddos/glossary/open-systems-interconnection-model-osi/"><strong>OSI model</strong></a> in computer network.<strong> </strong>Although networking as a whole appears to be complex, we often divide it into layers in order to organize the protocols. We also state that each layer relies on the services offered by the layer below it. In Spring boot, the same principle applies.</p><h4>Spring Boot Layers:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g0htFSEnplHtdXYcZG3qZQ.gif" /><figcaption>Self made image</figcaption></figure><p>We can mainly divide Spring boot into 4 layers,</p><ol><li><strong>Controller Layer</strong></li></ol><p>The first part of the system that engages with the client request is a Controllers. They define the endpoints of the API, one can imagine end-points as valid routes and request method(GET,POST,PUT). Controller’s main goal is to offer services to the client i.e. providing the response, status and more. Controller makes use of the services provided by Service layer in order to serve the client.</p><blockquote>Example of Endpoints:</blockquote><blockquote>/login (POST)<br>/register (POST)<br>/products (GET)</blockquote><p><strong>2. Service layer</strong></p><p>Service layers are meant to implement business logics. The main aim of service layer is to offer services to controller layer. All sort of computations on the data are performed in this layer, thus service layer requires data. Therefore they rely on the services offered by the DAO/Repository layer.</p><p><strong>3. Repository/DAO layer</strong></p><p>DAO stands for Data Access Object, The main goal of this layer is access(Query) data efficiently from database and provide services to the Service layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*5QNtR7_7UpgsRY6pk8-VKg.png" /><figcaption>Source: GeeksForGeeks</figcaption></figure><p>There exists interfaces in spring boot which provides us CRUD operations (CREATE, RETRIEVE, UPDATE, DELETE). Thus Repository layer can implement one of these. Its worth to have a look at different functionality provided by there repositories from <a href="https://www.geeksforgeeks.org/spring-boot-difference-between-crudrepository-and-jparepository/">here</a>.</p><h4>4. Model:</h4><p>Model represents real world objects. Thus these objects are referred to as Models. JPA (Java Persistence API) provides reference or details about ORM( Object Relation Mapping) which means the Java class can we related to the database table. There exists many implementation of JPA ORM, one of them is <a href="https://hibernate.org/">Hibernate</a>. Therefore you will require the Java class of real world entities and then map it to the relation(Table).</p><h3>Template for implementation of the above Layers:</h3><blockquote>Note: For the implementations, lets consider Project Management as a topic.</blockquote><h4>Controller Layer:</h4><p><em>ProjectController.Java</em></p><pre>package com.example.Controller;<br>//import statements goes here<br>@RestController<br>public class UserController {<br>   <br>    //List all the available projects<br>    @GetMapping(path = &quot;/projects&quot;, produces = MediaType.APPLICATION_JSON_VALUE)<br>    public ResponseEntity&lt;List&lt;Project&gt;&gt; getProjects() {<br>     <br>    // perform validation checks<br>    // return the services provided by service layer<br>    }<br>    //Apply for the project<br>    @PostMapping(path = &quot;/apply-project&quot;, consumes = MediaType.APPLICATION_JSON_VALUE)<br>    public ResponseEntity&lt;HttpStatus&gt; applyProject(@RequestBody Map&lt;String,String&gt; json) {<br>    // perform validation checks<br>    // return the services provided by service layer<br>    }<br>    <br>    //Upload resume<br>    @PostMapping(path = &quot;/upload-resume/{usn}&quot;)<br>    public ResponseEntity&lt;List&lt;Object&gt;&gt; uploadToDB(@RequestParam(&quot;file&quot;) MultipartFile[] file,@PathVariable String usn) {<br>    <br>    // perform validation checks<br>    // return the services provided by service layer<br>    }<br>    //Download resume<br>    @GetMapping(&quot;/files/download/{fileName:.+}&quot;)<br>    public ResponseEntity downloadFromDB(@PathVariable String fileName) {<br>    // perform validation checks<br>    // return the services provided by service layer<br>    }<br>}</pre><p>The above example makes use of @ annotations, These are used to inform spring whether it is a RestController, PostMapping etc.</p><h4>Service Layer:</h4><p><em>ProjectService.Java</em></p><pre>package com.example.Service;<br><br>// import statements<br><br>public interface ProjectService {<br><br>    ResponseEntity&lt;List&lt;Project&gt;&gt; getProjects();<br><br>    HttpStatus applyProject(String USN,int project_id);<br><br>    ResponseEntity&lt;List&lt;Object&gt;&gt; uploadProjectDocument(MultipartFile[] files,int project_id);<br><br>}</pre><p><em>ProjectServiceImpl.Java</em></p><pre>package com.example.Service;<br><br>//import statements<br>@Service<br>public class ProjectServiceImpl implements ProjectService {<br>//dependency injection of DAO to be gone here (Autowire)<br>  <br>    @Override<br>    public ResponseEntity&lt;List&lt;Project&gt;&gt; getProjects() {<br>        try {<br>           //Business logic implementation using DAO services<br>        } catch (Exception e) {<br>            return new ResponseEntity&lt;&gt;(null,HttpStatus.INTERNAL_SERVER_ERROR) ;<br>        }<br>    }<br>   <br>    @Override<br>    public HttpStatus applyProject(String USN, int project_id) {<br>   <br>    //Business logic implementation using DAO services<br>    }<br>  <br>   //helper functions<br>    public ResponseEntity uploadToLocalFileSystem(MultipartFile file,int project_id) {<br>     <br>    }<br>    @Override<br>    public ResponseEntity&lt;List&lt;Object&gt;&gt; uploadProjectDocument(MultipartFile[] files,int project_id) {<br>       //Business logic implementation using DAO services<br>    }<br><br>}</pre><h4>Repository/DAO Layer:</h4><p><em>ProjectDAO.java</em></p><pre>package com.example.Dao;<br><br>//import statements<br><br>public interface ProjectDao extends JpaRepository&lt;Project,Integer&gt; {<br><br>//You can also include native queries on top of CRUD operations provided by JPA<br>// Add queries here using @Query annotations and corresponding functions<br><br>    @Query(value = &quot;Your SQL query &quot;,nativeQuery = true)<br>    public List&lt;Project&gt; getProjects();<br><br>}<br><br>}</pre><h4>Model:</h4><p><em>Project.java</em></p><pre>package com.example.Entity;<br><br>//import statements<br><br>@Entity<br>@Table(name = &quot;project&quot;)<br>public class Project {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private int project_id;<br>    @Column(nullable = false, name = &quot;company_name&quot;)<br>    private String company_name;<br><br>    @Column(nullable = false, name = &quot;description&quot;)<br>    private String description;<br><br>    @Column(nullable = false, name = &quot;requirements&quot;)<br>    private String requirements;<br><br>    @Column(nullable = false, name = &quot;manager&quot;)<br>    private String manager;<br>    @Column(nullable = false, name = &quot;start_date&quot;)<br>    private Date start_date = new Date();<br><br>    @Column( name = &quot;end_date&quot;)<br>    private Date end_date = new Date();<br>    @Column(nullable = false,name = &quot;opening&quot;)<br>    private int opening;<br>    @Column(name = &quot;resources&quot;)<br>    private String resources;<br>    public Set&lt;Staff&gt; getStaff_incharge() {<br>        return staff_incharge;<br>    }<br>    public void setStaff_incharge(Set&lt;Staff&gt; staff_incharge) {<br>        this.staff_incharge = staff_incharge;<br>    }<br>    public Set&lt;Student&gt; getApplied_students() {<br>        return applied_students;<br>    }<br>    public Set&lt;Document&gt; getDocuments() {<br>        return documents;<br>    }<br>    public void setDocuments(Set&lt;Document&gt; documents) {<br>        this.documents = documents;<br>    }<br>    @JsonIgnore<br>    @ManyToMany(mappedBy=&quot;funded_projects&quot;)<br>    private Set&lt;Fund&gt; funds;<br>    public Set&lt;Fund&gt; getFunds() {<br>        return funds;<br>    }<br>    public void setFunds(Set&lt;Fund&gt; funds) {<br>        this.funds = funds;<br>    }<br>    public void setApplied_students(Set&lt;Student&gt; applied_students) {<br>        this.applied_students = applied_students;<br>    }<br>    public Set&lt;Student&gt; getWorking_students() {<br>        return working_students;<br>    }<br>    public void setWorking_students(Set&lt;Student&gt; working_students) {<br>        this.working_students = working_students;<br>    }<br>//constructors<br>    public Project() {<br>        super();<br>    }<br>    public Project(int project_id, String company_name, String description, String requirements, String manager, Date start_date, Date end_date, int opening, String resources) {<br>        super();<br>        this.project_id = project_id;<br>        this.company_name = company_name;<br>        this.description = description;<br>        this.requirements = requirements;<br>        this.manager = manager;<br>        this.start_date = start_date;<br>        this.end_date = end_date;<br>        this.opening = opening;<br>        this.resources = resources;<br>    }<br>    public int getProject_id() {<br>        return project_id;<br>    }<br>    public void setProject_id(int project_id) {<br>        this.project_id = project_id;<br>    }<br>    public String getCompany_name() {<br>        return company_name;<br>    }<br>    public void setCompany_name(String company_name) {<br>        this.company_name = company_name;<br>    }<br><br>    public String getDescription() {<br>        return description;<br>    }<br>    public void setDescription(String description) {<br>        this.description = description;<br>    }<br>    public String getRequirements() {<br>        return requirements;<br>    }<br>    public void setRequirements(String requirements) {<br>        this.requirements = requirements;<br>    }<br>    public String getManager() {<br>        return manager;<br>    }<br>    public void setManager(String manager) {<br>        this.manager = manager;<br>    }<br>    public Date getStart_date() {<br>        return start_date;<br>    }<br>    public void setStart_date(Date start_date) {<br>        this.start_date = start_date;<br>    }<br>    public Date getEnd_date() {<br>        return end_date;<br>    }<br>    public void setEnd_date(Date end_date) {<br>        this.end_date = end_date;<br>    }<br>    public int getOpening() {<br>        return opening;<br>    }<br>    public void setOpening(int opening) {<br>        this.opening = opening;<br>    }<br>    public String getResources() {<br>        return resources;<br>    }<br>    public void setResources(String resources) {<br>        this.resources = resources;<br>    }<br>    @Override<br>    public String toString() {<br>        return &quot;Project{&quot; +<br>                &quot;project_id=&quot; + project_id +<br>                &quot;, company_name=&#39;&quot; + company_name + &#39;\&#39;&#39; +<br>                &quot;, description=&#39;&quot; + description + &#39;\&#39;&#39; +<br>                &quot;, requirements=&#39;&quot; + requirements + &#39;\&#39;&#39; +<br>                &quot;, manager=&#39;&quot; + manager + &#39;\&#39;&#39; +<br>                &quot;, start_date=&quot; + start_date +<br>                &quot;, end_date=&quot; + end_date +<br>                &quot;, opening=&quot; + opening +<br>                &quot;, resources=&#39;&quot; + resources + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>There is a wide use of annotations, have a look at it from <a href="https://www.baeldung.com/jpa-entities">here</a>. In the above example, The class represents a table and its data members represents the attributes of the table. We can also represent the relationship between tables using <em>OnetoOne, ManyToOne, ManyToMany</em> annotations. Learn more about ORM<a href="https://www.tutorialspoint.com/spring_boot_orm/index.htm"> here.</a></p><blockquote>Learn more about implementation from <a href="https://www.baeldung.com/spring-boot">https://www.baeldung.com/spring-boot</a></blockquote><p>The above implementation was incomplete because the aim of the article is to understand the workflow and layers which, has nothing to do with implementation. Spring boot is huge and I have covered only a very small part of it. My sincere apologies for any errors in the article, and I hope that helpful, Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6083e2631bc6" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-spring-boot-architecture-6083e2631bc6">Understanding Spring Boot Architecture</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[News app using Volley and Glide]]></title>
            <link>https://medium.com/@mssandeepkamath/volley-glide-the-match-made-in-heaven-36e1ac6fbb9f?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/36e1ac6fbb9f</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Sat, 21 Jan 2023 17:48:39 GMT</pubDate>
            <atom:updated>2025-08-21T21:13:03.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>News Android app using Volley and Glide</h3><p>This article demonstrates the use of Volley HTTP library with Glide Framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6gSfuVTGjr4xILUcMmgVA.png" /></figure><p>All applications, whether they be Web, Android, or perhaps another platform, use <a href="https://aws.amazon.com/what-is/api/">API</a> calls. Large-scale apps generally cannot be created without using an API. Now in android we mainly focus on doing things asynchronously to prevent blocking of main/UI thread. Lets understand it better with a diagram,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nK8QuvEDPdi0Uh6L7YvKeQ.png" /></figure><p>So say you have build a application which has a button in it, and now you try to do a http request to a remote API using okHttp or other synchronous library. What can happen is your UI thread can get blocked(frozen) if the response takes time, i.e. you wont be able to click the button. Thus any kind of external API, Database requests or high computational task have to be done asynchronously(parallel) using threading or coroutines.</p><p>Implementing multi threading or coroutines can be difficult so the solution for the same is using Asynchronous HTTP library.</p><h3>Volley HTTP:</h3><p>Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.</p><p>Volley offers the following benefits:</p><ul><li>Automatic scheduling of network requests.</li><li>Multiple concurrent network connections.</li><li>Transparent disk and memory response caching with standard HTTP <a href="https://en.wikipedia.org/wiki/Cache_coherence">cache coherence</a>.</li><li>Support for request prioritization.</li><li>Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.</li><li>Ease of customization, for example, for retry and backoff.</li><li>Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.</li><li>Debugging and tracing tools.</li></ul><h3>Glide:</h3><p>Glide is a fast and efficient image loading library for Android focused on smooth scrolling. Glide offers an easy to use API, a performant and extensible resource decoding pipeline and automatic resource pooling.</p><p>Glide takes a number of steps to ensure image loading is both as fast and as smooth as possible on Android:</p><ul><li>Smart and automatic down sampling and caching minimize storage overhead and decode times.</li><li>Aggressive re-use of resources like byte arrays and Bitmaps minimizes expensive garbage collections and heap fragmentation.</li><li>Deep lifecycle integration ensures that only requests for active Fragments and Activities are prioritized and that Applications release resources when necessary to avoid being killed when backgrounded.</li></ul><p>So all this might sound a lot, but lets jump towards the implementation.</p><p>So in simple words the images from API response are provided to Glide to load it into UI efficiently.</p><h3>Volley Implementation:</h3><p>The dependency for the volley HTTP library to be added into <em>gradle.build (</em>module level)</p><pre>dependencies {<br>    implementation &#39;com.android.volley:volley:1.2.1&#39;<br>}</pre><p>In your activity or fragment,</p><pre>  //Get request<br>  private fun volleyApiCall() {<br>      val url = &quot;api_url&quot;<br>      var requestQueue: RequestQueue = Volley.newRequestQueue(this) //this activity context<br>      val request = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener {<br>          response -&gt;<br>          try {<br>            val jsonArray = response.getJSONArray(&quot;name&quot;)<br>            for (i in 0 until jsonArray.length()) {<br>               val object= jsonArray.getJSONObject(i)<br>               val attributeOne= employee.getString(&quot;attributeOne&quot;)<br>               val attributeTwo= employee.getInt(&quot;attributeTwo&quot;)<br>               //..<br>                 }<br>               }<br>            catch (e: JSONException) {<br>                e.printStackTrace()<br>                }<br>      },Response.ErrorListener{ error -&gt; error.printStackTrace()})<br>      //add request to volley queue<br>      requestQueue.add(request)<br>   }</pre><p>Learn more about Volley Http GET, POST requests from <a href="https://google.github.io/volley/">here</a>.</p><h3>Glide Implementation:</h3><p>The dependency for the Glide framework to be added into <em>gradle.build (</em>module level)</p><pre>dependencies {<br>    implementation &#39;com.github.bumptech.glide:glide:4.14.2&#39;<br>    annotationProcessor &#39;com.github.bumptech.glide:compiler:4.14.2&#39;<br>}</pre><p>In your activity or fragment,</p><pre> Glide.with(activity as Context)<br>              .load(url) //url of image or gif<br>              .placeholder(R.drawable.placeholder)//preload placeholder image id<br>              .listener(object : RequestListener&lt;Drawable&gt; {<br>                   //success and error callbacks<br>                   override fun onLoadFailed(e: GlideException?, model: Any?, target: Target&lt;Drawable&gt;?, isFirstResource: Boolean): Boolean {<br>                      return false<br>                   }<br>                   override fun onResourceReady(resource: Drawable?, model: Any?, target: Target&lt;Drawable&gt;?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {<br>                     return false<br>                   }<br>                   })<br>               .diskCacheStrategy(DiskCacheStrategy.ALL) // cache all<br>               .error(placeHolderId) //error placeholder image id<br>               .into(imageViewId) //imageView id</pre><p>Learn more about Glides caching from <a href="https://bumptech.github.io/glide/doc/caching.html">here</a>.</p><p>Here’s a complete integration of Volley and Glide for a News API.</p><p>The Volley GET request returns a array of News object which is then passed to a recycler views adapter to display the news and image associated with it using Glide. In the below implementation I have used Singleton Volley Request Queue to just create one instance of it with the lifecycle same as that of the activity.</p><p>Also I would prefer to use view binding over findViewById, read more about it <a href="https://medium.com/@msandeepcip/why-view-binding-over-findviewbyid-in-android-9cbbaef2c7ef">here</a>.</p><h4>Kotlin Files:</h4><p>News Data Class:</p><pre>package com.sandeep.model<br><br>data class NewsDataClass(val title:String,val description:String,val urlImage:String,val urlPost:String,val date:String)</pre><p>Singleton Volley Request Queue (optional for better practice):</p><pre>package com.sandeep.util<br><br>//import packages<br><br>class MySingleton constructor(context: Context) {<br>    companion object {<br>        @Volatile<br>        private var INSTANCE: MySingleton? = null<br>        fun getInstance(context: Context) =<br>            INSTANCE ?: synchronized(this) {<br>                INSTANCE ?: MySingleton(context).also {<br>                    INSTANCE = it<br>                }<br>            }<br>    }<br>    val imageLoader: ImageLoader by lazy {<br>        ImageLoader(requestQueue,<br>            object : ImageLoader.ImageCache {<br>                private val cache = LruCache&lt;String, Bitmap&gt;(20)<br>                override fun getBitmap(url: String): Bitmap {<br>                    return cache.get(url)<br>                }<br>                override fun putBitmap(url: String, bitmap: Bitmap) {<br>                    cache.put(url, bitmap)<br>                }<br>            })<br>    }<br>    private val requestQueue: RequestQueue by lazy {<br>        // applicationContext is key, it keeps you from leaking the<br>        // Activity or BroadcastReceiver if someone passes one in.<br>        Volley.newRequestQueue(context.applicationContext)<br>    }<br>    fun &lt;T&gt; addToRequestQueue(req: Request&lt;T&gt;) {<br>        requestQueue.add(req)<br>    }<br>}</pre><p>Fragment:</p><pre>package com.sandeep.fragment<br><br>//import packages<br><br>class NewsFragment : Fragment() {<br><br>    lateinit var itemArray: ArrayList&lt;NewsDataClass&gt;<br>    lateinit var recyclerView: RecyclerView<br>    lateinit var layoutManager: RecyclerView.LayoutManager<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?,<br>        savedInstanceState: Bundle?,<br>    ): View? {<br><br>        val view = inflater.inflate(R.layout.fragment_news, container, false)<br>        recyclerView = view.findViewById(R.id.vwRecyclerView)<br>        layoutManager = LinearLayoutManager(activity as MainActivity)<br>        itemArray = ArrayList()<br>        volleyGetRequest()// call the volley function<br>     return view<br><br>    }<br><br>    fun volleyGetRequest()<br>    {<br>        val url =  &quot;https://newsapi.org/v2/everything?q=technology%20and%20IT&amp;language=en&amp;pageSize=100&amp;sortBy=publishedAt&amp;apiKey=your_api_key&quot;<br><br>            val jsonObjectRequest = object : JsonObjectRequest(<br>                Method.GET,<br>                url,<br>                null,<br>                { response -&gt;<br>                    try {<br>                        val obj: JSONObject = response<br>                        if (response.getString(&quot;status&quot;) == &quot;ok&quot;) {<br>                            val Itemarray = obj.getJSONArray(&quot;articles&quot;)<br>                            for (i in 0 until Itemarray.length()) {<br>                                if (Itemarray.getJSONObject(i) != null) {<br>                                    val jsonObject: JSONObject = Itemarray.getJSONObject(i)<br>                                    val title: String = jsonObject.getString(&quot;title&quot;)<br>                                    val description: String = jsonObject.getString(&quot;description&quot;)<br>                                    val urlImage: String = jsonObject.getString(&quot;urlToImage&quot;)<br>                                    val urlPost: String = jsonObject.getString(&quot;url&quot;)<br>                                    val date: String = jsonObject.getString(&quot;publishedAt&quot;)<br>                                    <br>                                    itemArray.add(NewsDataClass(title,<br>                                        description,<br>                                        urlImage,<br>                                        urlPost,<br>                                        date))// News data class<br>                                }<br>                            }<br>                            recyclerView.layoutManager = layoutManager<br>                            recyclerView.adapter = NewsAdapter(activity as MainActivity, itemArray)<br>                        } else { <br>                            ToastMessage(&quot;Some unexpected error occurred.&quot;)<br>                        }<br>                    } catch (e: JSONException) {<br>                      e.printStackTrace()<br>                    }<br>                },<br>                { error -&gt;                   <br>                    ToastMessage(&quot;Something went wrong..&quot;)               <br>                }<br>            ) {<br>                //passing header if required<br>                override fun getHeaders(): MutableMap&lt;String, String&gt; {<br>                    val headers = HashMap&lt;String, String&gt;()<br>                    headers[&quot;User-Agent&quot;] = &quot;Mozilla/5.0&quot;<br>                    return headers<br>                }<br>            }<br><br>            // add network request to volley queue<br>            MySingleton.getInstance((activity as MainActivity).applicationContext)<br>                .addToRequestQueue(jsonObjectRequest)<br>        } <br>    }<br><br>    fun ToastMessage(message: String) {<br>        Toast.makeText(activity as MainActivity, message, Toast.LENGTH_SHORT).show()<br>    }<br><br>}</pre><p>Recycler Adapter:</p><pre>package com.sandeep.adapter<br><br>//import packages<br><br><br>class NewsAdapter(val context: Context, val itemArrayList: ArrayList&lt;NewsDataClass&gt;) :<br>    RecyclerView.Adapter&lt;NewsAdapter.ViewHolderNews&gt;() {<br> <br>    class ViewHolderNews(view: View) : RecyclerView.ViewHolder(view) {<br>        //Item layout views<br>        val title = view.findViewById&lt;TextView&gt;(R.id.txtNewsTitle)<br>        val description = view.findViewById&lt;TextView&gt;(R.id.txtNewsDescription)<br>        val image = view.findViewById&lt;ImageView&gt;(R.id.imgNewsPhoto)<br>        val date = view.findViewById&lt;TextView&gt;(R.id.txtNewsDate)<br>        val link = view.findViewById&lt;TextView&gt;(R.id.txtNewsLink)<br>    }<br><br>    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolderNews {<br>        val view = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false)<br>        return ViewHolderNews(view)<br>    }<br><br>    override fun onBindViewHolder(holder: ViewHolderNews,position:Int) {<br>        holder.title.text = itemArrayList[position].title<br>        holder.description.text = itemArrayList[position].description<br>        //Glide to load the image<br>        Glide.with(context).load(itemArrayList[position].urlImage)<br>            .placeholder(R.drawable.placeholder).diskCacheStrategy(DiskCacheStrategy.ALL)<br>            .error(R.drawable.no_placeholder_new).into(holder.image)<br>        holder.date.text = itemArrayList[position].date.substring(0, 10)<br>        //Redired to news article onClick<br>        holder.link.setOnClickListener {<br>            val browserIntent = Intent(Intent.ACTION_VIEW)<br>            browserIntent.data = Uri.parse(itemArrayList[position].urlPost)<br>            context.startActivity(browserIntent)<br>        }<br>    }<br><br>    override fun getItemCount(): Int {<br>        return itemArrayList.size<br>    }<br>}</pre><h4>XML Files:</h4><p>News Item:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:background=&quot;@color/white&quot;&gt;<br><br>    &lt;androidx.cardview.widget.CardView<br>        android:id=&quot;@+id/cardNotes&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;@dimen/_10sdp&quot;<br>        android:layout_marginBottom=&quot;@dimen/_10sdp&quot;<br>        android:layout_marginRight=&quot;@dimen/_15sdp&quot;<br>        android:layout_marginLeft=&quot;@dimen/_15sdp&quot;<br>        app:cardBackgroundColor=&quot;@color/white&quot;<br>        app:cardCornerRadius=&quot;@dimen/_20sdp&quot;<br>        app:cardElevation=&quot;@dimen/_2sdp&quot;<br>       &gt;<br><br>        &lt;LinearLayout<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:orientation=&quot;vertical&quot;<br>            &gt;<br><br>            &lt;LinearLayout<br>                android:layout_width=&quot;match_parent&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:orientation=&quot;vertical&quot;&gt;<br><br>                &lt;ImageView<br>                    android:id=&quot;@+id/imgNewsPhoto&quot;<br>                    android:layout_width=&quot;match_parent&quot;<br>                    android:layout_height=&quot;@dimen/_175sdp&quot;<br>                    android:layout_gravity=&quot;center&quot;<br>                    android:scaleType=&quot;centerCrop&quot; /&gt;<br><br>            &lt;/LinearLayout&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/txtNewsTitle&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:fontFamily=&quot;@font/roboto&quot;<br>                android:padding=&quot;@dimen/_4sdp&quot;<br>                android:textColor=&quot;@color/black&quot;<br>                android:layout_marginStart=&quot;@dimen/_2sdp&quot;<br>                android:layout_marginBottom=&quot;@dimen/_1sdp&quot;<br>                android:layout_marginEnd=&quot;@dimen/_2sdp&quot;<br>                android:layout_marginTop=&quot;@dimen/_3sdp&quot;<br>                android:textSize=&quot;@dimen/_16sdp&quot;<br>                android:letterSpacing=&quot;0.01&quot;<br>                android:textStyle=&quot;bold&quot; /&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/txtNewsDescription&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:layout_marginStart=&quot;@dimen/_2sdp&quot;<br>                android:layout_marginBottom=&quot;@dimen/_2sdp&quot;<br>                android:layout_marginEnd=&quot;@dimen/_2sdp&quot;<br>                android:fontFamily=&quot;@font/roboto&quot;<br>                android:padding=&quot;@dimen/_4sdp&quot;<br>                android:textColor=&quot;#636363&quot;<br>                android:textSize=&quot;@dimen/_14sdp&quot;<br>                android:letterSpacing=&quot;0.01&quot;<br>                android:textStyle=&quot;normal&quot;<br>                /&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/txtNewsLink&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:layout_marginTop=&quot;@dimen/_10sdp&quot;<br>                android:layout_marginBottom=&quot;@dimen/_10sdp&quot;<br>                android:background=&quot;@drawable/card_border&quot;<br>                android:fontFamily=&quot;@font/roboto&quot;<br>                 android:paddingStart=&quot;@dimen/_10sdp&quot;<br>                android:paddingEnd=&quot;@dimen/_10sdp&quot;<br>                android:paddingTop=&quot;@dimen/_5sdp&quot;<br>                android:paddingBottom=&quot;@dimen/_5sdp&quot;<br>                android:text=&quot;@string/read_more&quot;<br>                android:textAlignment=&quot;center&quot;<br>                android:textColor=&quot;@color/black&quot;<br>                android:foreground=&quot;?attr/selectableItemBackground&quot;<br>                android:clickable=&quot;true&quot;<br>                android:focusable=&quot;true&quot;<br>                android:textSize=&quot;@dimen/_13sdp&quot;<br>                android:textStyle=&quot;bold&quot; /&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/txtNewsDate&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_gravity=&quot;center&quot;<br>                android:layout_marginBottom=&quot;@dimen/_5sdp&quot;<br>                android:fontFamily=&quot;@font/roboto&quot;<br>                android:padding=&quot;@dimen/_2sdp&quot;<br>                android:textAlignment=&quot;center&quot;<br>                android:textColor=&quot;@color/text_grey_new&quot;<br>                android:textSize=&quot;@dimen/_10sdp&quot;<br>                android:textStyle=&quot;bold&quot;<br>                android:clickable=&quot;true&quot;<br>                android:focusable=&quot;true&quot;<br>                android:foreground=&quot;?attr/selectableItemBackground&quot;<br>                /&gt;<br><br>        &lt;/LinearLayout&gt;<br><br>    &lt;/androidx.cardview.widget.CardView&gt;<br><br><br>&lt;/LinearLayout&gt;</pre><blockquote>Note: I have used a external sdp(scalable density pixels) library in the above xml.</blockquote><p>Fragment XML:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    android:orientation=&quot;vertical&quot;<br>    tools:context=&quot;.activity.fragment.NewsFragment&quot;&gt;<br>   <br>        &lt;androidx.recyclerview.widget.RecyclerView<br>            android:id=&quot;@+id/vwRecyclerView&quot;<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;match_parent&quot;<br>            android:background=&quot;@color/white&quot;<br><br>            /&gt;<br><br>&lt;/RelativeLayout&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7zcCbo2NpAFBpcn-SBmuA.png" /><figcaption>Ouput of the above implementation</figcaption></figure><p>That’s all from my side. My sincere apologies for any errors in the article, and I hope that gave some insights on Volley and Glide. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36e1ac6fbb9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop using findViewById() in Android!]]></title>
            <link>https://medium.com/@mssandeepkamath/why-view-binding-over-findviewbyid-in-android-9cbbaef2c7ef?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cbbaef2c7ef</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[view-binding]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 19:00:46 GMT</pubDate>
            <atom:updated>2023-05-10T06:16:32.176Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explains why viewBinding should be used instead of our preferred findViewById function.</p><p>In every application development be it web, android, desktop applications, we always have to connect the UI to our backend(Logic) code. In android the traditional way to do it is findViewById(viewId). This is similar to Document.getElementById(id) in js. The UI for android is built using XML which has a tree structure(Document Object Model). Therefore each findViewById is a dept first search on that XML tree(<a href="https://stackoverflow.com/questions/28635992/how-does-findviewbyid-works-on-a-multi-hierarchy-tree-with-many-ids-from-a-custo">source</a>) thus making it in-efficient when there is lot of nesting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*QnJuw5KyKqzj80MjVVp65Q.png" /><figcaption>Android logo</figcaption></figure><p>Lets consider a layout(UI) named <em>activity_main.xml</em></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br><br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.MainActivity&quot;&gt;<br><br><br>    &lt;Button<br>        android:id=&quot;@+id/button&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginEnd=&quot;16dp&quot;<br>        android:layout_marginBottom=&quot;16dp&quot;<br>        android:text=&quot;Button&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/title&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:textAppearance=&quot;@style/TextAppearance.AppCompat.Display4&quot;<br>        android:textStyle=&quot;&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>        tools:text=&quot;Awesome Title&quot; /&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/subtext&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:layout_marginTop=&quot;63dp&quot;<br>        android:text=&quot;TextView&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintHorizontal_bias=&quot;1.0&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/title&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>And lets consider the Activity named MainActivity.kt</p><pre>package com.example.activity<br><br>import android.app.Activity<br>import com.example.R<br><br>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var button: Button //declare a button object<br>    private lateinit var title: TextView<br>    private lateinit var subtext: TextView<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br><br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main)<br>        button= findViewById(R.id.button) // find for the button by its id<br>        title=findViewById(R.id.title)<br>        subtext=findViewById(R.id.subtext)<br>        button.setOnClickListener{it -&gt;<br><br>          //..<br><br>        }<br><br>        //..<br><br>    }<br><br>}</pre><p>The more efficient way to do this is View Binding(Part of <a href="https://developer.android.com/jetpack">Android Jetpack</a>).</p><h4>What is View Binding?</h4><p><em>View binding</em> is a feature that allows you to more easily write code that interacts with views. Once view binding is enabled in a module, it generates a <em>binding class</em> for each XML layout file present in that module. An instance of a binding class contains direct references to all views that have an ID in the corresponding layout.</p><p>In simple words its a Java class of the XML layout. In the above example the name of the layout was <em>activity_main.xml, </em>Therefore the corresponding binding class for that XML layout will be <em>ActivityMainBinding.java.</em></p><p>First we will have to enable the view binding in <em>build.gradle </em>(module level).</p><pre>android {<br>    //..<br>    buildFeatures {<br>        viewBinding = true<br>    }<br>}</pre><p>Once enabled for a project, view binding will generate a binding class for <em>all</em> of your layouts automatically and the same can be used in Activity, Fragment and Recycler view. So lets have look at its usage,</p><h4>View Binding in Activity:</h4><pre>package com.example.activity<br><br>import android.app.Activity<br>import com.example.R<br>import com.example.databinding.ActivityMainBinding<br><br><br>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var bindingMainActivity: ActivityMainBinding // Declare a object of binding class<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        bindingMainActivity = ActivityMainBinding.inflate(layoutInflater) //Initialize by inflating the layout<br>        setContentView(bindingMainActivity.root) // getRoot() or root returns root view<br>        bindingMainActivity.button.setOnClickListener{it-&gt;<br><br>         //..<br><br>        }<br><br>        //..<br> <br>    }<br><br>}</pre><h4>View Binding in Fragment:</h4><pre>package com.example.fragment<br><br>import android.app.Activity<br>import com.example.tripfactory_concierge_android.R<br>import com.example.tripfactory_concierge_android.databinding.FragmentHomeBinding<br><br><br>class HomeFragment : Fragment(),OnClickListener {<br><br>    private lateinit var bindingHomeFragment: FragmentHomeBinding // Declare a object of binding class<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?,<br>        savedInstanceState: Bundle?,<br>    ): View {<br>       <br>        bindingHomeFragment = FragmentHomeBinding.inflate(inflater, container, false) // attach to root is your choice(true/false)<br>        bindingHomeFragment.button.setOnClickListener{it-&gt;<br><br>         //..<br><br>        }<br>        //..<br>        return bindingHomeFragment.root //return the root view<br>    }<br><br>}</pre><p>There’s even a better and safer implementation for fragment, have a look at it <a href="https://developer.android.com/topic/libraries/view-binding">here</a>.</p><p>Quick guide:</p><ul><li><em>inflate( inflater )</em> – Use this in an <em>Activity’s onCreate </em>where there is no parent view to pass to the binding object.</li><li><em>inflate( inflater, parent, attachToParent )</em> – Use this in a <em>Fragment </em>or a Recycler View where you need to pass the <em>viewGroup </em>to the binding object.</li></ul><h4>Internal implementation of binding class:</h4><pre>public final class ActivityMainBinding implements ViewBinding {<br>  @NonNull<br>  private final ConstraintLayout rootView;<br>  @NonNull<br>  public final Button button;<br>  @NonNull<br>  public final TextView subtext;<br>  @NonNull<br>  public final TextView title;<br>  <br>  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button button,<br>      @NonNull TextView subtext, @NonNull TextView title) {<br><br>  //..<br><br>  }<br>  <br>  @NonNull<br>  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {<br>    View root = inflater.inflate(R.layout.activity_main, null, false);<br>    return bind(root);<br>  }</pre><p>View binding has important advantages over using<em> findViewById</em>:</p><ul><li><strong>Null safety:</strong> Since view binding creates direct references to views, there’s no risk of a null pointer exception due to an invalid view ID, But in case of <em>findViewById </em>we could pass a Invalid ID.</li><li><strong>Type safety:</strong> The fields in each binding class have types matching the views they reference in the XML file. This means that there’s no risk of a class cast exception. example: Declaring <em>button</em> object but initializing it <em>findViewById(id of textView)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tj4o0awZvBBjdKGt.png" /><figcaption>View binding VS ButterKnife VS Kotlin synthetics(Source: <a href="https://stackoverflow.com/questions/58351239/viewbinding-vs-kotlin-android-extensions-with-synthetic-views">Stack Overflow</a>).</figcaption></figure><h4>Bonus:</h4><p>You can access the binding object of the <em>active activity</em> in the<em> fragment. </em>This can be helpful when you have bottom navigation or navigation drawer in the activity and there is a need to access it in your fragment.</p><p>Example:</p><pre>package com.example.fragment<br><br>import android.app.Activity<br>import android.view.LayoutInflater<br>import android.view.View<br>import android.view.View.OnClickListener<br>import android.view.ViewGroup<br>import androidx.core.view.GravityCompat<br>import androidx.fragment.app.Fragment<br>import com.example.tripfactory_concierge_android.R<br>import com.example.activity.MainActivity<br>import com.example.FragmentHomeBinding<br><br><br>class HomeFragment : Fragment(),OnClickListener {<br><br><br>    private lateinit var bindingHomeFragment: FragmentHomeBinding<br>    private lateinit var bindingMainActivity: ActivityMainBinding<br><br>    override fun onCreateView(<br>        inflater: LayoutInflater, container: ViewGroup?,<br>        savedInstanceState: Bundle?,<br>    ): View {<br>        //viewBinding fragment_home<br>        bindingHomeFragment = FragmentHomeBinding.inflate(inflater, container, false)<br>        //viewBinding activity_main<br>        bindingMainActivity=(activity as MainActivity).bindingMainActivity<br>        //Close drawer on navigationDrawerHeader click<br>        bindingMainActivity.vwNavigation.getHeaderView(0).setOnClickListener {<br>            bindingMainActivity.lytDrawer.closeDrawers()<br>        }<br>        //on click declarations<br>        bindingHomeFragment.ivHamburger.setOnClickListener(this)<br>        bindingHomeFragment.lytResturants.setOnClickListener(this)<br>        bindingHomeFragment.lytPlaces.setOnClickListener(this)<br>        bindingHomeFragment.lytRestRooms.setOnClickListener(this)<br>        return bindingHomeFragment.root<br>    }<br><br>    override fun onClick(v: View?) {<br>       when(v?.id)<br>       {<br>           //Open drawer on hamburgerIcon click<br>           R.id.ivHamburger-&gt;  bindingMainActivity.lytDrawer.openDrawer(GravityCompat.START)<br>           R.id.lytResturants-&gt;{<br>               intentProvider(RestaurantActivity())<br>           }<br>           R.id.lytPlaces-&gt;{<br>               intentProvider(PlaceActivity())<br>           }<br>           R.id.lytRestRooms-&gt;{<br>               intentProvider(RestRoomActivity())<br>           }<br>       }<br>    }<br>    private fun intentProvider(activityName:Activity)<br>    {<br>        //Intent to respective activities<br>        val intent= Intent(activity as MainActivity,activityName::class.java)<br>        (activity as MainActivity).startActivity(intent)<br>    }<br><br>}</pre><p>If interested to know more about view binding read it from <a href="https://developer.android.com/topic/libraries/view-binding">here</a>. My sincere apologies for any errors in the article, and I hope that reading it will inspire someone to move from Kotlin synthesis to View binding. Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cbbaef2c7ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Kotlin over Java]]></title>
            <link>https://levelup.gitconnected.com/why-kotlin-over-java-336c50fef9ed?source=rss-a514c7d38193------2</link>
            <guid isPermaLink="false">https://medium.com/p/336c50fef9ed</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kotlin-vs-java]]></category>
            <dc:creator><![CDATA[Sandeep Kamath]]></dc:creator>
            <pubDate>Mon, 02 Jan 2023 20:41:47 GMT</pubDate>
            <atom:updated>2023-07-18T18:58:45.417Z</atom:updated>
            <content:encoded><![CDATA[<p>The article delivers some notable features of Kotlin over Java.</p><p>Before jumping into the Kotlin its essential to know the importance of Java.</p><p><strong>Java:</strong></p><p>Java is the most popular and widely used object oriented programming language. Java is mainly used to develop Enterprise applications, Android application and Server-side programming.</p><p><strong>Kotlin:</strong></p><p>Kotlin is also a object oriented programming language which is interoperable with Java. For example, a Android application can be half coded in Java and the other half in Kotlin. Lets understand how?</p><p>Kotlin is a JVM based language just like Java, i.e. The the Kotlin compiler after compilation generates the byte code which is same as that of Java’s byte code produced by Java compiler. Thus both can run on JVM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ix4eh8NjWcMCw1zts3OSxQ.gif" /></figure><p>Is Kotlin faster than Java? <strong>Kotlin’s performance is comparable to Java’s performance</strong>. Thus Kotlin offers same runtime as Java.</p><blockquote>Note: Java has improved over the years but the one I have used here might be outdated.</blockquote><p>What makes Kotlin better?</p><p>Syntax is one of the Kotlin’s biggest advantage. Kotlin requires significantly lesser code than java, which makes code look more simpler and readable.</p><p>Lets try to understand it better,</p><p><strong>1.Null-Safety</strong></p><p>Heard about<a href="https://hackernoon.com/null-the-billion-dollar-mistake-8t5z32d6"> billion dollar mistake</a>? its the NULL reference.</p><p>Lets take a practical example, Suppose you are doing a API call and expecting a String response from the server. But somethings goes wrong underway. What do you get as response? its null!</p><pre><br>String respose = &lt;Response from API&gt;;<br><br>System.out.println(response.length());// You are actually trying to do null.length()</pre><p>What do you expect here,</p><pre>Exception in thread &quot;main&quot; java.lang.NullPointerException<br>	at Temp.main(Temp.java:7)</pre><p><strong>Java Solution:</strong></p><pre>String response = &lt;Response from API&gt;;<br><br>if(response != null)<br>{<br>  System.out.println(response.length());<br>}<br>else<br>{<br>System.out.println((String)null);<br>}</pre><p>The above solution looks pretty obvious but lengthy too.</p><p>Kotlin comes with a null safety operator (?)</p><p>Kotlin distinguishes variables in Nullable and Non-Nullable</p><pre><br>Kotlin Non-nullable:<br><br>var name:String = &quot;Kotlin&quot;<br>name = null                 // compilation error<br><br><br>Kotlin nullable:<br><br>var name : String? = &quot;Kotlin&quot;<br>name=null            //no compilation error<br><br><br>Java:<br><br>String name = &quot;Java&quot;;    <br>name = null                 // No compilation error</pre><p><strong>Kotlin Solution:</strong></p><pre>var response: String? = &lt;response from api&gt;<br><br>println(response?.length);<br></pre><p>response?.length returns the length of the string if response is non-null else it returns null. Thus its a replacement for Java’s if-else check.</p><p><strong>2. Data classes:</strong></p><p>Object oriented programming mainly deals with real world objects. Thus entities are always the part of our project. Most of the time we require a class with only members variables (States only) to store data. Example: Student, Course</p><p>Entity: Student<br>Attribute: Name, USN, DOB, Email id, Address, Phone number and more.</p><p><strong>Java Solution:</strong></p><pre>public class Student {<br><br>    private String name;<br>    private String USN;<br>    private String emailID;<br>    private String address;<br><br>    public Student(String name, String USN, String emailID, String address) {<br>        this.name = name;<br>        this.USN = USN;<br>        this.emailID = emailID;<br>        this.address = address;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getUSN() {<br>        return USN;<br>    }<br><br>    public void setUSN(String USN) {<br>        this.USN = USN;<br>    }<br><br>    public String getEmailID() {<br>        return emailID;<br>    }<br><br>    public void setEmailID(String emailID) {<br>        this.emailID = emailID;<br>    }<br><br>    public String getAddress() {<br>        return address;<br>    }<br><br>    public void setAddress(String address) {<br>        this.address = address;<br>    }<br><br>}</pre><p>Now lets print the object of Student class,</p><pre><br>class Main<br>{<br><br>  public static void main(String[] args)<br>  {<br>    Student student = new Student(&quot;Sandeep&quot;,&quot;2342&quot;,&quot;hi@example.com&quot;,&quot;Bengaluru&quot;);<br>    System.out.println(student);<br>  }<br><br>}</pre><pre>Output: <br><br>Student@3fee733d</pre><p>This doesn’t seem to the expected output, hence the solution for this is overriding toString() in the Student class.</p><pre>@Override<br>    public String toString() {<br>        return &quot;Studentt{&quot; +<br>                &quot;name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, USN=&#39;&quot; + USN + &#39;\&#39;&#39; +<br>                &quot;, emailID=&#39;&quot; + emailID + &#39;\&#39;&#39; +<br>                &quot;, address=&#39;&quot; + address + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }</pre><p>Now it works fine. But that is a lot of code.</p><p><strong>Kotlin Solution:</strong></p><p>Kotlin comes with a data class which doesnt require getters and setter, toString().</p><pre>data class Student(var name:String,var USN:String, var emailId:String,var address:String)</pre><p>Done! now lets populate some data and print it:</p><pre>fun main()<br>{<br>  var student: Student = Student(&quot;Sandeep&quot;,&quot;2342&quot;,&quot;mssk@example.com&quot;,&quot;Bengaluru&quot;)<br>  println(student);<br>}</pre><pre>Output:<br><br>Student(name=Sandeep, USN=2342, emailId=mssk@example.com, address=Bengaluru)</pre><p><strong>3.String templates:</strong></p><p>Print functions are widely used in every programming language. How do we print a variable along with string description to it?</p><p><strong>Java Solution:</strong></p><pre>class Main<br>{<br><br>  public static void main(String[] args)<br>  {<br>    String name = &quot;XYZ&quot;;<br>    System.out.println(&quot;My name is &quot; + name + &quot;, I am ......(your story)&quot;);<br>    System.out.println(&quot;Length of the string is &quot; + name.length());<br>  }<br><br>}</pre><p><strong>Kotlin solution:</strong></p><p>${variable_name}</p><pre>fun main()<br>{<br>  var name = &quot;XYZ&quot; //need not need to define datatype in kotlin<br>  println(&quot;My name is $name I am ......(your story)&quot;)<br>  println(&quot;Length of the string is ${name.length} &quot;)<br>}</pre><p><strong>4. Extension Functions:</strong></p><p>Kotlin <strong>extension function</strong> provides a facility to <strong>“add”</strong> methods to class without inheriting a class or using any type of design pattern.</p><p>Say you have a Kotlin Inbuilt Class with some method defined in it and you want to add more functions. This is achived using extension functions.</p><p>Example: MutableList&lt;&gt; is the List in Kotlin and you want to add swap function to it.</p><pre>fun MutableList&lt;Int&gt;.swap(index1: Int, index2: Int):MutableList&lt;Int&gt; <br>{  <br>    val tmp = this[index1]      // &#39;this&#39; represents to the list  <br>    this[index1] = this[index2]  <br>    this[index2] = tmp  <br>    return this  <br>}  <br><br>fun main(args: Array&lt;String&gt;) {  <br><br>val list = mutableListOf(5,10,15)  <br>println(&quot;before swapping the list :$list&quot;)  <br>val result = list.swap(0, 2)  <br>println(&quot;after swapping the list :$result&quot;)  <br><br>}  </pre><p><strong>5. Singletons:</strong></p><p>Singleton classes are classes with only one instance/object. This is widely used in android to achieve a single instance of API request queue (Volley library).</p><p><strong>Java Solution:</strong>class Singleton<br>{<br> private static Singleton singleton=null;<br><br> // have constructor, variables, methods here.<br><br> public String name = &quot;XYZ&quot;;<br> <br> public static synchronized Singleton getInstance()<br> {<br><br> if(singleton==null)<br> singleton = new Singleton();<br><br> return singleton;<br><br> }<br><br>}<br><br>Class Main<br>{<br> public static void main(String[] args)<br> {<br><br> Singleton s1 = Singleton.getInstance();<br> Singleton s2= Singleton.getInstance();<br> // Here s2 is equivalent (pointing) to s1 and thus only one object can be created.<br> }<br>}</p><p>The above implementation is self explanatory i.e. getInstance() return a new object only for the first time.</p><p><strong>Kotlin Solution:</strong></p><pre>Object Singleton<br>{<br>   var name:String = &quot;XYZ&quot;;<br>   // have init, variables, methods here.<br>}<br><br>fun main()<br>{<br>println(&quot;${Singleton.name}&quot;);<br>}<br></pre><p>6. Smart Casts:</p><p>In most cases, you don’t need to use explicit cast operators in Kotlin because the compiler tracks the is-checks and explicit casts for immutable values and inserts (safe) casts automatically when necessary:</p><pre>fun demo(x: Any) {<br><br>  if (x is String) <br>  {<br><br>   print(x.length) // x is automatically cast to String <br><br>  } <br><br>//When is switch statement in Kotlin<br><br> when (x) {<br><br>    is Int -&gt; print(x + 1)<br><br>    is String -&gt; print(x.length + 1)<br><br>    is IntArray -&gt; print(x.sum())<br><br> }<br><br>}</pre><p><strong>7. Many More:</strong></p><p>There are many other functionalities provided by Kotlin which makes it better than Java.</p><p>Some of them are:</p><ul><li><a href="https://kotlinlang.org/docs/lambdas.html">Lambda expressions</a> + <a href="https://kotlinlang.org/docs/inline-functions.html">Inline functions</a> = performant custom control structures</li><li><a href="https://kotlinlang.org/docs/typecasts.html">Smart casts</a></li><li><a href="https://kotlinlang.org/docs/properties.html">Properties</a></li><li><a href="https://kotlinlang.org/docs/classes.html">Primary constructors</a></li><li><a href="https://kotlinlang.org/docs/delegation.html">First-class delegation</a></li><li><a href="https://kotlinlang.org/docs/basic-types.html">Type inference for variable and property types</a></li><li><a href="https://kotlinlang.org/docs/generics.html">Declaration-site variance &amp; Type projections</a></li><li><a href="https://kotlinlang.org/docs/ranges.html">Range expressions</a></li><li><a href="https://kotlinlang.org/docs/operator-overloading.html">Operator overloading</a></li><li><a href="https://kotlinlang.org/docs/classes.html#companion-objects">Companion objects</a></li><li><a href="https://kotlinlang.org/docs/collections-overview.html">Separate interfaces for read-only and mutable collections</a></li><li><a href="https://kotlinlang.org/docs/coroutines-overview.html">Coroutines</a></li></ul><p><strong>Bonus:</strong></p><p>Kotlin is not only better that Java in syntax but also provides powerful yet lightweight Framework.</p><p><strong>Ktor for RESTful API:</strong></p><p>Kotlin’s Ktor vs Java Spring boot:</p><p>Both are equally good, but Kotlin’s Ktor is comparatively lighter and simpler in setup/integration compared to spring boot. Kotlin’s coroutines also is a plus point.</p><p>Here’s the simple Authorization RESTAPI using Ktor,</p><p><a href="https://github.com/mssandeepkamath/Authorization_RESTAPI">GitHub - mssandeepkamath/Authorization_RESTAPI: Authentication RESTful API using Kotlin&#39;s ktor, Postgresql and JWT.</a></p><p>My sincere apologies for any errors in the article, Thanks for your time, I hope it was helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=336c50fef9ed" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/why-kotlin-over-java-336c50fef9ed">Why Kotlin over Java</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>