<?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[FAcademy - Medium]]></title>
        <description><![CDATA[If you only do what you can do, you will never be more than you are — Master Shifu - Medium]]></description>
        <link>https://medium.com/facademy?source=rss----e786222d210f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>FAcademy - Medium</title>
            <link>https://medium.com/facademy?source=rss----e786222d210f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:53:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/facademy" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Animated Custom View — Driven by tests! — Part 1]]></title>
            <link>https://medium.com/facademy/animated-custom-view-driven-by-tests-5f082190acd6?source=rss----e786222d210f---4</link>
            <guid isPermaLink="false">https://medium.com/p/5f082190acd6</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[custom-views]]></category>
            <category><![CDATA[custom-view-animation]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <dc:creator><![CDATA[Maciej Najbar]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 20:21:46 GMT</pubDate>
            <atom:updated>2017-02-17T05:11:32.417Z</atom:updated>
            <content:encoded><![CDATA[<p>Edit: I’ve received a feedback about this article that it’s too long for a single article and it should be divided into parts. Also I would like to thank a lot <a href="https://medium.com/u/de3b4c9e3479">Kamil Burczyk</a> who studied this story thoroughly and pointed out few very interesting improvements. This story may be extended with future steps for a final view, so stay tuned.</p><p>Creating Custom Views in Android is probably the most common phrase searched in Google. Recently it’s louder and louder about Test Driven Development approach in Android development. Why won’t we join these two topics together and go step-by-step while creating a custom view driven by tests.</p><p>Not long time ago I needed to create some „cool” way of presenting balance in a wallet. I figured out that it will probably be the best chance to introduce it as custom view.</p><p>I work for <a href="https://www.grandparade.co.uk/">Grand Parade</a> (<a href="https://www.williamhill.com/">William Hill</a>) as Android Developer and my direct leader is David Marin (who used to work for Shazam). He doesn’t let feature branches be merged to master if tests don’t cover at least 80% of the code.</p><p>This guy was mentoring me to dive into TDD. I found completely no practical tutorials on the Internet which would show more complicated examples than e.g. email verifier. Which is good example, but definitely too easy to see that process in action.</p><p>I decided to present of what I’ve learned so far using Test Driven Development on real example. It’s not going to show the full view, because while writing this article it turned out that that I had written 30 pages just to show TDD in action for a loading view.</p><p>You can find the code here: <a href="https://github.com/macieknajbar/AnimatedCustomViewTDD">https://github.com/macieknajbar/AnimatedCustomViewTDD</a></p><p><strong>Are you ready?</strong></p><p>First of all, we need to have a plan of what we want to achieve. So we need to have and idea of how something should look like and a TO-DO list of steps.</p><p>Bear in mind I’m using Android Studio on Mac OS. Shortcuts may differ on different software.</p><p><strong>Idea</strong></p><p>Let’s have a look at the view I will present in this tutorial:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*-OobQmympiQHe5NZCO3OMA.gif" /></figure><p><strong>TO-DO:</strong></p><ul><li><strong>Extend View</strong></li><li><strong>Set fixed size</strong></li><li><strong>Set background to show view’s area</strong></li><li><strong>Draw a dot</strong></li><li><strong>Animate and show FPS rate</strong></li><li><strong>Cut FPS to at most 60 FPS (optional)</strong></li><li><strong>Move a dot on sinusoidal path</strong></li><li><strong>Make sure dot jumps only up</strong></li><li><strong>Add other 2 dots so it’s 3 shown</strong></li><li><strong>Add time offset so they bounce independently</strong></li></ul><p><strong>Extend View</strong></p><p>Start new Android project with an empty Activity (for simplicity of this tutorial leave Activity’s name MainActivity and xml’s name activity_main.xml).</p><p>Create a new Java class — LoadingView — as I did. Extend View class from Android SDK.</p><pre>public class LoadingView extends View {</pre><pre>  public LoadingView(Context context, AttributeSet attrs) {</pre><pre>    super(context, attrs);</pre><pre>  }</pre><pre>}</pre><p><strong>Set fixed size</strong></p><p>I always prefer to use dp units instead of pixels. To do that we need a conversion method.</p><p>Let’s start Test Driven Development.</p><p>Before I start I want to say, that we’re not going to test LoadingView itself, but we will use tested code inside.</p><p>Let’s create a new class then — LoadingComputations.</p><pre>public class LoadingComputations {</pre><pre>}</pre><p>ALT+ENTER on class name and click Create test.</p><p>Confirm and make sure it goes to <strong>/test/</strong> folder. Initialize test class:</p><pre>import org.junit.Before;</pre><pre>public class LoadingComputationsTest {</pre><pre>  private LoadingComputations loadingComputations;</pre><pre>  @Before public void setUp() {</pre><pre>    loadingComputations = new LoadingComputations();</pre><pre>  }</pre><pre>}</pre><p>Our first test class. We’re good to go!</p><p>Start with defining first test:</p><pre>@Test public void checksComputerAbilityToMultiply() {<br>}</pre><p>If we run this test now, it will pass — it’s empty it checks nothing, if something is not false, then it’s true. But Test Driven Development tells us that:</p><blockquote>Defined test must fail first and we must make it green by the power of code.</blockquote><p>Let’s add a body:</p><pre>@Test public void checksComputerAbilityToMultiply() {</pre><pre>  Assert.assertEquals(2.5f, loadingComputations.dpToPx(1), 0.001);</pre><pre>}</pre><p>ALT+ENTER on highlighted missing method and click Create method ‚dpToPx’. You may notice <strong>0.001</strong> value which is an accuracy against float value.</p><p>This should result of code in LoadingComputation’s class, similar to this:</p><pre>float dpToPx(int size) {<br>  return 0;<br>}</pre><p>Run the test and witness its failure!</p><p>YES!</p><pre><em>java.lang.AssertionError:</em></pre><pre><em>Expected :2.5</em></pre><pre><em>Actual :0.0</em></pre><p>Go back to code and change method ‚dpToPx’ to:</p><pre>float dpToPx(int size) {<br>  return 2.5f;<br>}</pre><p>I know you started to swear right now — I did that too. I was turning into red, because I thought David was messing around with me. I wanted to shut down the computer or else he treats me with respect.</p><p>He just said „it’s TDD man”. I thank him for that.</p><p>Ok.. Be patient and we’ll go to the end. So let’s run the test and check if it’s green.</p><p>Yes — it is… surprising.</p><p>Create another test and make sure this works as expected:</p><pre>@Test public void doubleCheckConversionIsCorrect() {</pre><pre>  Assert.assertEquals(7.5f, loadingComputations.dpToPx(3), 0.001);</pre><pre>}</pre><p>Uff.. It’s not magic after all. Our code is wack! We need to fix it.</p><p>Now we can change definition of our method:</p><pre>float dpToPx(int size) {</pre><pre>  return size * 2.5f;</pre><pre>}</pre><p>Run entire test class and watch the whole test case turning into green. Pretty amazing seeing your code passing tests — I hope you feel the same way.</p><p>But wait a minute.. Something’s not right. What’s that magic number <strong>2.5f</strong>? This should be device’s density. What if density is 2.0f or 3.0f? Will our code still work as expected?</p><p>Let’s find out:</p><pre>@Test public void convertForDensityEqual3() {</pre><pre>  Assert.assertEquals(9.f, loadingComputations.dpToPx(3), 0.001);</pre><pre>}</pre><p>Run tests.</p><p>Crap! — Failed.</p><p>What to do then? We need to make sure that our code works fine on any density.</p><p>We need to create a dependency. Which means that our class LoadingComputation will depend on some external value.</p><p>Let’s do it. In test class write float value as a param in LoadingComputation constructor.</p><pre>@Before public void setUp() {</pre><pre>  loadingComputations = new LoadingComputations(2.5f);</pre><pre>}</pre><p>ALT+ENTER and click Create constructor.</p><p>This will result with the code similar to mine:</p><pre>public LoadingComputations(float density) {</pre><pre>}</pre><p>ALT+ENTER on density and click Create field for parameter ‚density’.</p><pre>private float density;</pre><pre>public LoadingComputations(float density) {</pre><pre>  this.density = density;</pre><pre>}</pre><p>Pretty amazing how Android Studio writes the code for us just by using ALT+ENTER shortcut.</p><p>Let’s change our method now:</p><pre>float dpToPx(int size) {</pre><pre>  return size * density;</pre><pre>}</pre><p>And run the test again.</p><p>Ok — at least we didn’t break those previously working, but still the newest one is failing.</p><p>We need to create a new instance of LoadingComputations with different density, which would mean refactor on test side. Let’s remove @Before setUp method body and paste initialization in separate test cases, since they will differ.</p><pre>private LoadingComputations loadingComputations;</pre><pre>@Test public void checksComputerAbilityToMultiply() {</pre><pre>  loadingComputations = new LoadingComputations(2.5f);</pre><pre>  Assert.assertEquals(2.5f, loadingComputations.dpToPx(1), 0.001);</pre><pre>}</pre><pre>@Test public void doubleCheckConversionIsCorrect() {</pre><pre>  loadingComputations = new LoadingComputations(2.5f);</pre><pre>  Assert.assertEquals(7.5f, loadingComputations.dpToPx(3), 0.001);</pre><pre>}</pre><pre>@Test public void convertForDensityEqual3() {</pre><pre>  loadingComputations = new LoadingComputations(3.f);</pre><pre>  Assert.assertEquals(9.f, loadingComputations.dpToPx(3), 0.001);</pre><pre>}</pre><p>Run the test class and watch.</p><p>FINALLY! All tests pass.</p><p>Now we’re sure that our method returns correct result. Which means that we can finally set a fixed size of our view with using our fantastic converter.</p><p>We go to LoadingView class and create an object of our LoadingComputation inside.</p><pre>public class LoadingView extends View {</pre><pre>  private LoadingComputations loadingComputations;</pre><pre>  public LoadingView(Context context, AttributeSet attrs) {</pre><pre>    super(context, attrs);</pre><pre>    loadingComputations =</pre><pre>    new LoadingComputations(<br>              getResources().getDisplayMetrics().density);</pre><pre>  }</pre><pre>}</pre><p>Override view’s measure method, and set fixed size of 100x100 dp.</p><pre>@Override<br>protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {<br>  setMeasuredDimension(<br>      (int) loadingComputations.dpToPx(100), <br>      (int) loadingComputations.dpToPx(100));<br>}</pre><p>We’ll need our method dpToPx to return float (because drawing figures on canvas require floats), so let’s cast results to int.</p><p><strong>Set background to show view’s area</strong></p><p>Let’s put our view into MainActivity’s layout and set background color so we can see our view’s size. In activity_main.xml file insert view:</p><pre>&lt;com.example.customview.LoadingView<br>    android:background=”#FFEFEFEF”<br>    android:layout_width=”wrap_content”<br>    android:layout_height=”wrap_content” /&gt;</pre><p>layout_width and layout_height attributes are ignored for now, because we set fixed size 100x100dp for simplicity.</p><p><strong>Draw a dot</strong></p><p>Now we can start drawing. So first thing we have to do is to override onDraw method within our LoadingView.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>}</pre><p>Awesome. Our view now has its own drawing logic — which basically doesn’t do anything at all. Let’s change that and draw a dot in center of our view.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  canvas.drawCircle(<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(3), dotPaint);<br>}</pre><p>ALT+ENTER on dotPaint and click Create field ‚dotPaint’.</p><p>Go to activity_main.xml and click „build” on Preview section.</p><p>NullPointerException — that’s not always a bad sign. This gives us information that we’re moving forward. Ok.. we forgot to instantiate a dotPaint object. Go back to LoadingView and in constructor put that line:</p><pre>public LoadingView(Context context, AttributeSet attrs) {<br>  …<br>  dotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);<br>}</pre><p>Now we can go back to activity_main.xml and build our project again.</p><p>Success! We can see dot drawn. We also notice our dot default color is black. In my opinion we can change that too. Let’s add another line to constructor then:</p><pre>  …<br>  dotPaint.setColor(0xFFB0B0B0);<br>}</pre><p>We go to activity_main.xml, we build and… Ok, much better (or just better).</p><p>TDD is really a carve practice you make sure every time you make a step, that the result is what you expected to achieve.</p><p>Great! We finished another milestone in our process.</p><h3>Closure</h3><p>Let’s finish Part 1 here. Hope you enjoy it this far, but believe me, <a href="https://medium.com/@MaciejNajbar/animated-custom-view-driven-by-tests-part-2-edd4cbcf039c">Part 2</a> and <a href="https://medium.com/@MaciejNajbar/animated-custom-view-driven-by-tests-part-3-fb3a41c6b37c">Part 3</a> bring you much more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f082190acd6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/facademy/animated-custom-view-driven-by-tests-5f082190acd6">Animated Custom View — Driven by tests! — Part 1</a> was originally published in <a href="https://medium.com/facademy">FAcademy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Animated Custom View — Driven by tests! — Part 3]]></title>
            <link>https://medium.com/facademy/animated-custom-view-driven-by-tests-part-3-fb3a41c6b37c?source=rss----e786222d210f---4</link>
            <guid isPermaLink="false">https://medium.com/p/fb3a41c6b37c</guid>
            <category><![CDATA[custom-view-animation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[custom-views]]></category>
            <dc:creator><![CDATA[Maciej Najbar]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 18:29:25 GMT</pubDate>
            <atom:updated>2017-02-14T21:35:27.407Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 3 seems to be a long one. But it’s worth it — I promise. In this part we’ll dive more into virtual presentation. If you want to finish this part faster, read the note “optional” under next header.</p><p>So, let’s remind ourselves what we’ve accomplished so far:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*-OobQmympiQHe5NZCO3OMA.gif" /></figure><ul><li>Extend View</li><li>Set fixed size</li><li>Set background to show view’s area</li><li>Draw a dot</li><li>Animate and show FPS rate</li><li><strong>Cut FPS to at most 60 FPS (optional)</strong></li><li><strong>Move a dot on sinusoidal path</strong></li><li><strong>Make sure dot jumps only up</strong></li><li><strong>Add other 2 dots so it’s 3 shown</strong></li><li><strong>Add time offset so they bounce independently</strong></li></ul><p><strong>Cut FPS to at most 60 FPS (optional)</strong></p><blockquote>Note:<br>If you’d like to skip this part — because you’re not interested or you want to return to it later — just when you encounter method “framesManager.canGo()” make sure its implementation always returns <strong>true</strong>.</blockquote><blockquote>Go directly to headline “<strong>Move a dot on sinusoidal path”</strong> — from here it should be 5mins reading.</blockquote><p>Lots of wise (gaming) articles claim that 60 FPS gives us the smoothest animation and it became a standard for animations. So why won’t we stick to this rule and draw at most 60 FPS.</p><p>We should understand now what exactly means Frames Per Second. It’s a number of drawn images within elapsed time and more precisely 1 second.</p><blockquote>60 FPS = 60frames / 1s = 60frames / 1000ms.</blockquote><p>So if we want to have 60 FPS, we need to calculate the time that is allowed for us to draw 1 frame.</p><blockquote>60 frames / 1s = 1frame / time</blockquote><blockquote>60 / 1s = 1 / time</blockquote><blockquote>60*time = 1s</blockquote><blockquote>time = 1s / 60 = 1000ms / 60 = 16.(6)ms</blockquote><p><strong>16.(6)ms!</strong> This is the time that we have to draw 1 frame!</p><p>So.. now we’re smarter with this information.</p><p>But what if we don’t need 60 Frames Per Second, maybe we just need 30.</p><p>Let’s do that, just for fun. 60 is perhaps what your device gets by default. So let’s do 30 FPS to see if that actually works as expected.</p><p>Create a test:</p><pre>@Test public void frameShouldBeSkipped() {<br>  framesManager.frame(); // Initialization frame (we need previous frame’s time)<br>  framesManager.frame();<br>  assertEquals(false, framesManager.canGo());<br>}</pre><p>ALT+ENTER on canGo and Create method ‚canGo’.</p><p>You receive method implementation like this:</p><pre>public boolean canGo() {<br>  return false;<br>}</pre><p>When you run your test, it will pass. This means it’s a wrong test. Test at first should fail. So in that situation we have to return here true, like this:</p><pre>public boolean canGo() {<br>  return true;<br>}</pre><p>Run test and watch it burn.</p><p>We can start implementation. Let’s change that to false:</p><pre>public boolean canGo() {<br>  return false;<br>}</pre><p>Unfortuntely I’m not kidding. This will make our test pass and isn’t it something that we really want?</p><p>Having our tests pass, we can create another test — that is not a Happy Path:</p><pre>@Test public void frameCanBeDrawn() throws Exception {<br>  framesManager.frame(); // Initialization frame (we need previous frames’s time)<br>  Thread.sleep(100);<br>  framesManager.frame();<br>  Assert.assertEquals(true, framesManager.canGo());<br>}</pre><p>Run the tests, and it turns out that this one fails — classic.</p><p>So we go back to the code in FramesManager class and we change canGo implementation:</p><pre>public boolean canGo() {<br>  return timeFrame &gt; TIME_PER_FRAME;<br>}</pre><p>ALT+ENTER on timeFrame and click Create field ‚timeFrame’ — make sure its type is long.</p><p>ALT+ENTER on TIME_PER_FRAME and click Create content field ‚TIME_PER_FRAME’ — this one should be of type double. Like below:</p><pre>private static final double <em>TIME_PER_FRAME </em>= 1000 / 30;</pre><p>When we run our test we can see that nothing changed. It’s the fact that timeFrame is 0 and it’s never grater than 1000 / 30. We need to get the time between each two frames. I remember we already implemented this one.</p><p>Let’s look into our frame method:</p><pre>public void frame() {<br>  long currentFrame = System.currentTimeMillis();</pre><pre>timeSpan += <strong>currentFrame — lastFrame</strong>;<br>  if (timeSpan &gt; TimeUnit.SECONDS.toMillis(1)) {<br>    timeSpan = 0;<br>    fps = getFramesCount();<br>    frames = 0;<br>  }</pre><pre>frames++;<br>  lastFrame = currentFrame;<br>}</pre><p>There it is. Bolded. I knew we had it, but we used it for calculating the timeSpan (which is the period of 1s). We need to take it out for our timeFrame and we’ll add timeFrame to timeSpan. Sounds good!</p><pre>…<br>timeFrame = currentFrame — lastFrame;<br>timeSpan += timeFrame;<br>…</pre><p>Done.</p><p>Run tests.</p><p>Yaay! Tests claim it works correct. So do I then.</p><p>Now we can go to LoadingView and we can make use of our canGo method. So what we want to do? We want to draw only if canGo returns true. That’s why we refactor our drawing function and we have something like:</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  if (framesManager.canGo()) {<br>    canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.fps()), 0.f, fpsPaint.getTextSize(), fpsPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50),<br>        loadingComputations.dpToPx(50),<br>        loadingComputations.dpToPx(3), dotPaint);<br>  }</pre><pre>framesManager.frame();<br>  invalidate();<br>}</pre><p>We need to leave invalidate method outside of if block, because otherwise onDraw would finish its run without forcing our view to refresh.</p><p>We also leave frame method outside, since it calculates our time between two frames, which is needed for canGo method to determine if it can draw or not.</p><p>Let’s run our App on physical device.</p><p>Ok… Now it draws nothing. Nevertheless tests pass, we don’t get what we wanted. This proves that TDD approach isn’t god like, but definitely reduces the chances of failure and if we break something we’ll know it.</p><p>We need to create another test then. Something that will go the buggy path. Let’s think a little…</p><p>So what we know so far.</p><p>1. We know from our tests, that if time between last and current frame is less than 1000 / 30, then it doesn’t allow to draw.</p><p>2. We also know that if time between last and current frame is more than 1000 / 30, then it does allow to draw.</p><p>Where is the problem then?</p><p>View draws frames much faster than 1000 / 30[ms], let’s add a test that will cover this scenario:</p><pre>@Test public void doubleCheckIfFrameCanBeDrawn() throws Exception {<br>  framesManager.frame(); // Initialization frame (we need previous frames’s time)<br>  Thread.sleep(20);<br>  framesManager.frame();<br>  Thread.sleep(20);<br>  framesManager.frame();<br>  Assert.assertEquals(true, framesManager.canGo());<br>}</pre><p>Uff, it failed. That’s a good sign — because we just found a bug that we can fix forever.</p><p>It resets our timeFrame each turn. The common sense tells us that yes, first frame shouldn’t be drawn, but the second frame is far later than 33ms (because over 40ms) so it definitely should.</p><p>Let’s go to our code and change the logic of frame method to fix our test.</p><pre>public void frame() {<br>  long currentFrame = System.currentTimeMillis();</pre><pre><strong>long timeStep = currentFrame — lastFrame;<br>  timeFrame += timeStep;<br>  timeSpan += timeStep;<br>  </strong>if (timeSpan &gt; TimeUnit.SECONDS.toMillis(1)) {<br>    timeSpan = 0;<br>    fps = getFramesCount();<br>    frames = 0;<br>  }</pre><pre><strong>if (canGo()) {<br>    </strong>frames++;<br>    <strong>timeFrame = 0;<br>  }</strong></pre><pre>lastFrame = currentFrame;<br>}</pre><p>Look at the bolded parts. I sum the time between frames, but I also check if I should increment frames and when I do it, I reset timeFrame variable.</p><p>Let’s run our tests.</p><p>OMG.. We broke tests a lot. Due to the fact we are depending on time now, we need to change our tests that fail, since they are not time aware now.</p><p>We will now use some TDD practice that helps us play with time. Ladies and Gentlemen let me introduce you the TimestampProvider. It looks like following:</p><pre>public interface TimestampProvider {<br>  long timestamp();<br>}</pre><p>Create this interface.</p><p>We will also need its implementation, so let’s create a class that implements our layer of abstraction, and call it RealTimestampProvider. This will return our current time:</p><pre>public class RealTimestampProvider implements TimestampProvider {<br>  @Override<br>  public long timestamp() {<br>    return 0;<br>  }<br>}</pre><p>ALT+ENTER on RealTimestampProvider class and click Create Test. Again, make sure it’s /test/ folder in the path.</p><p>So as always we start with:</p><pre>@Before public void setUp() {<br>  realTimestampProvider = new RealTimestampProvider();<br>}</pre><p>ALT+ENTER on realTimestampProvider and click Create field ‚realTimestampProvider’.</p><p>We can create our test:</p><pre>@Test public void providerGivesUsCurrentTime() {<br>  long now = System.currentTimeMillis();<br>  Assert.assertEquals(now, realTimestampProvider.timestamp());<br>}</pre><p>We run it, and it fails. Which means that we can go to the code and change it to what we meant.</p><pre>@Override<br>public long timestamp() {<br>  return System.currentTimeMillis();<br>}</pre><p>This time it’s about time, so we can’t really guess the long number because it changes too quickly, so we won’t need to double check it works. We just go and put „currentTimeMillis”.</p><p>Let’s run our test.</p><p>Does it pass? Does it fail? I don’t know, sometimes it passes and sometimes it fails. This is called „<a href="https://github.com/nodejs/node/wiki/Flaky-tests">Flaky test</a>” because test should always pass or should always fail. When it’s half way there it’s not a reliable test.</p><p>It depends on how quickly time elapsed between one timestamp call and the next one. Let’s be more precise and let’s put nanoTime into test:</p><pre>@Test public void providerGivesUsCurrentTime() {<br>  long now = System.nanoTime();<br>  Assert.assertEquals(now, realTimestampProvider.timestamp());<br>}</pre><p>And into timestamp method:</p><pre>@Override<br>public long timestamp() {<br>  return System.nanoTime();<br>}</pre><p>Now we can see that our test fails every time. So we need to check if the time is correct for some delta time.</p><p>Let’s make sure that our delta time is not grater than 2ms. If in the application we have 2ms of error than I can live with that.</p><p>So let’s fix our test first:</p><pre>@Test public void providerGivesUsCurrentTime() {<br>  long now = System.nanoTime();<br>  Assert.assertTrue(“Timestamp fits 2ms window”, realTimestampProvider.timestamp() — now &lt; TimeUnit.MILLISECONDS.toMillis(2));<br>}</pre><p>We run our test now and boom! It passes every time. Ok, so if something works for nano seconds it will definitely work for mili seconds. Let’s change our implementation to millis again. First in tests:</p><pre>@Test public void providerGivesUsCurrentTime() {<br>  long now = System.currentTimeMillis();<br>  Assert.assertTrue(“Timestamp fits 2ms window”, realTimestampProvider.timestamp() — now &lt; TimeUnit.MILLISECONDS.toMillis(2));<br>}</pre><p>And in RealTimestampProvider:</p><pre>@Override<br>public long timestamp() {<br>  return System.currentTimeMillis();<br>}</pre><p>Let’s run our tests at least 10 times and see results.</p><p>Works for me! We can start using our reliable timestamp provider.</p><p>But when it comes to tests we would like to have a possibility to cheat a little with time. We would like to have control, to add time if we need it and how much we need without waiting for it.</p><p>For these occasions we have to create a new timestamp provider class — fake. Let’s create a new class FakeTimestampProvider that implements TimestampProvider interface.</p><pre>public class FakeTimestampProvider implements TimestampProvider {<br>  @Override<br>  public long timestamp() {<br>    return 0;<br>  }<br>}</pre><p>ALT+ENTER on FakeTimestampProvider class name and click Create test.</p><pre>@Before public void setUp() {<br>  fakeTimestampProvider = new FakeTimestampProvider();<br>}</pre><p>ALT+ENTER on fakeTimestampProvider and click Create field ‚fakeTimestampProvider’.</p><p>Now test:</p><pre>@Test public void timestampReturnsOneSecond() {<br>  long second = TimeUnit.SECONDS.toMillis(1);<br>  fakeTimestampProvider.add(second);<br>  Assert.assertEquals(second, fakeTimestampProvider.timestamp());<br>}</pre><p>ALT+ENTER on add and click Create method ‚add’ — in FakeTimestampProvider, because it will only be this class’s feature to manipulate the time.</p><p>Let’s run our test… Failed. Good — I’m really surprised that I’m glad that my tests fail.</p><p>Let’s go back to the implementation of our Fake class.</p><pre>public class FakeTimestampProvider implements TimestampProvider {<br>  @Override<br>  public long timestamp() {<br>    return 1000;<br>  }</pre><pre>public void add(long millis) {<br>  }<br>}</pre><p>Passed.</p><p>But let’s be sure. New test:</p><pre>@Test public void timestampReturnsElapsedTime() {<br>  fakeTimestampProvider.add(1000);<br>  fakeTimestampProvider.add(500);<br>  Assert.assertEquals(1500, fakeTimestampProvider.timestamp());<br>}</pre><p>Ok. When we run it we see that it failed. It returned one second when we specifically provided 1s and 500ms elapsed. We gotta fix it if we want to use it after all.</p><p>Let’s go back to the code and change it to this final version:</p><pre>public class FakeTimestampProvider implements TimestampProvider {<br>  private long timeInMillis;</pre><pre>@Override<br>  public long timestamp() {<br>    return timeInMillis;<br>  }</pre><pre>public void add(long millis) {<br>    timeInMillis += millis;<br>  }<br>}</pre><p>Run the tests. They both passed, which means that it supposed to work.</p><p>Ok, now we can use our timestamp provider in our test cases. Let’s move back to FramesManagerTest class and the first thing we need to do is to pass dependency to FramesManager. It will depend on TimestampProvider interface in tests and in real application. So let’s do this. In setUp method change the code to following:</p><pre>@Before public void setUp() {<br>  framesManager = new FramesManager(fakeTimestampProvider);<br>}</pre><p>ALT+ENTER on fakeTimestampProvider and click Create field ‚fakeTimestampProvider’ — with type of our FakeTimestampProvider.</p><p>Again ALT+ENTER on fakeTimestampProvider in FramesManager constructor and click Create constructor.</p><p>The constructor should use TimestampProvider interface not our class implementation (<a href="https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)">SOLID</a> rules):</p><pre>public FramesManager(TimestampProvider timestampProvider) {<br>}</pre><p>ALT+ENTER on timestampProvider and click Create field for parameter ‚timestampProvider’. The result should be like this:</p><pre>private TimestampProvider timestampProvider;</pre><p>Let’s run our tests of FramesUpdaterTest class and see if it helped.</p><p>So.. While compiling tests, my LoadingView cried about FramesManager parameter. Fortunately we have implementation of RealTimestampProvider, so let’s pass it there. This provider is meant to be used by real time view.</p><pre>…<br>framesManager = new FramesManager(new RealTimestampProvider());<br>…</pre><p>And run tests for FramesUpdaterTest class again. Ok, so it didn’t help at all… Right, we didn’t use it!</p><p>Ok, so wherever we used System.currentTimeMillis, we want to use our provider now. Which is here:</p><pre>public void frame() {<br>  long currentFrame = timestampProvider.timestamp();<br>  …</pre><p>Let’s run again. All failed… After looking into logs we can see it’s NullPointerException. Uff.. We just need to create an instance of our FakeTimestampProvider in tests:</p><pre>@Before public void setUp() {<br>  fakeTimestampProvider = new FakeTimestampProvider();<br>  framesManager = new FramesManager(fakeTimestampProvider);<br>}</pre><p>Run tests… It’s even worse than it used to be before we used that timestamp provider. But it’s a step forward. Believe me. I also had doubts when I was told by David that I’ll understand it one day. It’s like a Rubic’s cube. When you start breaking it you want to move back to the state you thought was closer to the end. Unfortunately without breaking it, we will not go further. So let’s start fixing what we broke. We need to control the time of frames.</p><p>Let’s go test by test. The first one is „framesManagerMonitorsFramesProgress” timestamp provider needs to tell it what time it is:</p><pre>@Test public void framesManagerMonitorsFramesProgress() {<br>  framesManager.frame();<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>I added one TIME_PER_FRAME value + 1 ms to make sure it goes to the next frame.</p><p>But it fails. Of course it fails, because it should have initialization frame to make sure we have last frame’s timestamp so the subtraction of current frame and last frame returns positive result. So let’s correct our test:</p><pre>@Test public void framesManagerMonitorsFramesProgress() {<br>  framesManager.frame(); // Initialization frame<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>Run tests………… Passed! Great. So let’s do next one:</p><pre>@Test public void makeSureFramesManagerIsAwareOfFramesPassed() {<br>  framesManager.frame(); // Initialization frame<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  Assert.assertEquals(3, framesManager.getFramesCount());<br>}</pre><p>Passed!</p><p>It’s time to present the next rule of TDD.</p><blockquote>If something repeats at least three times, it should be simplified to some common code.</blockquote><p>I can see few things so far (based on those two tests above).</p><p>1. Initialization frame — we can move it to setUp method. This method runs before each test anyway, so why we have to remember of initialization frame in our test cases if this one call can do that.</p><p>2. 1000 / 30 + 1 — this can become a static final field</p><p>3. Repetition of add and frame. Let’s close it in a loop.</p><p>1. Initialization frame:</p><pre>@Before public void setUp() {<br>  fakeTimestampProvider = new FakeTimestampProvider();<br>  framesManager = new FramesManager(fakeTimestampProvider);<br>  framesManager.frame(); // Initialization frame<br>}<br>…<br>@Test public void framesManagerMonitorsFramesProgress() {<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}<br>…<br>@Test public void makeSureFramesManagerIsAwareOfFramesPassed() {<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  fakeTimestampProvider.add(1000 / 30 + 1);<br>  framesManager.frame();<br>  Assert.assertEquals(3, framesManager.getFramesCount());<br>}</pre><p>2. 1000 / 30 + 1</p><pre>private static final long TIME_PER_FRAME = 1000 / 30 + 1;<br>…<br>fakeTimestampProvider.add(TIME_PER_FRAME);</pre><p>3. Loop</p><pre>@Test public void makeSureFramesManagerIsAwareOfFramesPassed() {<br>  for (int i = 0; i &lt; 3; ++i) {<br>    fakeTimestampProvider.add(TIME_PER_FRAME);<br>    framesManager.frame();<br>  }<br>  Assert.assertEquals(3, framesManager.getFramesCount());<br>}</pre><p>Much better.. Now my eyes stopped bleeding.</p><p>Let’s continue with our great improvements:</p><pre>@Test public void resetsFramesCountAfterOneSecond() {<br>  for (int i = 0; i &lt; 3; ++i) {<br>    fakeTimestampProvider.add(TIME_PER_FRAME);<br>    framesManager.frame();<br>  }</pre><pre>fakeTimestampProvider.add(1001);<br>  framesManager.frame();<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>Notice here that I removed Thread.sleep method, because I don’t rely on real time now, but on my fake timestamp provider instead. This also speeds up our tests, because we don’t need to wait 1s for our test to continue. We just tell our application that it’s 1s later when it elapsed in real 1ms. Isn’t that awesome?!</p><p>Next test:</p><pre>@Test public void resetsFramesCountsAfterOneSecondRepeatedly() {<br>  for (int i = 0; i &lt; 8; ++i) {<br>    fakeTimestampProvider.add(300);<br>    framesManager.frame();<br>  }<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>Passed again! Lightning mode!</p><p>Next test:</p><pre>@Test public void showsFramesPerSecond() throws Exception {<br>  for (int i = 0; i &lt; 3; ++i) {<br>    fakeTimestampProvider.add(TIME_PER_FRAME);<br>    framesManager.frame();<br>  }<br>  fakeTimestampProvider.add(1001);<br>  framesManager.frame();<br>  Assert.assertEquals(3, framesManager.fps());<br>}</pre><p>Passing again!</p><p>Next test:</p><pre>@Test public void showsCorrectFramesPerSecond() throws Exception {<br>  for (int i = 0; i &lt; 3; ++i) {<br>    fakeTimestampProvider.add(TIME_PER_FRAME);<br>    framesManager.frame();<br>  }</pre><pre>fakeTimestampProvider.add(1001);<br>  for (int i = 0; i &lt; 2; ++i) {<br>    fakeTimestampProvider.add(TIME_PER_FRAME);<br>    framesManager.frame();<br>  }</pre><pre>fakeTimestampProvider.add(1001);<br>  framesManager.frame();<br>  Assert.assertEquals(2, framesManager.fps());<br>}</pre><p>Passed!</p><p>Next test — this one passed, but we should change it anyway, to be using our current flow:</p><pre>@Test public void frameShouldBeSkipped() {<br>  fakeTimestampProvider.add(1);<br>  framesManager.frame();<br>  Assert.assertEquals(false, framesManager.canGo());<br>}</pre><p>This test actually with our current implementation of the code is useless. Because if frame cannot be drawn it passes, but also if the frame can be drawn it passes as well, because frame is drawn and value of timeFrame is reset to 0, which gives us again result that it can’t be drawn. But let’s leave it. Test are more like story teller of what we want to achieve but running tests it gives us information if we succeeded in delivery.</p><p>Next test:</p><pre>@Test public void frameCanBeDrawn() throws Exception {<br>  fakeTimestampProvider.add(100);<br>  framesManager.frame();<br>  Assert.assertEquals(true, framesManager.canGo());<br>}</pre><p>Crap.. it fails no matter what. This means that our current solution is not correct. We can’t let tests fail. We need to fix that. Let’s go back to the code then.</p><pre>public void frame() {<br>  <strong>if (canGo()) {<br>    timeFrame = 0;<br>  }</strong></pre><pre>long currentFrame = timestampProvider.timestamp();</pre><pre>long timeStep = currentFrame — lastFrame;<br>  timeFrame += timeStep;<br>  timeSpan += timeStep;<br>  if (timeSpan &gt; TimeUnit.SECONDS.toMillis(1)) {<br>    timeSpan = 0;<br>    fps = getFramesCount();<br>    frames = 0;<br>  }</pre><pre><strong>if (canGo()) {<br>    frames++;<br>  }</strong></pre><pre>lastFrame = currentFrame;<br>}</pre><p>I divided our condition into two. At the beginning I’m checking if I should reset the timeFrame. In the second I check if I should increment frames count.</p><p>Let’s check if we didn’t break previous test by that change by running all of them.</p><p>Fortunately all of them pass. Phew!</p><p>Last test!</p><pre>@Test public void doubleCheckIfFrameCanBeDrawn() throws Exception {<br>  for (int i = 0; i &lt; 2; ++i) {<br>    fakeTimestampProvider.add(20);<br>    framesManager.frame();<br>  }<br>  Assert.assertEquals(true, framesManager.canGo());<br>}</pre><p>Passed!</p><p>All tests pass again!</p><p>One giant leap for the programmer, one small step for mankind. But that’s us — programmers. Nobody knows what effort we put into making their lives easier.</p><p>Let’s run our Application on physical device one more time and let’s see if we made any progress.</p><p>Nooooo. Something doesn’t work as expected. It cuts values by half. When I set TIME_PER_FRAME to 1000 / 30 I get about ~22 FPS, when I set 1000 / 60, I get ~44 FPS</p><p>But the worst is that it scintillates..</p><p>I realized that we’re losing too much time in our calculations. If one time step between frame and a frame is 28ms, we get only every two frames.</p><ol><li>28[ms]</li><li>56[ms] — reset</li><li>28[ms]</li><li>56[ms] — reset</li></ol><p>But there is our precious time that we loose. Let’s create a test to prove it:</p><pre>@Test public void doesNotLooseTimeForTimeFrame() {<br>  for (int i = 0; i &lt; 3; ++i) {<br>    fakeTimestampProvider.add(TIME_PER_FRAME / 2 + TIME_PER_FRAME / 3);<br>    framesManager.frame();<br>  }<br>  Assert.assertEquals(2, framesManager.getFramesCount());<br>}</pre><p>Let’s make a change in the code:</p><pre>public void frame() {<br>  if (canGo()) {<br>    <strong>timeFrame %= TIME_PER_FRAME;<br>  </strong>}</pre><pre>long currentFrame = timestampProvider.timestamp();</pre><pre>long timeStep = currentFrame — lastFrame;<br>  timeFrame += timeStep;<br>  timeSpan += timeStep;<br>  if (timeSpan &gt; TimeUnit.SECONDS.toMillis(1)) {<br>    timeSpan = 0;<br>    fps = getFramesCount();<br>    frames = 0;<br>  }</pre><pre>if (canGo()) {<br>    frames++;<br>  }</pre><pre>lastFrame = currentFrame;<br>}</pre><p>Replace your method, run tests. All pass! Good — another good did!</p><p>But 30FPS scintillates too much. Let’s go back to 60 FPS. Change value of TIME_PER_FRAME to 1000 / 60 in FramesManager and FramesManagerTest.</p><p><strong>Move a dot on sinusoidal path</strong></p><p>Now we can move our dot.</p><p>First math.<br><a href="https://www.wolframalpha.com/input/?i=sin(x)">Sinusoid</a> has it’s period from 0–2π. Which means:</p><blockquote>sin(0) = sin(2π)</blockquote><p>Ok, so we need one more thing. Due to the fact we don’t monitor our time with π fractions we need to make sure we do so. We need to determine how long our animation must last. Let’s say 1s — I love 1s.</p><p>Ok. So if:</p><blockquote>1[s] = 2*π</blockquote><p>Then for our ’t’ that we know, because we will pass that (in ms):</p><p>t[ms] = X, where X is a sinus parameter</p><p>This gives us X * 1[s] = 2*π*t[ms]…</p><blockquote>X = 2*π*t[ms]/1000[ms] = 2*π*t / 1000</blockquote><p>Tests! Tests! Tests!</p><p>We need to make sure that our code will give us the correct result of the equation above. We can go back to our forgotten class LoadingComputationTest class and create a new test:</p><pre>@Test public void calculatesSinusoidResultBasedOnTime() {<br>  loadingComputations = new LoadingComputations(0.f);<br>  Assert.assertEquals(0., loadingComputations.verticalPosition(0), 0.002);<br>}</pre><p>ALT+ENTER on verticalPosition and click Create method ‚verticalPosition’.</p><pre>public double verticalPosition(long time) {<br>  return 1;<br>}</pre><p>Let’s return 1 to meet the expected failure of our test.</p><p>After our test watching failed we can change it back to 0 and be happy we made one test more to pass!</p><p>But it’s not over, we know we want to use our fantastic equation. So we need to create a new method that will check other parts of sinusoid and compare the results. We know value for:</p><blockquote>1. sin(π/6) = 1/2</blockquote><blockquote>2. sin(π/4) = √2 / 2</blockquote><blockquote>3. sin(π/2) = 1</blockquote><p>This would mean that time value would equal respectively:</p><blockquote>1. ~83ms</blockquote><blockquote>2. 125ms</blockquote><blockquote>3. 250ms</blockquote><p>Let’s put those numbers into our test by extending existing one. Unit test must check one thing, but it is one thing but couple of different parameters.</p><pre>@Test public void calculatesSinusoidResultBasedOnTime() {<br>  loadingComputations = new LoadingComputations(0.f);<br>  Assert.assertEquals(0., loadingComputations.verticalPosition(0), 0.002);</pre><pre>Assert.assertEquals(1./2, loadingComputations.verticalPosition(83), 0.002);</pre><pre>Assert.assertEquals(Math.sqrt(2)/2, loadingComputations.verticalPosition(125), 0.002);</pre><pre>Assert.assertEquals(1, loadingComputations.verticalPosition(250), 0.002);<br>}</pre><p>Ok, so after running we can see that it fails on our second assertion. Let’s fix that in the code.</p><p>We know that we want our equation to start playing the main role already. Change the code to:</p><pre>public double verticalPosition(long time) {<br>  double X = 2 * Math.PI * time / ANIMATION_LENGTH;<br>  return Math.sin(X);<br>}</pre><p>ALT+ENTER on ANIMATION_LENGTH and click Create constant field ANIMATION_LENGTH — with type of long and value 1000.</p><p>We can run tests!</p><p>Seems to work! Let’s put it into our LoadingView and see what happens.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  if (framesManager.canGo()) {<br>    canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.fps()), 0.f, fpsPaint.getTextSize(), fpsPaint);</pre><pre>canvas.drawCircle(<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(50) * (float)loadingComputations.verticalPosition(System.currentTimeMillis()),<br>      loadingComputations.dpToPx(3), dotPaint);<br>  }</pre><pre>framesManager.frame();<br>  invalidate();<br>}</pre><p>Run our application on physical device and see for yourself.</p><p><strong>Make sure dot jumps only up</strong></p><p>It animates! Not exactly what we expected! But isn’t that exciting?! Ok, so what we want, is to have it inside our view frame. We know that it jumps right now with value from -1 to 1, so when it’s 1 it is in the center of view, when it’s 0 it’s on top and when it’s -1 it’s totally out of scope.</p><p>We want our equation to return only values from 0 to 1. To do that, we need to modify our test:</p><pre>@Test public void calculatesSinusoidResultBasedOnTime() {<br>  loadingComputations = new LoadingComputations(0.f);</pre><pre>Assert.assertEquals(<strong>(0. + 1)/2</strong>, loadingComputations.verticalPosition(0), 0.002);</pre><pre>Assert.assertEquals(<strong>(1./2 + 1)/2</strong>, loadingComputations.verticalPosition(83), 0.002);</pre><pre>Assert.assertEquals(<strong>(Math.sqrt(2)/2 + 1)/2</strong>, loadingComputations.verticalPosition(125), 0.002);</pre><pre>Assert.assertEquals(<strong>(1 + 1)/2</strong>, loadingComputations.verticalPosition(250), 0.002);<br>}</pre><p>Because + 1 will give us values from 0 to 2 we need to also devide the whole result by 2.</p><p>Run the test. Test fails. Good.</p><p>Now back to the code. And we do the same:</p><pre>public double verticalPosition(long time) {<br>  double X = 2 * Math.PI * time / ANIMATION_LENGTH;<br>  return (Math.sin(X) + 1) / 2.;<br>}</pre><p>Run the App now. Ohh yeah! It’s animating within the frame!</p><p>But I don’t think that this should go this much up and down. Let’s cut its way to let’s say 20dp.</p><p>Go to LoadingView and and change onDraw method to:</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  if (framesManager.canGo()) {<br>    canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.fps()), 0.f, fpsPaint.getTextSize(), fpsPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50),<br>        loadingComputations.dpToPx(50) <strong>— loadingComputations.dpToPx(20)</strong> * (float)loadingComputations.verticalPosition(System.currentTimeMillis()),<br>        loadingComputations.dpToPx(3), dotPaint);<br>  }</pre><pre>framesManager.frame();<br>  invalidate();<br>}</pre><p>Subtracting pixels from base position moves dot up.</p><p>Looks better, doesn’t it?</p><p><strong>Add other 2 dots so it’s 3 shown</strong></p><p>We can add now two other dots. Let’s say they will be in a distance of 12dp from one another, this will give us a 6dp space between them (radius of one is 3dp and the other 3dp as well which gives us 6dp in total just for dots).</p><p>Expand our onDraw method by additional commands for drawing circles:</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  if (framesManager.canGo()) {<br>    canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.fps()), 0.f, fpsPaint.getTextSize(), fpsPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50)<strong> — loadingComputations.dpToPx(12)</strong>,<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(20) * (float)loadingComputations.verticalPosition(System.currentTimeMillis()),<br>        loadingComputations.dpToPx(3), dotPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50),<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(20) * (float)loadingComputations.verticalPosition(System.currentTimeMillis()),<br>        loadingComputations.dpToPx(3), dotPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50) <strong>+ loadingComputations.dpToPx(12)</strong>,<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(20) * (float)loadingComputations.verticalPosition(System.currentTimeMillis()),<br>        loadingComputations.dpToPx(3), dotPaint);<br>  }</pre><pre>framesManager.frame();<br>  invalidate();<br>}</pre><p>One on the left, one on the right and one in center.</p><p>Isn’t that pure joy seeing our code working that easily? Everything thanks to the testing!</p><p><strong>Add time offset so they bounce independently</strong></p><p>We would like to see them going independently though. We should definitely add offsets so their time is different for each one.</p><p>Ready! Tests! Go!</p><p>LoadingComputationsTest class and add test that will calculate sinusoid values but for time that offsets let’s say 125ms (for simplicity in tests):</p><pre>@Test public void calculatesSinusoidResultBasedOnTimeWithOffset125ms() {<br>  loadingComputations = new LoadingComputations(0.f);</pre><pre>Assert.assertEquals((0. + 1)/2, loadingComputations.verticalPosition(-125, 125L), 0.002);</pre><pre>Assert.assertEquals((Math.sqrt(2)/2 + 1)/2, loadingComputations.verticalPosition(0, 125L), 0.002);</pre><pre>Assert.assertEquals((1 + 1)/2, loadingComputations.verticalPosition(125, 125L), 0.002);<br>}</pre><p>ALT+ENTER on verticalPositions’s parameters and click Add ‚long’ as 2nd parameter..</p><p>Now you need to find all the places that use this method and insert value 0, so we don’t break previous calculations.</p><p>Run tests. As expected only our last test failed. Let’s fix it right away.</p><p>We need to add to our previous time value offset and include it in calculations. In that case we get:</p><pre>public double verticalPosition(long time, long offset) {<br>  double X = 2 * Math.PI * (time + offset) / ANIMATION_LENGTH;<br>  return (Math.sin(X) + 1) / 2.;<br>}</pre><p>Run tests again — Passed!</p><p>We can now add this behavior to our LoadingView. Let’s get back to our onDraw method and let’s add offset 125 (it doesn’t have to be 125ms — it was perfect number for tests because we knew exact results of sinus for 0, 125 and 250. Now in the real example you can use any offset you want).</p><p>In onDraw:</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  if (framesManager.canGo()) {<br>    canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.fps()), 0.f, fpsPaint.getTextSize(), fpsPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(12),<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(20) * (float)loadingComputations.verticalPosition(System.currentTimeMillis(), 0),<br>        loadingComputations.dpToPx(3), dotPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50),<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(20) * (float)loadingComputations.verticalPosition(System.currentTimeMillis(), 125),<br>        loadingComputations.dpToPx(3), dotPaint);</pre><pre>canvas.drawCircle(<br>        loadingComputations.dpToPx(50) + loadingComputations.dpToPx(12),<br>        loadingComputations.dpToPx(50) — loadingComputations.dpToPx(20) * (float)loadingComputations.verticalPosition(System.currentTimeMillis(), 250),<br>        loadingComputations.dpToPx(3), dotPaint);<br>  }</pre><pre>framesManager.frame();<br>  invalidate();<br>}</pre><p>Run the App and see the results.</p><h3><strong>Closure</strong></h3><p>I’m not going to extend that view further in this article. In fact, I wanted to create a much bigger view for showing a wallet value. I haven’t expected that just for loading I will write this much. It’s my first article to public, which means I’m not aware of how long the articles should be, but I wanted to show every reader what are the key points of programming and building a big effect from very little steps.</p><p>This view is not perfect, there is still much to be done e.g.:</p><ul><li>Add separate thread that watches the time for each frame and refreshes it when it’s time — that would eliminate scintillation when we have lower FPS than maximum our machine can do. Now, you can just change TIME_PER_FRAME to 1000 / 100 and I don’t think any device on the market can draw over 100 FPS, so it will draw each frame.</li><li>I would add also a rest time for our dots, because now they run indefinitely and after 30 seconds it gets boring.</li><li>I’d also add some style able parameters to personalize our view.</li><li>I also thought of possibility to change our view’s size</li><li>Probably many others.</li></ul><p>But I think after this article you will gain a powerful tool which is knowledge of how to start with TDD.</p><p>If someone got that far (to the end of this article), I’m really amazed and flattered at the same time.</p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb3a41c6b37c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/facademy/animated-custom-view-driven-by-tests-part-3-fb3a41c6b37c">Animated Custom View — Driven by tests! — Part 3</a> was originally published in <a href="https://medium.com/facademy">FAcademy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Animated Custom View — Driven by tests! — Part 2]]></title>
            <link>https://medium.com/facademy/animated-custom-view-driven-by-tests-part-2-edd4cbcf039c?source=rss----e786222d210f---4</link>
            <guid isPermaLink="false">https://medium.com/p/edd4cbcf039c</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[custom-view-animation]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[custom-views]]></category>
            <dc:creator><![CDATA[Maciej Najbar]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 18:29:07 GMT</pubDate>
            <atom:updated>2017-03-18T05:10:17.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome again! So in Part 1 we finished on drawing our custom view. Not much this far, probably the most boring part of all three. Let’s have a look on our TO-DO list. Bolded text is what yet to come:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*-OobQmympiQHe5NZCO3OMA.gif" /></figure><ul><li>Extend View</li><li>Set fixed size</li><li>Set background to show view’s area</li><li>Draw a dot</li><li><strong>Animate and show FPS rate</strong></li><li><strong>Cut FPS to at most 60 FPS (optional)</strong></li><li><strong>Move a dot on sinusoidal path</strong></li><li><strong>Make sure dot jumps only up</strong></li><li><strong>Add other 2 dots so it’s 3 shown</strong></li><li><strong>Add time offset so they bounce independently</strong></li></ul><p>No time to hesitate any longer. Let’s get to work!</p><p><strong>Animate and show FPS rate</strong></p><p>To animate our view we need to refresh our view every frame. In Android, if something changes in our view, we need to call a special method called invalidate, so let’s do that.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  canvas.drawCircle(<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(3), dotPaint);</pre><pre>invalidate();<br>}</pre><p>Now, believe me or not, but our view is redrawn as fast as possible. Right after our dot is drawn, our view gets invalid and has to be redrawn — so it does happen.</p><p>To see how frequent the view is redrawn we’ll add frame counter in top-left corner.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  canvas.drawText(“Frames per second: “, 0.f, 0.f, fpsPaint);<br>  canvas.drawCircle(<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(3), dotPaint);</pre><pre>invalidate();<br>}</pre><p>ALT+ENTER on fpsPaint and click Create field ‚fpsPaint’.</p><p>Again we go to activity_main.xml to see results. We build…</p><p>Oups — I forgot to instantiate an object. Sorry, I always forget. Let me get back to LoadingView and add a missing snippet in constructor.</p><pre>…<br>  fpsPaint = new Paint(Paint.ANTI_ALIAS_FLAG);<br>}</pre><p>Now I can move back to activity_main.xml file, click build. Hmm.. Can you see any text? No? Me neither. Maybe it’s because I told canvas to draw the text in 0,0 position. I will get back to LoadingView and change position to be at 0,textSize.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  canvas.drawText(“Frames per second: “, 0.f,fpsPaint.getTextSize(), fpsPaint);</pre><pre>canvas.drawCircle(<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(3), dotPaint);</pre><pre>invalidate();<br>}</pre><p>Now I check it again in activity_main.xml, after building my project. I can see it now! But I think it takes too much. I’ll change text „Frame per second:” to just „FPS:”. Yup.. That’s fine by me.</p><p>But now I realized that it just shows text FPS, and I wanted to see some value. I’ll take that text out and make it formattable string.</p><pre>public class LoadingView extends View {<br>  private static final String FPS = “FPS: %d”;<br>  …<br>  @Override<br>  protected void onDraw(Canvas canvas) {<br>    canvas.drawText(FPS, 0.f, fpsPaint.getTextSize(), fpsPaint);<br>  …</pre><p>Ok, now in activity_main.xml it shows text “FPS: %d”. Not really what I meant.</p><p>We’ll need to create a tool that will help us calculate frames (of course TDD). We leave our LoadingView for now and let’s create a new class FramesManager.</p><p>ALT+ENTER on FramesManager class name and create a test, bearing in mind that it has to go to <strong>/test/ </strong>package.</p><p>Insert out first method:</p><pre>@Before public void setUp() {<br>  framesManager = new FramesManager();<br>}</pre><p>ALT+ENTER on framesManager and click Create field ‚framesManager’.</p><p>Now we need to make sure that our frames manager can calculate frames.</p><pre>@Test public void framesManagerMonitorsFramesProgress() {<br>  framesManager.frame();<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>ALT+ENTER on frame method and click create method.</p><p>ALT+ENTER on getFramesCount and click Create method ‚getFramesCount’.</p><p>You should now see the class FramesManager just like mine:</p><pre>public class FramesManager {<br>  public void frame() {<br>  }</pre><pre>public int getFramesCount() {<br>    return 0;<br>  }<br>}</pre><p>Run test class FramesManagerTest and watch the result. Fails — as expected.</p><p>Let’s follow the TDD process and make the smallest step we can. Let’s change result of getFramesCount to return 1:</p><pre>…<br>public int getFramesCount() {<br>  return 1;<br>}<br>…</pre><p>Now we need to make sure, that our code does exactly what we mean. Create new test:</p><pre>@Test public void makeSureFramesManagerIsAwareOfFramesPassed() {<br>  framesManager.frame();<br>  framesManager.frame();<br>  framesManager.frame();<br>  Assert.assertEquals(3, framesManager.getFramesCount());<br>}</pre><p>Not really. Expected value is 3 but the actual is 1. Let’s fix that with the smallest step we can (I know you can throw up with that sentence and I know you can see the perfect solution instantly, but believe me, this is really good practice to do as little as possible).</p><p>Go back to FramesManager class and change getFramesCount method:</p><pre>public int getFramesCount() {<br>  return frames;<br>}</pre><p>ALT+ENTER on frames and click Create field ‚frames’.</p><p>Run the tests now.</p><p>Crap! One of our test was already green, now both of them are red…</p><p>No worries, we invoke in our tests method frame that doesn’t do anything at all for now.</p><p>Ok, but in our tests we wanted to increment frame every time we call frame method. Let’s increment frames value in that method then.</p><pre>public void frame() {<br>  frames++;<br>}</pre><p>Run tests.</p><p>Hell yeah! Both green. Now we are sure that invoking method frame makes our frame manager monitoring the progress of frames. Working code we can finally use in our LoadingView.</p><pre>@Override<br>protected void onDraw(Canvas canvas) {<br>  canvas.drawText(FPS, 0.f, fpsPaint.getTextSize(), fpsPaint);<br>  canvas.drawCircle(<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(50),<br>      loadingComputations.dpToPx(3), dotPaint);</pre><pre>framesManager.frame();<br>  invalidate();<br>}</pre><p>ALT+ENTER on framesManager and click Create field ‚framesManager’. Make sure framesManager field is type of FramesManager itself.</p><p>Let’s make use of our formattable string FPS and put our frames count into it:</p><pre>…<br>canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.getFramesCount()), 0.f, fpsPaint.getTextSize(), fpsPaint);<br>…</pre><p>Let’s go to activity_main.xml file and see what is shows in Preview now.</p><p>Ehh.. NullPointerException.. We need to initialize framesUpdater. Do me a favor and add in constructor this line:</p><pre>…</pre><pre>framesManager = new FramesManager();</pre><pre>…</pre><p>Now we can get back to our activity_main.xml file, build and see the result.</p><p>YES! One step at the time. We can see the FPS: and some digit. Let’s see it live. Run application on physical device.</p><p>Ooook. It does shows us frames, but not exactly Frames Per Second, but more like Frames Drawn So Far.</p><p>Now we need to make sure that our frames manager knows that every second it needs to reset the counter.</p><p>We go back to FramesManagerTest class and we create a new failing test:</p><pre>@Test public void resetsFramesCountAfterOneSecond() throws Exception {<br>  framesManager.frame();<br>  framesManager.frame();<br>  framesManager.frame();<br>  Thread.sleep(1001);<br>  framesManager.frame();<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>After we run our test we can see that our frames manager is not aware of resetting. We need to check the difference between last frame and the current one if time is grater than 1 second. If it is, we reset frames count.</p><pre>public void frame() {<br>  long currentFrame = System.currentTimeMillis();<br>  if (currentFrame — lastFrame &gt; TimeUnit.SECONDS.toMillis(1)) {<br>    frames = 0;<br>  }</pre><pre>frames++;<br>  lastFrame = currentFrame;<br>}</pre><p>ALT+ENTER on lastFrame and click Create field ‚lastFrame’.</p><p>The time of our current frame, after all calculations, becomes our previous frame, so we can measure time between each two frames.</p><p>Let’s run our tests.</p><p>Wooohooo! Green! Thunderstruck!</p><p>But we need to be sure that it works as expected. One test is never convincing. One test means Happy Path. Let’s go to FramesManagerTest again and create another test — just to make sure:</p><pre>@Test public void resetsFramesCountsAfterOneSecondInTotal() throws Exception {<br>  framesManager.frame();<br>  Thread.sleep(300); // 300ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 600ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 900ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 1200ms<br>  framesManager.frame();<br>  assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>As I thought so.. Our previous test held process for 1s and that caused that our test worked. It didn’t work with more complicated scenario.</p><p>Let’s go back to FramesManager and change the code. Add another field that will be a summary of each time frame and then compare if after several frames, time is grater than 1s, if so, reset frames and clean timeSpan, so it can measure the time again.</p><pre>…<br>timeSpan += currentFrame — lastFrame;<br>if (timeSpan &gt; TimeUnit.SECONDS.toMillis(1)) {<br>  timeSpan = 0;<br>  frames = 0;<br>}<br>…</pre><p>ALT+ENTER on timeSpan and click Create field ‚timeSpan’.</p><p>Run all our tests.</p><p>GREEN!!!! Uff.. I want to be sure though, I’ll make some refactor in our last test method, and make another round of frames. I changed method name to describe more precisely of whats the goal:</p><pre>@Test public void resetsFramesCountsAfterOneSecondRepeatedly() throws Exception {<br>  framesManager.frame();<br>  Thread.sleep(300); // 300ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 600ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 900ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 1200ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 300ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 600ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 900ms<br>  framesManager.frame();<br>  Thread.sleep(300); // 1200ms<br>  framesManager.frame();<br>  Assert.assertEquals(1, framesManager.getFramesCount());<br>}</pre><p>Run tests.</p><p>Tick, tock, tick, tock…..</p><p>Greeeeeeeeen!</p><p>Now that we know it works we can run our application on physical device and see the result.</p><p>Hmm.. It does resets the FPS after 1s, but FPS should be some static number, not something that draws frames numbers from 1 to X in a loop.</p><p>We need to create another variable that will keep FPS and refresh it every second.</p><p>Ok, so open class FramesManagerTest and insert test method like the one below:</p><pre>@Test public void showsFramesPerSecond() throws Exception {<br>  framesManager.frame();<br>  framesManager.frame();<br>  framesManager.frame();<br>  Thread.sleep(1001);<br>  framesManager.frame();<br>  assertEquals(3, framesManager.fps());<br>}</pre><p>ALT+ENTER on fps and click Create method ‚fps’.</p><p>Run tests.</p><p>Failing.. I know it can annoy you so far, but make this newly created method to return 3.</p><p>Green. But we know — Happy Path, so let’s create a new test method:</p><pre>@Test public void showsCorrectFramesPerSecond() throws Exception {<br>  framesManager.frame();<br>  framesManager.frame();<br>  framesManager.frame();<br>  Thread.sleep(1001);<br>  framesManager.frame();<br>  framesManager.frame();<br>  Thread.sleep(1001);<br>  framesManager.frame();<br>  assertEquals(2, framesManager.fps());<br>}</pre><p>Run tests. You were right. It’s failing.</p><p>Now we can change our code:</p><pre>public int fps() {<br>  return fps;<br>}</pre><p>ALT+ENTER on fps and click Create field ‚fps’.</p><p>Run tests. No way! Two tests fail.</p><p>From the tests we can read that we want to save frames count right before reset.</p><pre>public void frame() {<br>  long currentFrame = System.currentTimeMillis();</pre><pre>timeSpan += currentFrame — lastFrame;<br>  if (timeSpan &gt; TimeUnit.SECONDS.toMillis(1)) {<br>    timeSpan = 0;<br>    fps = getFramesCount();<br>    frames = 0;<br>  }</pre><pre>frames++;<br>  lastFrame = currentFrame;<br>}</pre><p>Run tests.</p><p>Hurray! Green again. Our code is so stable..</p><p>Let’s now use that new method in our LoadingView:</p><pre>…<br>canvas.drawText(String.format(Locale.getDefault(), FPS, framesManager.fps()), 0.f, fpsPaint.getTextSize(), fpsPaint);<br>…</pre><p>And let’s see the result on physical device. Run the app.</p><p>Wow.. it works. And it works really nice. I get result on my device, something between 60–62 FPS. Pretty good result.</p><h3>Closure</h3><p>Congratulations! You finished second part of this journey. Animating this view was a big step forward. I know it doesn’t do much, but it’s a small piece of something much bigger. Read <a href="https://medium.com/@MaciejNajbar/animated-custom-view-driven-by-tests-part-3-fb3a41c6b37c#.86qsmfywp">Part 3</a> and get the job done.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd4cbcf039c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/facademy/animated-custom-view-driven-by-tests-part-2-edd4cbcf039c">Animated Custom View — Driven by tests! — Part 2</a> was originally published in <a href="https://medium.com/facademy">FAcademy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setup Jenkins for private GitHub repository]]></title>
            <link>https://medium.com/facademy/setup-jenkins-for-private-repository-9060f54eeac9?source=rss----e786222d210f---4</link>
            <guid isPermaLink="false">https://medium.com/p/9060f54eeac9</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Maciej Najbar]]></dc:creator>
            <pubDate>Sat, 16 Mar 2019 18:28:25 GMT</pubDate>
            <atom:updated>2017-12-04T09:55:46.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*bNLQb8_DBtWHwMvQ3ZXPzg.png" /></figure><p>Last couple of days I spent with Jenkins. It doesn’t seem like a funny weekend, right? Well it was really funny time. I ended up with no hair on my head and dozens of notes that actually don’t make sense at all.<br>So I decided to put it altogether here so whenever I need to go through this process again it’ll be easier. Feel free to use this article for your own purpose.</p><h4>Note!</h4><p>Jenkins may NOT work with Java version 9.x. This was the first problem I struggled with. If you have the same problem, download JDK 8u152 and install it.<br>Use this command in Terminal to remove Java 9.X from your Mac.</p><pre><strong>sudo rm -rf /Library/Java/JavaVirtualMachines/jdk-9.X.jdk</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*S1nITTWSbL-Lm34DM815ew.png" /></figure><p>Remember to restart your computer after that process.</p><h3>Jenkins installs on its own</h3><p>Basically there is lot of waiting while installing Jenkins and from time to time you just need to click something. That’s really cool part.<br>Download Jenkins from their <a href="https://jenkins.io/">official website</a> and install on your local machine.</p><p>When it’s done installing, Jenkins will be locked and you have to unlock it manually by copying and pasting initial password. You can find this password here:</p><pre><strong>sudo more /Users/Shared/Jenkins/Home/secrets/initialAdminPassword</strong></pre><p>When you paste it to that text box, click continue and wait another bit.<br>Select Install suggested plug-ins and wait one more bit (as I said, installing Jenkins is mostly a waiting process 😃).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D1bZW3iZmLA6Mn0GYCH6g.png" /></figure><h3>Preparing Jenkins GitHub account</h3><p>Ok, while plug-ins are installing it’s a good time to prepare an account you’ll use for building the project. In my opinion it’s wise to create extra account for tools.</p><p>If you don’t want to create a separate email for this account, you’re welcome to do the same trick as I did.<br>My GitHub account is created on <a href="http://maciek.najbar@gmail.com/">maciek.najbar@gmail.com</a> email.<br>I created Jenkins on <a href="http://maciek.najbar+jenkins@gmail.com/">maciek.najbar+jenkins@gmail.com</a>. This way I manage both accounts with just one email.</p><p>When you have the account already, let’s generate ssh key for that account and assign it to our Jenkins user. Open Terminal and follow steps below.</p><pre><strong>sudo su</strong><br><strong>(type your password)</strong></pre><pre><strong>whoami</strong><br>(should tell you that currently you&#39;re &#39;root&#39;)</pre><pre><strong>sudo su jenkins<br>whoami</strong><br>(should tell you that currently you&#39;re &#39;jenkins&#39;)</pre><pre><strong>ssh-keygen -t rsa -b 4096 -C &quot;maciek.najbar+jenkins@gmail.com&quot;</strong> <em># use your email for Jenkins GitHub account</em><br><strong>(Leave file name empty)</strong><br><strong>(Don&#39;t set password, just leave empty)</strong> <em># Jenkins is a service and it won&#39;t be able to enter passphrase when connecting to ssh</em></pre><p>Ok. Let’s leave it here for now.</p><h3>Create a new Job for Jenkins</h3><p>I assume Jenkins completed with all plug-ins installation. It will ask you to create Admin account to Jenkins panel. This account will be your point of control for the panel.</p><p>When you’re done and logged in to the panel, click at Create New Job. Name your job whatever you want and choose Freestyle project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPCwPye1S36jv_Hkw9kuHA.png" /><figcaption>One picture can be more descriptive than hundred words</figcaption></figure><p>Next step is job configuration. Let’s set only General part. So, we need to set Jenkins to <em>Discard old builds</em>(experiment with your own values) and to <em>Execute concurrent builds if neccessary</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*T1W4LICey5-B43F7cR0kEA.png" /></figure><p>Save progress.</p><h3>Create GitHub repository</h3><p>Login to your daily GitHub account and create new private repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*C_CkJNIG53FGyJVnvYfg-g.png" /></figure><p>Follow the steps that are displayed to connect your local Android project repository with GitHub remote server.</p><p>When it’s done, we need to add Jenkins GitHub account as a collaborator to our project. On the repository ribbon click Settings and go to Collaborators section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*ZBbe53L1G8ogq4Zhyx0OZw.png" /></figure><p>Find your Jenkins account and send an invite. You’ll receive an email to accept an invitation. To accept it, you first need to re-login to Jenkins GitHub account.</p><p>Invitation accepted? Awesome! Taking advantage you’re logged in to this account, let’s add SSH key that we previously prepared. Go to your account Settings and enter section <em>SSH and GPG keys</em>. Click on <em>Add new</em> for SSH keys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6m49tJmEuRQfarRFXoZczA.png" /></figure><p>When generating SSH key for Jenkins user, two files were created (id_rsa and id_rsa.pub). One of them is public and the other is private. Public key goes to GitHub.</p><pre><strong>whoami</strong> <em># make sure it says &#39;jenkins&#39;</em></pre><pre><strong>cd /Users/Shared/Jenkins/.ssh/<br>more id_rsa.pub</strong><br>(copy the entire output and paste to GitHub)</pre><p>Let’s leave the private key for now. But let’s establish connection for Jenkins to GitHub server. We need to add GitHub to known hosts. Let’s do it by simply connecting to GitHub server.</p><pre><strong>whoami</strong> <em># make sure it says &#39;jenkins&#39;</em></pre><pre><strong>ssh -T git@github.com</strong><br>(And yes, you&#39;re sure you want to continue)<br>(Result should be a welcome message)</pre><p>If you got the welcome message it means your Jenkins account finally has access to your repository!</p><h3>Continue job configuration</h3><p>Let’s connect Jenkins job to our repository. In job configuration go to <em>Source Code Management</em> section and choose <em>Git</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo9Jc4YAlHJfaHF6uktaHA.png" /></figure><p>In the picture you can see I have some credentials already, it’s because I created them in the previous picture. Click Add and you’ll see the same screen. Pick Kind: <em>SSH Username with private key</em> and type username and again, let’s go to terminal.</p><pre><strong>more /Users/Shared/Jenkins/.ssh/id_rsa</strong> <em># This time private key</em><br>(space, space, space until you see the entire private key)</pre><p>Copy entire private key as in the picture (including BEGIN and END stuff). Save and choose just created credentials (as in the last screenshot).</p><p>Go to Build Triggers and checkoff <em>Poll SCM</em>. Schedule it for every 15mins.</p><pre>H/15 * * * *</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3QlV27tp0EP8zKDzAMk8hg.png" /></figure><p>When you save here and run the build, it will pass. It will connect via SSH to your repository (and that’s basically all it will do).</p><p>But we want it to do more. We want it to run our Gradle commands to create build for us. Let’s go back to job configuration view again.</p><p>Go to Build section and click <em>Add build step</em>. Choose <em>Gradle script</em> option and pick <em>Use Gradle Wrapper</em> (because this is what Android projects use). Set the tasks you want Gradle to execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bxcRucNTgHjr88cXKmP3HQ.png" /></figure><p>Save the project and you can run the build again. Works? Excellent!</p><h3>What if my build fails?</h3><p>There is this possibility. I had it. I means that the project cannot find ANDROID_HOME environment variable. Well, first if your SDK folder is located in your computer user’s location, Jenkins user won’t be able to see it. Go to Android Studio and change that location to one that is shared by all the users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*LVvAiXNpCKLRUMc_ZUg5mQ.png" /></figure><p>When you change it, let your project rebuild. Install all missing tools and sdk platforms. When your project builds successfully again, you can delete the folder that previously was used to store all Android sdks.</p><p>Open Jenkins again, and go to Jenkins’ settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*V_TIMDKFIcq1lmOnuZ62bw.png" /></figure><p>Find Environment variables and set ANDROID_HOME to location you’ve just set in Android Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18kaiB2dhW9rsBM99kc5NA.png" /></figure><p>Save and go run the job again. Works? Awesome!</p><p>Still doesn’t work? Leave me a comment, together we can figure something out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9060f54eeac9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/facademy/setup-jenkins-for-private-repository-9060f54eeac9">Setup Jenkins for private GitHub repository</a> was originally published in <a href="https://medium.com/facademy">FAcademy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>