<?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 Paul Núñez on Medium]]></title>
        <description><![CDATA[Stories by Paul Núñez on Medium]]></description>
        <link>https://medium.com/@paulnunezm?source=rss-7700451cbec1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GZdugXiNHOlqjiGaQMoemQ.jpeg</url>
            <title>Stories by Paul Núñez on Medium</title>
            <link>https://medium.com/@paulnunezm?source=rss-7700451cbec1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 18:55:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@paulnunezm/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[The joy of relearning algorithms: Why learning different approaches matter]]></title>
            <link>https://medium.com/@paulnunezm/the-joy-of-relearning-algorithms-why-learning-different-approaches-matter-1f8b1014954e?source=rss-7700451cbec1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f8b1014954e</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[quicksort]]></category>
            <dc:creator><![CDATA[Paul Núñez]]></dc:creator>
            <pubDate>Fri, 29 Nov 2024 10:48:52 GMT</pubDate>
            <atom:updated>2024-11-29T10:52:25.509Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pU4Twp1aeIGvAfYX" /><figcaption>Photo by <a href="https://unsplash.com/@sen7?utm_source=medium&amp;utm_medium=referral">Sen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>TL; DR</h3><p>Give yourself the chance of learning a new approach to solve a familiar problem, it can provide new perspectives that can help you when confronting new ones.</p><h3>Intro</h3><p>Sometimes I like to replay video games and when I do I like to do things different on each run. I’m currently relearning Data Structure and Algorithms (DSA) and wondered if I could, just like replaying video games, find new, fun and interesting ways to do the same things. And for one topic, I did and learned more than I was expecting.</p><h3>Relearning</h3><p>Advent of Code approaches and I wanted to sharpen my problem solving skills by relearning some algorithms from scratch. While seeing a Quicksort explanation video from <a href="https://frontendmasters.com/courses/algorithms/">ThePrimeagen’s <em>The Last Algorithms Course You’ll Need</em></a> noticed that the way he implemented Quicksort it’s different of what I just learned from <a href="https://www.manning.com/books/grokking-algorithms">Grooking’s Algorithms book</a> and that was also different from the way I had learned before, something I wasn’t expecting but I was glad to find.</p><p>Although all implementations talked here use recursion and Divide &amp; Conquer (D&amp;C) the little differences are the things I really learn about.</p><h3>Implementations</h3><p>I’ll go trough the three implementations I covered and list the major points of learnings that I was able to grab from each one.</p><h3>Grooking Algorithm</h3><pre>def quicksort(array):<br>  if len(array) &lt; 2:<br>    return array<br>  else:<br>    pivot = array[0] # Grabs the first value as the pivot<br>    less = [i for i in array[1:] if i &lt;= pivot]<br>    greater = [i for i in array[1:] if i &gt; pivot] <br>    return quicksort(less) + [pivot] + quicksort(greater)</pre><p><strong>Key points:</strong></p><ul><li>Simple and small implementation.</li><li>Only one recursive base case. Which is easy to remember and hard to miss when rewriting.</li><li>Uses the first element as the pivot.</li><li>Pre recursion step it’s easy but creates two sub-arrays. Which can be great if you can afford to have more Space complexity.</li><li>Doesn’t require a partition function as the other implementation.</li></ul><p>I think this implementation is, from the ones showed here, the easiest to learn. There’s no surprise of why it was chosen by the author to teach about (D&amp;C) and as the Quicksort implementation on the book.</p><h3>ThePrimeagen course</h3><pre>function qs(arr: number[], lo: number, hi: number): void {<br>  if (low &gt;= hi) {<br>  return;<br>  }<br>  <br>  const pivotIdx = partition(arr, lo, hi);<br>  <br>  qs(arr, lo, pivotIdx - 1);<br>  qs(arr, pivotIdx, hi);<br>}<br><br>function partition(arr: number[], low: number, hi: number): number {<br>  const pivot = arr[hi]; // Grabs the last value as the pivot<br>  <br>  let idx = lo - 1; // Initializes the pointer before the array&#39;s initial position<br>  <br>  for (let i = lo; i &lt; hi; i++) {<br>    if(arr[i] &lt;= pivot) {<br>      idx++;<br>      // Swaps arr[i] with arr[idx]<br>    }<br>  }<br>  <br>  idx++;<br>  // swaps the pivot with arr[idx]<br>}</pre><p><strong>Key points:</strong></p><ul><li>Sorting happens in-place, meaning that the sort is done using the same array that was provided no extra Space needed.</li><li>Uses two pointers technique. A technique that can be used to solve a myriad of problems and a necessary one if your planning to solve DSA questions.</li><li>Has one simple recursive base case.</li><li>Uses the last index as its pivot value.</li><li>Fairly easy to remember and to derive after you fully understand and grasp the idea behind the two pointers.</li><li>Has a partition function to do the in-place sorting on a dedicated function.</li></ul><p>The great part of this code is not just that is solves the problem without using extra memory by moving elements inside the given array but rather the fact that it shows how to use another problem solving technique, two pointers [link] , and something I never though before, initializing the first pointer before the array’s first index, something I still don’t know if I would use it in the future but I’m sure it will be great to have in the toolbox.</p><h3>Cracking the Coding Interview</h3><pre>void quickSort(int[] arr, int left, int right) {<br>  int index partition(arr, left, right); <br>  if (left &lt; index - 1) {  <br>    quickSort(arr, left, index - 1); <br>  }<br>  <br>  if (index &lt; right) { <br>    quickSort(arr, index, right); <br>  }<br>}<br><br>int partition(int[] arr, int left, int right) {<br>  // Picks pivot point from the middle<br>  int pivot = arr[(left + right) / 2]; <br>  <br>  while (left &lt;= right) {<br>    while(arr[left &lt; pivot) left++;<br>    while(arr[right &gt; pivot) right--;<br>    <br>    if (left &lt;= right) { <br>      // swap alements arr[left] and arr[right]<br>    }<br>  }<br>  return left;<br>}</pre><p><strong>Key points:</strong></p><ul><li>Also uses a two pointers and a partition function.</li><li>Has two recursive base cases. May not as clear to the ones not so used to recursion.</li><li>Although two pointers are being used, they behave on a completely different away.</li><li>Uses three whiles to move the cursors around and perform the sorting.</li></ul><p>To my surprise even though this approach also uses two pointers to partition the array, it uses them differently by thinking on the same algorithm on from another perspective, instead of comparing adjacent array values it compares elements starting at each corner of the array and using inner whiles to move the cursors.</p><h3>Final thoughts</h3><p>If I had decided to skip relearning Quicksort, something I though I knew just because I know recursion and the idea of D&amp;C, I would have never seen the approaches taken from these authors and wouldn’t have seen the problems with newer eyes.</p><p>I think that revisiting familiar problems and algorithms like Quicksort can definitely sharpen our problem solving skills and improve our understandings of fundamental concepts by learning new techniques or at least provide a fresh perspective on how to approach new problems.</p><p>Each of the previous approaches comes with they own benefits and ease of implementation but the great part, the one that encouraged me to write this article is to see the multiple ways we can tackle the same algorithm by approaching it from a whole new way of thinking. These kind of things are the things that makes me enjoy programming, keep learning and try to tackle this year’s Advent of Code.</p><h3>Bibliography</h3><ul><li>Laakmann McDowell, G. <em>Cracking the Coding Interview</em>. 6th ed. CarreerCup.</li><li>Bhargava, A. Y. <em>Grooking Algorithms</em>. Manning Publications.</li><li>ThePrimeagen (2022, September 12). <em>The Last Algorithms Course You’ll Need</em>. <a href="https://frontendmasters.com/courses/algorithms/">https://frontendmasters.com/courses/algorithms/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f8b1014954e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Canvas animations: Simple Circle Progress View on Android]]></title>
            <link>https://medium.com/@paulnunezm/canvas-animations-simple-circle-progress-view-on-android-8309900ab8ed?source=rss-7700451cbec1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8309900ab8ed</guid>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Paul Núñez]]></dc:creator>
            <pubDate>Wed, 30 Sep 2020 18:53:23 GMT</pubDate>
            <atom:updated>2020-09-30T18:53:23.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Photo by Daniel Cheung on Unsplash" src="https://cdn-images-1.medium.com/max/640/1*N6PF8uBsDPb7ZH8kUobxig.jpeg" /><figcaption><a href="https://unsplash.com/photos/ZqqlOZyGG7g"><strong>Photo by Daniel Cheung on Unsplash</strong></a></figcaption></figure><p>The Android Class class lets us draw anything* that we can imagine using basic shapes, paths, and bitmaps. <a href="https://developer.android.com/reference/android/graphics/Canvas">The Canvas API</a> it’s really big 🤯 and daunting at first sight. Here we’re only going to scratch the surface to create our simple animation.</p><h3>The animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*XKLmOFxtkRoZlTLVSH27Ag.gif" /><figcaption>Full circle progress animation</figcaption></figure><h3>Note</h3><p>This article will be covering each step for conceiving the animation but I do recommend reading a bit further: <a href="https://medium.com/over-engineering/getting-started-with-drawing-on-the-android-canvas-621cf512f4c7">Getting started with drawing on the Android Canvas</a> by <a href="https://medium.com/@riggaroo">Rebecca Franks</a> it’s a great read 🤓.</p><h3>Ok, lets started!</h3><p>You may know the drill. Create a new project, with an empty activity, and create a class that extends from the AndroidView class:</p><pre>class CircularProgressView(<br>    context: Context?,<br>    attrs: AttributeSet?<br>) : View(context, attrs) {}</pre><p>And now we have our ready to draw on view! 🙌</p><h3><strong>What do we need to draw?</strong></h3><p>In order to achieve this animation we first have to know how to draw the circles, we need one to be the background and another arc to fill the current progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vG5Oyr1iTn7Uv9YOFQ0RQ.png" /><figcaption>Background arc at the left and inner arc to mark the progress at the right.</figcaption></figure><h3>And how can we draw it?</h3><p>Each view comes with a onDraw method override which provides us with a Canvas instance for us to start drawing with. To achieve our animation we need to create draw two arcs using the canvas instance, one arc for the background, and one of the tops, which will be the one to be animated. For that, we’ll need to use the Canvas#drawArcmethod, which can let us draw a circle with nothing on the inside.</p><p>Let’s take a look into it 🖌.</p><pre>public void drawArc (<br> <a href="https://developer.android.com/reference/android/graphics/RectF"><strong>RectF</strong></a> oval, <br> float startAngle, <br> float sweepAngle, <br> boolean useCenter, <br> <a href="https://developer.android.com/reference/android/graphics/Paint"><strong>Paint</strong></a> paint<br>)</pre><p>Nice, but what do they mean?</p><ul><li>The <strong>RectF </strong>oval is just a holder for the coordinates needed to create an “invisible rectangle” in which our oval will be contained. This oval is <em>used to define the shape and size of the arc.</em></li><li>startAngle: is the degree starting point from our oval from where we are going to start drawing the arc.</li><li>sweepAngle: means how much of the arc is going to be painted from the startAngle to this angle.</li><li>useCenter: the documentation explains it as,<a href="https://developer.android.com/reference/android/graphics/Canvas#drawArc(android.graphics.RectF,%20float,%20float,%20boolean,%20android.graphics.Paint)"> <em>if true, include the center of the oval in the arc, and close it if it is being stroked. This will draw a wedge.</em></a></li><li>paint: this is the object that provides the information to the drawing of how it should be stroked, it’s color, and more.</li></ul><h3>Drawing the background circle 🎨</h3><p>Now that we understand what we need in order to draw an arc, let’s get to the code.</p><p>In our view’s onDraw method we should create our oval’s RectF space with the correct dimensions we want our circle progress to have:</p><pre>// ...</pre><pre>private val ovalSpace = RectF<em>()</em></pre><pre>override fun onDraw<em>(</em>canvas: Canvas?<em>) {<br>    </em>setSpace<em>() </em><strong><br></strong><em>}<br><br></em>private fun setSpace<em>() {<br>    </em>val horizontalCenter = <em>(width</em>.div<em>(</em>2<em>))</em>.toFloat<em>()<br>    </em>val verticalCenter = <em>(height</em>.div<em>(</em>2<em>))</em>.toFloat<em>()<br>    </em>val ovalSize = 200<br>    ovalSpace.set<em>(<br>        </em>horizontalCenter - ovalSize,<br>        verticalCenter - ovalSize,<br>        horizontalCenter + ovalSize,<br>        verticalCenter + ovalSize<br>    <em>)<br>}</em></pre><p>As this won&#39;t be painted it would only represent an invisible <em>oval space</em> like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aqZuRvv4IklzOWauzLTrpA.png" /><figcaption>Invisible oval space representation.</figcaption></figure><p>After we have our <em>oval space</em> we can use the canvas object to draw our arc on it. But in order to visualize it, we need a paint object to pass the to the drawArc canvas method. Let’s create it:</p><pre>// ...</pre><pre>private val parentArcColor = context?.resources?.getColor(R.color.gray_light, null) ?: Color.GRAY<br><br>private val parentArcPaint = Paint().apply <strong>{<br>    </strong>style = Paint.Style.STROKE<br>    isAntiAlias = true<br>    color = parentArcColor<br>    strokeWidth = 40f<br><strong>}</strong></pre><pre>// ...</pre><p>The paint object arguments are self-explanatory, but a good thing to note is to:</p><blockquote><em>Use the </em><em>isAntiAlias flag to ensure your drawing has smooth edges.</em></blockquote><p>And let it be a circle 🎨</p><pre>// ...</pre><pre>override fun onDraw<em>(</em>canvas: Canvas?<em>) {<br>    </em>setSpace<em>()<br>    </em>canvas?.<em>let </em><strong>{<br>        </strong>it.drawArc<em>(</em>ovalSpace, 0f, 360f, false, parentArcPaint<em>)<br>    </em><strong>}<br></strong><em>}</em></pre><p>In order to see anything, we need to make sure our custom view is added to the main activity layout. The name of the custom widget will be the name of our class in this case CirculaProgressView.</p><pre><em>&lt;</em>com.labs.circularprogress.CircularProgressView<br>    android:id=&quot;@+id/progress&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;200dp&quot;<br>    app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>    app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>    app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>    app:layout_constraintTop_toTopOf=&quot;parent&quot; <em>/&gt;</em></pre><p>And we will be able to see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*790nVU4D06XVrCTyxqq2Bw.png" /><figcaption>Background arc.</figcaption></figure><h3>Drawing the inner circle 🎨</h3><p>Now that we already know how to draw an arc, this part would be easy, just declare a paint object for it and draw it on our onDraw method. There would be a few differences, but I’ll be explaining each of the ones. Let&#39;s see:</p><pre>// ...<br>private val fillArcPaint = Paint<em>()</em>.<em>apply </em><strong>{<br>    </strong><em>style </em>= Paint.Style.STROKE<br>    <em>isAntiAlias </em>= true <br>    <em>color </em>= fillArcColor<br>    <em>strokeWidth </em>= 40f</pre><pre>    // 1<br>    <em>strokeCap </em>= Paint.Cap.ROUND <br><strong>}</strong></pre><pre>override fun onDraw<em>(</em>canvas: Canvas?<em>) {<br>    </em>setSpace<em>()<br>    </em>canvas?.<em>let </em><strong>{</strong></pre><pre><em>        // 2<br></em><strong>        </strong>drawBackgroundArc<em>(</em><strong>it</strong><em>)</em></pre><pre><em>        // 3<br>        </em>drawInnerArc<em>(</em><strong>it</strong><em>)<br>    </em><strong>}<br></strong><em>}</em></pre><pre>private fun drawBackgroundArc<em>(</em>it: Canvas<em>) {<br>    </em>it.drawArc<em>(</em>ovalSpace, 0f, 360f, false, parentArcPaint<em>)<br>}<br><br></em>private fun drawInnerArc<em>(</em>canvas: Canvas<em>) {<br> // 4<br> </em>val percentageToFill = 180f</pre><pre><em> // 5<br> </em>canvas.drawArc<em>(</em>ovalSpace, 270f, percentageToFill, false, fillArcPaint<em>)<br>}</em></pre><p><strong>Taking a look at the differences 🧐</strong></p><ol><li><em>strokeCap </em>= Paint.Cap.ROUND this would make the edge of the stroke while drawing to look round instead of flat.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JGglXzjlmYe02s_Vv1OAJA.png" /><figcaption>The left arc shows a square cap and the right a rounded one.</figcaption></figure><p>2. We moved the logic to draw the background arc into it’s own functions to improve readability at the onDraw method.</p><p>3. Created another function that will take care of drawing the inner arc.</p><p>4. We set the canvas#drawArc sweepAngle parameter to 180f as right now we only want to draw half of the circle.</p><p>5. Here we can notice a <strong>270f</strong> value for our startAngle parameter, this is because the angle diagram does not start as we use to. The 270f value will set the startAngle at the top as you could see in the next image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_a72LXpBdIAp7stQFAePJQ.png" /><figcaption>Android canvas angle system</figcaption></figure><h3>Let’s start with animations 🚀</h3><p>Let’s do a tiny recap. In order to be able to draw something, we need to specify everything that we want to show at our view onDraw function. Easy peasy right? Now… if we want to display something new in our canvas we need to draw everything we had before and then draw the new thing we want it to appear, in our case this new thing would be an incrementing arc to show the progress.</p><p>To achieve this we need a few things:</p><ul><li>A value that indicates the percent of our arc to draw and that we can change dynamically that can be read from our onDraw function</li><li>Draw the new value</li><li>And call a redraw for our view</li><li>And repeat</li></ul><p>First, let’s change our drawInnerArc function to use a dynamic currentPercentage value to determine the percentage fill to be drawn:</p><pre>private var currentPercentage = 0</pre><pre>//...</pre><pre>private fun drawInnerArc<em>(</em>canvas: Canvas<em>) {<br>    </em>val percentageToFill = getCurrentPercentageToFill<em>()<br>    </em>canvas.drawArc<em>(</em>ovalSpace, 270f, percentageToFill, false, fillArcPaint<em>)<br>}<br><br></em>private fun getCurrentPercentageToFill<em>() </em>=<br>    <em>(</em>ARC_FULL_ROTATION_DEGREE * <em>(</em>currentPercentage / PERCENTAGE_DIVIDER<em>))</em>.toFloat<em>()</em></pre><p>To draw the new value, we have to ask the view for a redraw and this is done b calling the view invalidate() method when a redraw is needed.</p><p>Now we&#39;ll create a function to be called when we want to perform the animation. Here we use Android’s <a href="https://developer.android.com/reference/android/animation/ValueAnimator">ValueAnimator</a>class to helps us change the the currentPercentage value through time and call our viewinvalidate() on each change, so it can be visualized.</p><blockquote>The documentation defines the ValueAnimator class a <em>a simple timing engine for running animations which calculate animated values and set them on target objects.</em></blockquote><p>In our case, we want to animate from values 0% to 100%, and this class will make achieve this animation a piece of cake. So let’s take a look into the code, a, I’ll explain each step on the go:</p><pre>fun animateProgress<em>() {<br>   // 1<br>   </em>val valuesHolder = PropertyValuesHolder.ofFloat<em>(<br>        </em>PERCENTAGE_VALUE_HOLDER,<br>        0f,<br>        100f<br>    <em>)</em></pre><pre><em><br>    // 2<br>    </em>val animator = ValueAnimator<em>()</em>.<em>apply </em><strong>{<br>        </strong>setValues<em>(</em>valuesHolder<em>)<br>        duration </em>= 1000<br>        <em>interpolator </em>= AccelerateDecelerateInterpolator<em>()</em></pre><pre><em><br>        // 3<br>        </em>addUpdateListener <strong>{</strong></pre><pre><strong>            // 4<br>            </strong>val percentage = <strong>it</strong>.getAnimatedValue<em>(</em>PERCENTAGE_VALUE_HOLDER<em>) </em>as Float<br>           <br>            // 5<br>            currentPercentage = percentage.toInt<em>()<br>           <br>             // 6<br>            </em>invalidate<em>()<br>        </em><strong>}<br>    }</strong></pre><pre><strong>    // 7<br>    </strong>animator.start<em>()<br>}</em></pre><pre>companion object <em>{<br>     // ...</em><br>    const val PERCENTAGE_VALUE_HOLDER = &quot;percentage&quot;<br><em>}</em></pre><ol><li>We create a PropertyValuesHolder instance for holding the values that we want to animate. In this case, we will animate from 0 to 100 percent. In order to create this instance we also need to pass a propertyName that we will use later to grab the current animated value from the animator.</li><li>Here we create an instance of ValueAnimator, we set the property values declared before and also pass how much time in milliseconds we want the animation to last.</li><li>This will be called on every frame of the animation, providing us with the calculated percentage value for a specific frame. This value will be used to update the currentPercentage animation later.</li><li>We get the current animation value (animatedValue) from our updateListener using the propertyName declared earlier.</li><li>Update the currentPercentage variable that is used to draw our inner arc on each onDraw call.</li><li>Now we call for a view redraw after we already updated the value.</li><li>We run our animation.</li></ol><blockquote>Note: This animation will start only when the function animateProgress get called.</blockquote><p>In order to trigger our new animation, we’ll need to add a Button to our activity layout in order to perform start it when clicking the button.</p><pre><em>// ... </em></pre><pre><em>    &lt;</em>Button<br>        android:id=&quot;@+id/animateButton&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;animate&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@+id/progress&quot; <em>/&gt;</em></pre><pre><em>// ...</em></pre><p>And add a clickListener on our Activity class:</p><pre>animateButton.setOnClickListener <strong>{<br>    </strong>progress.animateProgress<em>()<br></em><strong>}</strong></pre><p>And there you go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*XKLmOFxtkRoZlTLVSH27Ag.gif" /><figcaption>Final animation</figcaption></figure><p>You can find the full code <a href="https://github.com/paulnunezm/circularProgressView">here</a>.</p><p>Hope you enjoyed this post, you can follow me on twitter <a href="http://twitter.com/paulnunezm">@paulnunezm</a> where I usually tweet about Android Dev. And let please let me know what you think in the comment section bellow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8309900ab8ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Steps for creating a Content Provider]]></title>
            <link>https://medium.com/@paulnunezm/steps-for-creating-a-content-provider-ab376d661613?source=rss-7700451cbec1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab376d661613</guid>
            <category><![CDATA[contentprovider]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Paul Núñez]]></dc:creator>
            <pubDate>Tue, 07 Nov 2017 04:03:36 GMT</pubDate>
            <atom:updated>2017-11-07T04:04:21.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Meanwhile I study for the Android Developer Certification, I decided to document briefly the series of steps for setting up a Content Provider. I usually haven’t had the need to use it, but it is a handy tool to have in our utility belt, and as it is one of the core Android components, something we should be familiarized with.</p><p>I have to say that this isn’t exactly a tutorial for creating it, here I just show the major points. For more details you could check <a href="https://guides.codepath.com/android/Creating-Content-Providers">Codepath</a>’s guide for creating it, or other greats tutorials in the web.</p><p>Before we start, we need to have a few definitions fresh:</p><ul><li><a href="https://en.wikipedia.org/wiki/Uniform_Resource_Identifier"><strong>URI (Uniform Resource Identifier):</strong></a><strong><br></strong> Are used to identify or give the location of some content or data. IE: URL’s.</li><li><a href="https://developer.android.com/guide/topics/providers/content-provider-creating.html#TableMIMETypes"><strong>MIME types:</strong><br></a>These are the strings that describe the type of data stored at the input URI. This is also now as the <em>Content-Type.</em> A good example for this functionality is when you’re sending an implicit intent with an URI on the data field, the system will check the MIME type of that URI to determine which app component on the device can handle the request.</li></ul><h3>Steps for creating a Content Provider</h3><h4>1. Create a table contract:</h4><p>In this class will be declared all the information associated with the table, such as: the content authority, the path to the items, the item entry class and the SQL sentences, more about these at the bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*-mKvxtfvlJS5yJBUCgGMrg.png" /><figcaption>Product table contract.</figcaption></figure><ul><li><strong>Content Authority:</strong> A name for the entire Content Provider, that will help us locate it. This similar to the relationship between a domain name and its website. It is a common behavior to use the top package of your app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*IsV3QD2BngJ8GyS0U-VjBQ.png" /><figcaption>Declaring the content authority.</figcaption></figure><ul><li><strong>Item path:</strong> Possible path (appended to base content URI for possible URI’s). For instance,<em> content://com.example.android.products/products/</em> is a valid path for looking at product data. <em>content://com.example.android.product/staff/</em> will fail, as the ContentProvider hasn’t been given any information on what to do with “staff”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*EsI-S6zpN5XT9NtnRSGr9w.png" /><figcaption>Item path to be appended to the base content URI.</figcaption></figure><ul><li><strong>Item entry class: </strong>This class will define all table contents and should implement the BaseColumns interface. This interface only adds two static Strings variables to use as columns. These variables are: ID for the “_id” and COUNT for “_count” columns.</li></ul><p>We will create this as an inner class of ProductContract. The contents we will be defining on this class are:</p><ol><li>The content URI</li><li>The MIME for being able to know if we are working with a list or a single item</li><li>Table name</li><li>Column names</li><li>Relations</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Qz9009UKQZgQaEh0RaCXw.png" /><figcaption>Product entry values.</figcaption></figure><ul><li><strong>SQL create and delete table statements:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*-z6nkjd1MUP_Z-G99iJdhQ.png" /><figcaption>SQL for creating and delete the products table.</figcaption></figure><h4><strong>2. Setting up the Database helper:</strong></h4><p>For this Android provides a class named <em>SQLiteOpenHelper, </em>and as the documentation says, this class will <em>manage the database creation and versioning.</em></p><p>This step is very straight forward, we just have to extend the <em>SQLiteOpenHelper, </em>pass the database name and version to the super class<em> </em>and override the onCreate and onUpgrade methods:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VTLtMFuPyP5vi8rg9jrLQ.png" /><figcaption>ProductDbHelper class.</figcaption></figure><p>For the<em> onUpgrade</em> method, depending of the use case, you may have to handle the migration so all the user data is not deleted.</p><h4>3. Setting up de Content Provider:</h4><ul><li><strong>Create a class that extends from ContentProvider and implement the corresponding methods. </strong>All the code presented on this step will be inside this class.</li><li><strong>Declare URI’s matcher codes for each type of item:</strong><br>These are used along with the <em>UriMatcher</em> to create a URI pattern to help us <em>“choose the action we are going to make for an incoming content URI”</em>, instead of returning the whole content URI it will return integer values that we declare by ourselves. These are random but must be different and unique.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*epyks91DHkUnRE7xTjnVlw.png" /><figcaption>URI matcher codes.</figcaption></figure><ul><li><strong>Instantiate the URI matcher:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AA9b3GNLrf8Gn0usOVUIGg.png" /><figcaption>URI matcher.</figcaption></figure><ul><li><strong>Now create the content URIs:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TcT44ECsjeWPyazhIyL7FA.png" /><figcaption>Content URIs.</figcaption></figure><ul><li><strong>In the getType method set the URI matchers to return the correct MIME:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OToJEidIJ71QDaxsHzakLw.png" /><figcaption>The getType method of the ProductProvider class.</figcaption></figure><ul><li><strong>Implement the CRUD methods: </strong>In these we can check, with the URI matcher, the type of content the user is requesting, in this case if is one product or many. Lets see an implementation for the query method:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGKNohnZsOPPRyYGvFLBuA.png" /><figcaption>Query method of the ProductProvider class.</figcaption></figure><h4>4. <strong>Declare it on the manifest:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*ivBOnHnmYlJcHCgxmFoGfQ.png" /><figcaption>Declaring the content provider in the manifest.xml.</figcaption></figure><p>And those are the basic steps for creating a content provider!</p><p>Hope you enjoyed this post, you can follow me on twitter <a href="http://twitter.com/paulnunezm">@paulnunezm</a>where I usually tweet about Android Dev. And let please let me know what you think in the comment section bellow.</p><h3>References:</h3><ul><li><a href="https://developer.android.com/guide/topics/providers/content-provider-creating.html">Creating a Content Provider | Android Developers</a></li><li><a href="https://guides.codepath.com/android/Creating-Content-Providers">Creating Content Providers | CodePath Android Cliffnotes</a></li><li><a href="https://www.udacity.com/course/android-developer-nanodegree-by-google--nd801">Android Developer Online Course</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab376d661613" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simpler multiple click listeners with Kotlin Sealed classes]]></title>
            <link>https://medium.com/@paulnunezm/simpler-multiple-click-listeners-with-kotlin-sealed-classes-72a8f6e83e8?source=rss-7700451cbec1------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a8f6e83e8</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Paul Núñez]]></dc:creator>
            <pubDate>Mon, 03 Jul 2017 07:36:04 GMT</pubDate>
            <atom:updated>2017-07-03T07:36:04.807Z</atom:updated>
            <content:encoded><![CDATA[<p>With Kotlin came a lot of new concepts for the Android programming world and with them new possibilities for doing the same things on an easier way. One of those new concepts are Sealed classes that are, as said by Antonio Leiva <a href="https://antonioleiva.com/sealed-classes-kotlin/">in his post</a>, enums with super-powers.</p><h3><strong>Enums with super-powers?</strong></h3><p>As you may know, enums can only have one object per type, while in the Sealed classes we can have several objects of the same class. What does this mean? let’s see the difference in the next example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOnnZ3Jefv1uEPb8svCDdw.png" /><figcaption>Difference declaring Enums and Sealed classes.</figcaption></figure><p>As you can see, Sealed classes help us set different behavior for each subclass as we can pass in the parameters we need.</p><h3><strong>But how can this be better for handling multiple click listeners?</strong></h3><p>Imagine you have a RecyclerView Viewholder, that has many views on a layout that can be clicked, something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*FNd0cwdZvfNk5DOCK0IF1Q.png" /><figcaption>Update layout used in the following examples.</figcaption></figure><p>You could opt to create a normal interface with a method for each single view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*7Uy5cVeUfxZIW2fjp5bceA.png" /><figcaption>Updates layout listeners implemented with an interface.</figcaption></figure><p>Pass an instance to your adapter and then implement all the methods on your View. And this is totally fine! But each time you need to add a new method or change a method signature on the interface you’ll have to implement or change the signature on your View. And this is not ideal:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkOxPv0LTgbaR8hLsKuFrQ.png" /><figcaption>View implementing the Update layout listeners from the interface.</figcaption></figure><p>Another way is that if your click interactions are simple, you could use enums, but this is not a good idea, as said in a <a href="https://www.youtube.com/watch?v=Hzs6OBcvNQE">performance pattern video</a>, <strong>we should avoid Enums</strong>.</p><h3><strong>So what do we have left? Sealed classes to the rescue!</strong></h3><p>The same interface can be changed to the following class, and create a simpler interface to handle all the listeners:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XjyeH8IUaGgALn3HrAXcBw.png" /><figcaption>Sealed class implementation for the Updates Layout.</figcaption></figure><p>But now in your View, the implementation goes a lot simpler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KiQMN0DFEnHkqC6GF-WeMA.png" /><figcaption>Sealed class listener implemented in only one method on the View.</figcaption></figure><p>Now you can add new methods, change the signature without too much effort and have all the code for the listeners encapsulated in one place, which is great!</p><p>Hope you enjoyed this post, you can follow me on twitter <a href="http://twitter.com/paulnunezm">@paulnunezm</a> where I usually tweet about Android Dev. And let please let me know what you think in the comment section bellow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a8f6e83e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with RecyclerView and multiple view types]]></title>
            <link>https://medium.com/@paulnunezm/working-with-recyclerview-and-multiple-view-types-bb1e7dfc6993?source=rss-7700451cbec1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb1e7dfc6993</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Paul Núñez]]></dc:creator>
            <pubDate>Sat, 13 May 2017 19:22:44 GMT</pubDate>
            <atom:updated>2017-05-13T19:22:44.238Z</atom:updated>
            <content:encoded><![CDATA[<p>Applications that contains different views in the same list are really common (i.e: Twitter, Goodreads, New York Times…) and we should know how to create them with ease.</p><p>In this post is assumed that you understand the basics of creating a list using RecyclerViews. You should also read, if you haven’t, a great post by <a href="https://medium.com/u/4c3e591d8822">Jon F Hancock</a>, “<a href="https://jonfhancock.com/your-viewholders-are-dumb-make-em-not-dumb-82e6f73f630c"><em>Your ViewHolders are Dumb. Make ’em Not Dumb</em></a><em>” a good practice implemented in this post.</em></p><p>The code examples are written in Kotlin to keep it short, but as this language is really readable, this shouldn’t be an issue for the reader.</p><h4>First things first: The model</h4><p>We have to define our model classes, for this example, we are going to have a list that contains multiple updates feeds from our friends, each one with a different view. And for this we need a base Update class from which all the others update types are going to inherit and an User class from the user performing the update.</p><p>The User class (and yes, that’s all you need for defining a class in Kotlin):</p><pre>data class User(<br> var id: String,<br> var name: String,<br> var imageUrl: String,<br> var profileUrl: String)</pre><p>The Update classes:</p><pre>abstract class Update(<br>        val updateType: String,<br>        val updateUser: User,<br>        val updateTime: String) {<br><br>    class TYPE {<br>        companion object {<br>            val NEW_FRIEND = &quot;friend&quot;<br>            val COMMENT = &quot;comment&quot;<br>            val READ_STATUS = &quot;readstatus&quot;<br>            val USER_STATUS = &quot;userstatus&quot;<br>            val REVIEW = &quot;review&quot;<br>        }<br>    }<br>}</pre><pre>data class ReviewUpdate(<br>        val user: User,<br>        val updatedAt: String,<br>        val rating: String,<br>        val book: Book<br>) : Update(Update.TYPE.REVIEW, user, updatedAt)</pre><pre>data class NewFriendUpdate( <br>        val user: User,<br>        val updatedAt: String,<br>        val newFriendImageUrl: String,<br>        val newFriendName: String<br>) : Update(Update.TYPE.NEW_FRIEND, user, updatedAt)</pre><p>In our abstract Update class we have an inner TYPE class with various constants, this will let us know what kind of update we are receiving at the moment. That string constant is passed with the corresponding type to the Update super constructor each time we extended it:</p><pre>: Update(Update.TYPE.NEW_FRIEND, user, updatedAt)</pre><h4>Creating our Updates Adapter</h4><p>Normally when we create our custom adapter we specify to the parent adapter a custom view holder that it has to use, like this:</p><pre>RecyclerView.Adapter&lt;MyCustomViewHolder&gt;</pre><p>Our custom view holder will always extend<em> RecyclerView.ViewHolder. </em>But as we will be working with multiple view holder classes we have to use the parent class abstraction.</p><pre>RecyclerView.Adapter&lt;<em>RecyclerView.ViewHolder</em>&gt;</pre><p>I will show you the final implementation and explain each step below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e80d30ff6ee8f3911a53e828afe594d/href">https://medium.com/media/5e80d30ff6ee8f3911a53e828afe594d/href</a></iframe><ul><li>The <strong>companion object: </strong>is the way that we create constants in Kotlin. These two constants are types of views the adapter is going to handle. These are used to know which layout are we going to inflate and which view holder is going to be returned in the <em>onCreateViewHolder.</em></li><li><strong>getItembyType: </strong>this returns the view type of the update item at a position. Here we use a <em>when </em>(Kotlin’s switch with super powers) to check the Update type and return the corresponding type constant.</li><li><strong>onCreateViewHolder: </strong>as you know this is were we inflate our views and return our <em>ViewHolder</em> so the <em>RecyclerView </em>can later put it on screen. In this case, we only need to check which view type we are receiving and return the correct custom <em>ViewHolder.</em></li><li><strong>onBindViewHolder: </strong>here we just send the update item from the <em>updateList </em>to the view holder. Using a <em>bindView </em>method implemented on each <em>ViewHolder</em>, more on this in the next section.</li></ul><h4>Creating our custom ViewHolders</h4><p>To be able to keep things easy and clean, we are going to create a <em>UpdateViewHolder</em> interface that all our custom <em>ViewHolders</em> must implement. This way we can guarantee the same behavior between different <em>ViewHolder </em>classes.</p><p>As said before, in the <em>onBindViewHolder </em>method, we are calling <em>bindView </em>in the <em>ViewHolders</em> after being cast to <em>UpdateViewHolder, </em>because we should always depend on abstraction and not concrete implementations ;). In this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8272bee15cfb9bac282120b2b56d0506/href">https://medium.com/media/8272bee15cfb9bac282120b2b56d0506/href</a></iframe><p>This provides an easy way to handle multiple view types with <em>RecyclerViews. </em>There are many ways to tackle this, one really cool one is explained by <a href="https://medium.com/u/45b3dc97bb15">Juan Ignacio Saravia</a> using <a href="https://medium.com/@juanchosaravia/keddit-part-4-recyclerview-delegate-adapters-data-classes-with-kotlin-9248f44327f7">Delegate Adapters</a>, you should also check that out!</p><h4><strong>Conclusion</strong></h4><p>RecyclerView is a very powerful widget, and understanding how we can use it can save us a lot of time. I know that getting your hands on new things can be challenging for someone new, and that’s why I wanted to talk about this.</p><p>Hope you enjoyed this post, you can follow me on twitter <a href="https://twitter.com/paulnunezm">@paulnunezm</a> and let me know what you think there.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb1e7dfc6993" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>