<?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 Alex Yu on Medium]]></title>
        <description><![CDATA[Stories by Alex Yu on Medium]]></description>
        <link>https://medium.com/@j620656786206?source=rss-f9d1014a9ffb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kZQMoT6xKH06rVvr_xefvA.jpeg</url>
            <title>Stories by Alex Yu on Medium</title>
            <link>https://medium.com/@j620656786206?source=rss-f9d1014a9ffb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:33:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@j620656786206/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[Testing — Mock: learn from the example of Dependency Injection]]></title>
            <link>https://medium.com/engineer-cat/testing-mock-learn-from-the-example-of-dependency-injection-bbf3a914d69?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbf3a914d69</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Sat, 25 May 2019 16:35:18 GMT</pubDate>
            <atom:updated>2019-05-25T16:35:18.542Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing — Mock: learn from the example of Dependency Injection</h3><h3>What is mock?</h3><ul><li><strong>mock objects</strong> are simulated objects that mimic the behavior of real objects in controlled ways</li></ul><h3>Dependency Injection Example</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb19f824a833394cae6ed2cb2ef675b4/href">https://medium.com/media/fb19f824a833394cae6ed2cb2ef675b4/href</a></iframe><p>To implement this function, we might initially do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b30668202f7e0df9f767055c646989d/href">https://medium.com/media/6b30668202f7e0df9f767055c646989d/href</a></iframe><p>After a little refactor, we may get</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a8db923042d423de2ec8900ff60e71/href">https://medium.com/media/06a8db923042d423de2ec8900ff60e71/href</a></iframe><p>The problem here is that the <em>onHttpResponse</em> function depends on the <em>httpRequest, resolve </em>and <em>reject </em>variables, but those variables do not exist at the location where the event handler function is now defined.</p><p>To fix it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6957cc41bacc8c3b89f5504557c9f6b/href">https://medium.com/media/e6957cc41bacc8c3b89f5504557c9f6b/href</a></iframe><p>What now?</p><p>The <em>onHttpResponse</em> function is an <em>event handler </em>function. This means that we have <em>no control</em> over what gets passed into the function as arguments when it is invoked. An event handler is <em>always </em>invoked with only one argument, namely the event object. We have a dilemma: We want to be able to pass <em>httpRequest, resolve </em>and <em>reject </em>into the <em>onHttpResponse</em>function as parameters, but when it is invoked, it will only be invoked with the event object.</p><p>To solve it, turn the <em>onHttpResponse</em> function into a <em>higher order function </em>that takes in the dependencies as parameters and returns the desired event handler function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4e3babd7d694db508e7f990568aa2ee/href">https://medium.com/media/e4e3babd7d694db508e7f990568aa2ee/href</a></iframe><p>The test for the <em>onHttpResponse</em> function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0098b1605beb3009c429fd71da8f7fa/href">https://medium.com/media/b0098b1605beb3009c429fd71da8f7fa/href</a></iframe><p>Back to the get function, how do we test it?</p><p>Refactor it to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d74bd14bbeb95039dd4ff385e19999/href">https://medium.com/media/12d74bd14bbeb95039dd4ff385e19999/href</a></iframe><p>The test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eef26b7076774f076ca7f11ba53baac6/href">https://medium.com/media/eef26b7076774f076ca7f11ba53baac6/href</a></iframe><p>Additional principle:</p><p>clear up after each test case</p><h3>Mocking a Service</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b870ef47191a0d4b2f58de8439d43c65/href">https://medium.com/media/b870ef47191a0d4b2f58de8439d43c65/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c184bc2b533ea955c0a985a11dddcb1/href">https://medium.com/media/9c184bc2b533ea955c0a985a11dddcb1/href</a></iframe><p>Test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c1581de830fce62cc570802e4c5b00/href">https://medium.com/media/a7c1581de830fce62cc570802e4c5b00/href</a></iframe><h3>Mocking a Class</h3><pre><em>// myClass.js</em></pre><pre><em>class</em> MyClass {<br>  constructor(name) {<br>    this.name = name;<br>  }</pre><pre>methodOne() {<br>    return 1;<br>  }</pre><pre>methodTwo() {<br>    return 2;<br>  }<br>}</pre><pre>export default MyClass;</pre><p>Test:</p><pre>import testSubject from &#39;./testSubject&#39;;</pre><pre>jest.mock(&#39;./myClass&#39;, () <em>=&gt;</em> () <em>=&gt;</em> ({<br>  name: &#39;Jody&#39;,<br>  methodOne: () <em>=&gt;</em> 10,<br>  methodTwo: () <em>=&gt;</em> 25,<br>}));</pre><h3>CommonJS Modules vs ES Modules</h3><p>module.exports / require and export / import</p><p>The standard ES Module export / import syntax would be:</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>export default ourCode;</pre><pre><em>// testSubject.js<br></em>import ourCode from &#39;./externalModule&#39;;</pre><pre>// use ourCode()</pre><p>The standard CommonJS module.exports / require syntax would be:</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>module.exports = ourCode;</pre><pre><em>// testSubject.js<br></em>const ourCode = require(&#39;./externalModule&#39;);</pre><pre>// use ourCode()</pre><p>Using module.exports and then import is also not a problem:</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>module.exports = ourCode;</pre><pre><em>// testSubject.js<br></em>import ourCode from &#39;./externalModule&#39;;</pre><pre>// use ourCode()</pre><p>However, when using export with require we would see an error such as:</p><pre>TypeError: ourCode is not a function</pre><p>The CommonJS module does not understand the ES Module it is trying to require. This is easily fixed, by adding a .functionNameBeingExported to the require, which for a default export is default.</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>export default ourCode;</pre><pre><em>// testSubject.js<br></em>const ourCode = require(&#39;./externalModule&#39;).default;</pre><pre>// use ourCode()</pre><p>A : no modification needed to the standard syntax</p><p>B : some modification needed,</p><p>we can see this illustrated below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*88lScrmHJxOa4Czu.png" /></figure><p>For type A these can be seen as a function returning a result:</p><p>jest.mock(&#39;.\<em>externalModule</em>&#39;, () =&gt; () =&gt; &#39;mock result&#39;);</p><p>For type B these can be seen as an object containing a function that returns a result:</p><pre>jest.mock(&#39;.\<em>externalModule</em>&#39;, () =&gt; ({<br>  default: () =&gt; &#39;mock result&#39;,<br>}));</pre><p>Additional gotcha :</p><p>If you have a React component like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1df3761feeb243bb53a90d14cbbb0d/href">https://medium.com/media/9e1df3761feeb243bb53a90d14cbbb0d/href</a></iframe><p>Jest mock should be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe100c9f262e88d147ec628e2706ea3/href">https://medium.com/media/fbe100c9f262e88d147ec628e2706ea3/href</a></iframe><h3>Mock Example 2</h3><p>the examples are going to be made up, but I hope you’d get the point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VBbXnvT5MC1RSQX6.png" /></figure><p>After refactor the Greeter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XmrzZ_4V9PK2IMVv.png" /></figure><ul><li>still pass the title and the name in the old order, even though our test claims that everything is fine, why?</li></ul><h3>You are mocking it wrong</h3><ul><li>The more complex your mocked object is the more complex your mock setup becomes.</li><li>If that’s not the case, most probably you’re testing just the interaction with your dumb mock, i.e. you’re not testing anything.</li><li>If you’re building a web service you should reset the state between requests, so keep as many dependencies request scoped as it’s possible.</li><li>Same pattern to testing, treat each test as a ‘request’ and let the DI container to build the system under test for you.</li><li>Module (or cluster) level test would build the dependency tree for that module but would mock out the rest of the world.</li></ul><h3>Reference:</h3><ul><li><a href="https://en.wikipedia.org/wiki/Mock_object">Mock object - Wikipedia</a></li><li><a href="https://matthung0807.blogspot.com/2018/03/sutdoc.html">測試 什麼是SUT與DOC，什麼是Test Double</a></li><li><a href="https://medium.com/@daniel.oliver.king/dependency-injection-practical-examples-for-testing-and-refactoring-in-javascript-3cb5b58b50be">Dependency Injection: Practical Examples for Testing and Refactoring in JavaScript</a></li><li><a href="https://medium.com/codeclan/mocking-es-and-commonjs-modules-with-jest-mock-37bbb552da43">Mocking ES and CommonJS modules with jest.mock()</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbf3a914d69" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineer-cat/testing-mock-learn-from-the-example-of-dependency-injection-bbf3a914d69">Testing — Mock: learn from the example of Dependency Injection</a> was originally published in <a href="https://medium.com/engineer-cat">Engineer&amp;Cat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing — Mock: learn from the example of Dependency Injection]]></title>
            <link>https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/testing-mock-learn-from-the-example-of-dependency-injection-5c76e4711697?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c76e4711697</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Sat, 25 May 2019 16:32:21 GMT</pubDate>
            <atom:updated>2019-05-25T16:32:21.692Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing — Mock: learn from the example of Dependency Injection</h3><h3>What is mock?</h3><ul><li>一種機制用來模擬真實物件的行為</li><li><strong>mock objects</strong> are simulated objects that mimic the behavior of real objects in controlled ways</li></ul><h3>Dependency Injection Example</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb19f824a833394cae6ed2cb2ef675b4/href">https://medium.com/media/fb19f824a833394cae6ed2cb2ef675b4/href</a></iframe><p>To implement this function, we might initially do something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b30668202f7e0df9f767055c646989d/href">https://medium.com/media/6b30668202f7e0df9f767055c646989d/href</a></iframe><p>After a little refactor, we may get</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a8db923042d423de2ec8900ff60e71/href">https://medium.com/media/06a8db923042d423de2ec8900ff60e71/href</a></iframe><p>The problem here is that the <em>onHttpResponse</em> function depends on the <em>httpRequest, resolve </em>and <em>reject </em>variables, but those variables do not exist at the location where the event handler function is now defined.</p><p>To fix it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6957cc41bacc8c3b89f5504557c9f6b/href">https://medium.com/media/e6957cc41bacc8c3b89f5504557c9f6b/href</a></iframe><p>What now?</p><p>The <em>onHttpResponse</em> function is an <em>event handler </em>function. This means that we have <em>no control</em> over what gets passed into the function as arguments when it is invoked. An event handler is <em>always </em>invoked with only one argument, namely the event object. We have a dilemma: We want to be able to pass <em>httpRequest, resolve </em>and <em>reject </em>into the <em>onHttpResponse</em>function as parameters, but when it is invoked, it will only be invoked with the event object.</p><p>To solve it, turn the <em>onHttpResponse</em> function into a <em>higher order function </em>that takes in the dependencies as parameters and returns the desired event handler function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4e3babd7d694db508e7f990568aa2ee/href">https://medium.com/media/e4e3babd7d694db508e7f990568aa2ee/href</a></iframe><p>The test for the <em>onHttpResponse</em> function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0098b1605beb3009c429fd71da8f7fa/href">https://medium.com/media/b0098b1605beb3009c429fd71da8f7fa/href</a></iframe><p>Back to the get function, how do we test it?</p><p>Refactor it to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12d74bd14bbeb95039dd4ff385e19999/href">https://medium.com/media/12d74bd14bbeb95039dd4ff385e19999/href</a></iframe><p>The test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eef26b7076774f076ca7f11ba53baac6/href">https://medium.com/media/eef26b7076774f076ca7f11ba53baac6/href</a></iframe><p>Additional principle:</p><p>clear up after each test case</p><h3>Mocking a Service</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b870ef47191a0d4b2f58de8439d43c65/href">https://medium.com/media/b870ef47191a0d4b2f58de8439d43c65/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c184bc2b533ea955c0a985a11dddcb1/href">https://medium.com/media/9c184bc2b533ea955c0a985a11dddcb1/href</a></iframe><p>Test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7c1581de830fce62cc570802e4c5b00/href">https://medium.com/media/a7c1581de830fce62cc570802e4c5b00/href</a></iframe><h3>Mocking a Class</h3><pre><em>// myClass.js</em></pre><pre><em>class</em> MyClass {<br>  constructor(name) {<br>    this.name = name;<br>  }</pre><pre>  methodOne() {<br>    return 1;<br>  }</pre><pre>  methodTwo() {<br>    return 2;<br>  }<br>}</pre><pre>export default MyClass;</pre><p>Test:</p><pre>import testSubject from &#39;./testSubject&#39;;</pre><pre>jest.mock(&#39;./myClass&#39;, () <em>=&gt;</em> () <em>=&gt;</em> ({<br>  name: &#39;Jody&#39;,<br>  methodOne: () <em>=&gt;</em> 10,<br>  methodTwo: () <em>=&gt;</em> 25,<br>}));</pre><h3>CommonJS Modules vs ES Modules</h3><p>module.exports / require and export / import</p><p>The standard ES Module export / import syntax would be:</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>export default ourCode;</pre><pre><em>// testSubject.js<br></em>import ourCode from &#39;./externalModule&#39;;</pre><pre>// use ourCode()</pre><p>The standard CommonJS module.exports / require syntax would be:</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>module.exports = ourCode;</pre><pre><em>// testSubject.js<br></em>const ourCode = require(&#39;./externalModule&#39;);</pre><pre>// use ourCode()</pre><p>Using module.exports and then import is also not a problem:</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>module.exports = ourCode;</pre><pre><em>// testSubject.js<br></em>import ourCode from &#39;./externalModule&#39;;</pre><pre>// use ourCode()</pre><p>However, when using export with require we would see an error such as:</p><pre>TypeError: ourCode is not a function</pre><p>The CommonJS module does not understand the ES Module it is trying to require. This is easily fixed, by adding a .functionNameBeingExported to the require, which for a default export is default.</p><pre><em>// externalModule.js<br></em>const ourCode = () =&gt; &#39;result&#39;;</pre><pre>export default ourCode;</pre><pre><em>// testSubject.js<br></em>const ourCode = require(&#39;./externalModule&#39;).default;</pre><pre>// use ourCode()</pre><p>A : no modification needed to the standard syntax</p><p>B : some modification needed,</p><p>we can see this illustrated below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/0*88lScrmHJxOa4Czu.png" /></figure><p>For type A these can be seen as a function returning a result:</p><p>jest.mock(&#39;.\<em>externalModule</em>&#39;, () =&gt; () =&gt; &#39;mock result&#39;);</p><p>For type B these can be seen as an object containing a function that returns a result:</p><pre>jest.mock(&#39;.\<em>externalModule</em>&#39;, () =&gt; ({<br>  default: () =&gt; &#39;mock result&#39;,<br>}));</pre><p>Additional gotcha :</p><p>If you have a React component like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e1df3761feeb243bb53a90d14cbbb0d/href">https://medium.com/media/9e1df3761feeb243bb53a90d14cbbb0d/href</a></iframe><p>Jest mock should be:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbe100c9f262e88d147ec628e2706ea3/href">https://medium.com/media/fbe100c9f262e88d147ec628e2706ea3/href</a></iframe><h3>Mock Example 2</h3><p>the examples are going to be made up, but I hope you’d get the point</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VBbXnvT5MC1RSQX6.png" /></figure><p>After refactor the Greeter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XmrzZ_4V9PK2IMVv.png" /></figure><ul><li>still pass the title and the name in the old order, even though our test claims that everything is fine, why?</li></ul><h3>You are mocking it wrong</h3><ul><li>mock越複雜的物件會使得你的mock設定越複雜</li><li>The more complex your mocked object is the more complex your mock setup becomes.</li><li>如果沒有，則你的測試很可能只是在跟你的mock互動，你並沒有測試到任何東西</li><li>If that’s not the case, most probably you’re testing just the interaction with your dumb mock, i.e. you’re not testing anything.</li><li>假如你正在建構一個web service，你應該要在每一個request間重置state，因此盡可能的保留dependencies request scoped</li><li>If you’re building a web service you should reset the state between requests, so keep as many dependencies request scoped as it’s possible.</li><li>同樣的pattern在測試時，每一個測試都應該視為獨立的request，讓DI container為你建構系統環境</li><li>Same pattern to testing, treat each test as a ‘request’ and let the DI container to build the system under test for you.</li><li>模組測試則應為所測試的模組建構dependency tree，並且mock掉其他的部分</li><li>Module (or cluster) level test would build the dependency tree for that module but would mock out the rest of the world.</li></ul><h3>Reference:</h3><ul><li><a href="https://en.wikipedia.org/wiki/Mock_object">Mock object - Wikipedia</a></li><li><a href="https://matthung0807.blogspot.com/2018/03/sutdoc.html">測試 什麼是SUT與DOC，什麼是Test Double</a></li><li><a href="https://medium.com/@daniel.oliver.king/dependency-injection-practical-examples-for-testing-and-refactoring-in-javascript-3cb5b58b50be">Dependency Injection: Practical Examples for Testing and Refactoring in JavaScript</a></li><li><a href="https://medium.com/codeclan/mocking-es-and-commonjs-modules-with-jest-mock-37bbb552da43">Mocking ES and CommonJS modules with jest.mock()</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c76e4711697" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/testing-mock-learn-from-the-example-of-dependency-injection-5c76e4711697">Testing — Mock: learn from the example of Dependency Injection</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93">工程師與貓</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing — TDD and Unit Testing]]></title>
            <link>https://medium.com/@j620656786206/testing-tdd-and-unit-testing-5f3d45060963?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3d45060963</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 16:36:30 GMT</pubDate>
            <atom:updated>2019-04-28T16:37:47.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing — TDD and Unit Testing</h3><h3>TDD</h3><h4>What is TDD?</h4><ul><li>From wiki:</li><li><strong>Test-driven development</strong> (<strong>TDD</strong>) is a <a href="https://en.wikipedia.org/wiki/Software_development_process">software development process</a> that relies on the repetition of a very short development cycle: requirements are turned into very specific <a href="https://en.wikipedia.org/wiki/Test_case">test cases</a>, then the software is improved to pass the new tests, only.</li></ul><h4>Why TDD?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqyBtpGsUcInxlmo.png" /></figure><ul><li>“keep it simple, stupid” (<a href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a>) and “<a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">You aren’t gonna need it</a>” (YAGNI). By focusing on writing only the code necessary to pass tests, designs can often be cleaner and clearer than is achieved by other methods</li><li>Testability</li><li>deeper and earlier understanding of the product requirements</li></ul><p><strong>The comparaison of costs:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jOS7CZX-gWfOoKGPUU29kg.png" /></figure><p><strong>The time spent:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4KJ9RSNP4_JsnGYjVxwnlw.png" /></figure><h4>How to do TDD?</h4><ol><li><strong>Add a test</strong></li></ol><ul><li>must clearly understand the feature’s specification and requirements</li><li>The developer can accomplish this through <a href="https://en.wikipedia.org/wiki/Use_case">use cases</a> and <a href="https://en.wikipedia.org/wiki/User_story">user stories</a> to cover the requirements and exception conditions</li><li>makes the developer focus on the requirements <strong><em>before</em></strong> writing the code</li></ul><p><strong>2. Run all tests and see if the new test fails</strong></p><p><strong>3. Write the code</strong></p><p><strong>4. Run tests</strong></p><p><strong>5. Refactor code</strong></p><ul><li>Duplication must be removed</li><li><a href="https://en.wikipedia.org/wiki/Object_(computer_science)">Object</a>, <a href="https://en.wikipedia.org/wiki/Class_(computer_programming)">class</a>, <a href="https://en.wikipedia.org/wiki/Modular_programming">module</a>, <a href="https://en.wikipedia.org/wiki/Variable_(computer_science)">variable</a> and <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)">method</a> names should clearly represent their current purpose and use</li><li>By continually re-running the test cases throughout each refactoring phase, the developer can be confident that process is not altering any existing functionality</li></ul><p><strong>Repeat</strong></p><ul><li>“red/green/refactor”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAZjBGkzRe-tnJCD.png" /></figure><h4>Keep the unit small</h4><ul><li>For TDD, a unit is most commonly defined as a class, or a group of related functions often called a module. Benefits including:</li><li>Reduced debugging effort — When test failures are detected, having smaller units aids in tracking down errors</li><li>Self-documenting tests — Small test cases are easier to read and to understand</li><li>Better practice:</li><li>acceptance test–driven development (ATDD) and</li><li>unit test-driven development(UTDD)</li></ul><h3>Unit Test</h3><h4>What is unit test?</h4><ul><li>a unit as the smallest testable part of an application</li><li>Ideally, each test case is independent from the others, a unit test should usually not go outside of its own unit boundary</li></ul><h4>Why unit test?</h4><ul><li>create decoupled and cohesive code bodies</li><li>By abstracting this necessary attachment from the code (temporarily reducing the net effective coupling), the independent unit can be more thoroughly tested than may have been previously achieved. This results in a higher-quality unit that is also more maintainable</li><li>isolate each part of the program and show that the individual parts are correct</li><li>allows the programmer to refactor code or upgrade system libraries</li></ul><h4>Good Principles:</h4><p>F.I.R.S.T</p><ul><li>Fast</li><li>One of the major cause of slow tests — is dependency that must handle external evil necessities such as databases, files, and network calls. They take thousands of milliseconds. So to make suite fast, you must avoid creating these dependencies by using <a href="https://howtodoinjava.com/best-practices/first-principles-for-good-tests/Mock%20Testing%20using%20PowerMock">mock testing</a>.</li><li>Isolated</li><li><strong>Never ever write tests which depend on other test cases</strong>. No order-of-run dependency.</li><li>Do not do any more actions after the assert statement(s), preferably single logical assert.</li><li>Repeatable</li><li>set up a private sandbox to avoid conflicts with other developers whose tests concurrently alter the database, use in-memory databases.</li><li><strong>Each test should setup or arrange it’s own data.</strong> create a helper function if have common data structures with other test cases</li><li>Self-validating</li><li>Each test must be able to determine that the output is expected or not</li><li>Timely/Thorough</li><li>Should cover every use case scenario and NOT just aim for 100% coverage.</li><li>Tests for corner/edge/boundary values.</li><li>Tests for large data sets</li><li>Tests for large values — overflow and underflow errors for data types like integer.</li><li>Tests for exceptions and errors.</li><li>Tests for illegal arguments or bad inputs.</li></ul><p>3A</p><ul><li>arrange</li><li>act</li><li>assert</li></ul><p>Other Good principles</p><ul><li>Know what you’re testing</li><li>use the scenario tested and expected result as part of the test method name. When a developer has a problem naming a test, that means the test lacks focus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*H7aQMPJ_DjOxVHy8" /></figure><ul><li>Naming conventions</li><li>When a well-named test fails, it is easier to understand what was tested and why it failed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*S7dbvl1HiBMbEqwv" /></figure><ul><li>Do repeat yourself</li><li>Readability is very important in unit testing, so it is acceptable to have duplicate code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*UYEyz2uyPmKJC2XF" /></figure><ul><li>Test results, not implementation</li><li>Successful unit testing requires writing tests that would only fail in case of an actual error or requirement change.</li><li>Avoid overspecification</li><li>Use an Isolation framework</li></ul><h3>Additional</h3><h4>What is the difference between TDD and unit test?</h4><p>The purpose of a unit test is to give a developer confidence that a particular part of their application behaves in the way that the developer expects. This is very valuable for regression testing. If you modify code that is covered by unit tests, then you can use the tests to immediately determine whether you have broken existing functionality.</p><p>So how does a TDD test differ from a unit test? Unlike a unit test, a TDD test is used to drive the design of an application. A TDD test is used to express what application code should do before the application code is actually written.</p><p>Like unit tests, TDD tests can be used for regression testing. You can use TDD tests to immediately determine whether a change in code has broken existing application functionality. However, unlike a unit test, a TDD test does not necessarily test one unit of code in isolation.</p><p>Like acceptance tests, TDD tests are used to drive the creation of an application. TDD tests work like mini-acceptance tests. You create a TDD test to express the application functionality that needs to be implemented next. However, unlike an acceptance test, a TDD test is not an end-to-end test. A TDD test does not interact with a live database or web server.</p><h4>What is regression test?</h4><ul><li>Regression testing is re-running functional and non-functional tests to ensure that previously developed and tested software still performs after a change. If not, that would be called a regression. Changes that may require regression testing include bug fixes, software enhancements, configuration changes, and even substitution of electronic components.</li></ul><h3>Reference:</h3><p><a href="https://en.wikipedia.org/wiki/Test-driven_development">https://en.wikipedia.org/wiki/Test-driven_development</a></p><p><a href="https://en.wikipedia.org/wiki/Unit_testing">https://en.wikipedia.org/wiki/Unit_testing</a></p><p><a href="http://agiledata.org/essays/tdd.html">http://agiledata.org/essays/tdd.html</a></p><p><a href="http://stephenwalther.com/archive/2009/04/11/tdd-tests-are-not-unit-tests">http://stephenwalther.com/archive/2009/04/11/tdd-tests-are-not-unit-tests</a></p><p><a href="https://hackernoon.com/test-f-i-r-s-t-65e42f3adc17">https://hackernoon.com/test-f-i-r-s-t-65e42f3adc17</a></p><p><a href="https://esj.com/Articles/2012/09/24/Better-Unit-Testing.aspx?Page=1">https://esj.com/Articles/2012/09/24/Better-Unit-Testing.aspx?Page=1</a></p><p><a href="https://www.ca.com/en/blog-agile-requirements-designer/guide-to-test-driven-development-tdd-vs-bdd-vs-atdd.html">https://www.ca.com/en/blog-agile-requirements-designer/guide-to-test-driven-development-tdd-vs-bdd-vs-atdd.html</a></p><p><a href="https://howtodoinjava.com/best-practices/first-principles-for-good-tests/">https://howtodoinjava.com/best-practices/first-principles-for-good-tests/</a></p><p><a href="https://github.com/ghsukumar/SFDC_Best_Practices/wiki/F.I.R.S.T-Principles-of-Unit-Testing">https://github.com/ghsukumar/SFDC_Best_Practices/wiki/F.I.R.S.T-Principles-of-Unit-Testing</a></p><p><a href="https://builttoadapt.io/why-tdd-489fdcdda05e">https://builttoadapt.io/why-tdd-489fdcdda05e</a></p><p><a href="https://medium.freecodecamp.org/test-driven-development-what-it-is-and-what-it-is-not-41fa6bca02a2">https://medium.freecodecamp.org/test-driven-development-what-it-is-and-what-it-is-not-41fa6bca02a2</a></p><p><a href="https://medium.com/javascript-scene/the-outrageous-cost-of-skipping-tdd-code-reviews-57887064c412">https://medium.com/javascript-scene/the-outrageous-cost-of-skipping-tdd-code-reviews-57887064c412</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3d45060963" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing — TDD and Unit Testing]]></title>
            <link>https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/testing-tdd-and-unit-testing-a62c7c391aaa?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62c7c391aaa</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 16:28:54 GMT</pubDate>
            <atom:updated>2019-04-28T16:28:54.897Z</atom:updated>
            <content:encoded><![CDATA[<h3>Testing — TDD and Unit Testing</h3><h3><strong>近況更新</strong></h3><p>入職到現在也已經要半年了，工作內容主要是用react native做APP，所以之前的Android side project就暫停了。這篇文章也是因為前陣子公司開始準備寫測試，所以便紀錄了一下學習心得的重點。關於測試的文章大概會分三篇，第一篇便是這篇，闡述了一下TDD跟Unit test。第二篇會著重在藉由DI(dependency injection)的例子介紹mock。最後一篇則會介紹到寫測試時要考慮到哪些test cases與boundary case，因為畢竟測試是沒有寫完的一天...</p><h3>TDD</h3><h4>What is TDD?</h4><ul><li>From wiki:</li><li><strong>Test-driven development</strong> (<strong>TDD</strong>) is a <a href="https://en.wikipedia.org/wiki/Software_development_process">software development process</a> that relies on the repetition of a very short development cycle: requirements are turned into very specific <a href="https://en.wikipedia.org/wiki/Test_case">test cases</a>, then the software is improved to pass the new tests, only.</li><li><strong>測試驅動開發 </strong>是一種<a href="https://zh.wikipedia.org/wiki/%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91%E8%BF%87%E7%A8%8B">軟體開發過程</a>中的應用方法，是一種非常短的重複性開發流程，將需求轉變為非常具體的測試案例，然後改善軟體，使其僅通過新的測試案例。</li></ul><h4>Why TDD?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uqyBtpGsUcInxlmo.png" /></figure><ul><li>KISS 原則是指在設計當中應當注重簡約的原則，YAGNI則指不應該為程式碼加入尚未用到的功能。</li><li>“keep it simple, stupid” (<a href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a>) and “<a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">You aren’t gonna need it</a>” (YAGNI). By focusing on writing only the code necessary to pass tests, designs can often be cleaner and clearer than is achieved by other methods</li><li>可測性</li><li>Testability</li><li>更深入和更早地了解產品要求</li><li>deeper and earlier understanding of the product requirements</li></ul><p><strong>The comparaison of costs:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jOS7CZX-gWfOoKGPUU29kg.png" /></figure><p><strong>The time spent:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*4KJ9RSNP4_JsnGYjVxwnlw.png" /></figure><h4>How to do TDD?</h4><ol><li><strong>加入一個測試</strong> <strong>Add a test</strong></li></ol><ul><li>必須了解整個功能的規格跟要求</li><li>must clearly understand the feature’s specification and requirements</li><li>軟體開發者可透過使用者案例跟使用者故事去涵蓋這些產品要求跟例外情況</li><li>The developer can accomplish this through <a href="https://en.wikipedia.org/wiki/Use_case">use cases</a> and <a href="https://en.wikipedia.org/wiki/User_story">user stories</a> to cover the requirements and exception conditions</li><li>讓開發者可在開發前，專注在產品要求上</li><li>makes the developer focus on the requirements <strong><em>before</em></strong> writing the code</li></ul><p><strong>2. 跑所有測試，並確保這個新加入的測試結果為失敗的</strong> <strong>Run all tests and see if the new test fails</strong></p><p><strong>3. 開發程式</strong> <strong>Write the code</strong></p><p><strong>4. 跑測試</strong> <strong>Run tests</strong></p><p><strong>5. 重構程式</strong> <strong>Refactor code</strong></p><ul><li>移除重複的程式碼</li><li>Duplication must be removed</li><li>物件，類別，模組，變數以及方法名稱應清楚表達他們的目的與使用</li><li><a href="https://en.wikipedia.org/wiki/Object_(computer_science)">Object</a>, <a href="https://en.wikipedia.org/wiki/Class_(computer_programming)">class</a>, <a href="https://en.wikipedia.org/wiki/Modular_programming">module</a>, <a href="https://en.wikipedia.org/wiki/Variable_(computer_science)">variable</a> and <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)">method</a> names should clearly represent their current purpose and use</li><li>在每一次的重構階段，藉由重複性的跑這些測試案例可以讓程式開發者建立信心，確保每一次的重構並沒有改變現存的所有功能</li><li>By continually re-running the test cases throughout each refactoring phase, the developer can be confident that process is not altering any existing functionality</li></ul><p><strong>Repeat</strong></p><ul><li>“red/green/refactor”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAZjBGkzRe-tnJCD.png" /></figure><h4>Keep the unit small</h4><ul><li>For TDD, a unit is most commonly defined as a class, or a group of related functions often called a module. Benefits including:</li><li>Reduced debugging effort — When test failures are detected, having smaller units aids in tracking down errors</li><li>Self-documenting tests — Small test cases are easier to read and to understand</li><li>Better practice:</li><li>acceptance test–driven development (ATDD) and</li><li>unit test-driven development(UTDD)</li></ul><h3>Unit Test</h3><h4>What is unit test?</h4><ul><li>一個單元為程式中最小可測試單位</li><li>a unit as the smallest testable part of an application</li><li>理想情況下，每個測試用例都獨立於其他測試用例，單元測試通常不應超出其自身的單位邊界</li><li>Ideally, each test case is independent from the others, a unit test should usually not go outside of its own unit boundary</li></ul><h4>Why unit test?</h4><ul><li>建造解耦且有凝聚力的程式碼</li><li>create decoupled and cohesive code bodies</li><li>藉由從程式中抽取出這些必要的附件（暫時減少耦合），獨立單元可以比以前進行更徹底的測試。 可使得我們有更高質量的單元，也更易於維護</li><li>By abstracting this necessary attachment from the code (temporarily reducing the net effective coupling), the independent unit can be more thoroughly tested than may have been previously achieved. This results in a higher-quality unit that is also more maintainable</li><li>隔離程式的每個部分，並確保各個部分是正確的</li><li>isolate each part of the program and show that the individual parts are correct</li><li>讓軟體工程師可以進行重構</li><li>allows the programmer to refactor code or upgrade system libraries</li></ul><h4>Good Principles:</h4><p>F.I.R.S.T</p><ul><li>快速 Fast</li><li>One of the major cause of slow tests — is dependency that must handle external evil necessities such as databases, files, and network calls. They take thousands of milliseconds. So to make suite fast, you must avoid creating these dependencies by using <a href="https://howtodoinjava.com/best-practices/first-principles-for-good-tests/Mock%20Testing%20using%20PowerMock">mock testing</a>.</li><li>隔離 Isolated</li><li><strong>Never ever write tests which depend on other test cases</strong>. No order-of-run dependency.</li><li>Do not do any more actions after the assert statement(s), preferably single logical assert.</li><li>重複 Repeatable</li><li>set up a private sandbox to avoid conflicts with other developers whose tests concurrently alter the database, use in-memory databases.</li><li><strong>Each test should setup or arrange it’s own data.</strong> create a helper function if have common data structures with other test cases</li><li>自我驗證 Self-validating</li><li>Each test must be able to determine that the output is expected or not</li><li>適時/徹底 Timely/Thorough</li><li>Should cover every use case scenario and NOT just aim for 100% coverage.</li><li>Tests for corner/edge/boundary values.</li><li>Tests for large data sets</li><li>Tests for large values — overflow and underflow errors for data types like integer.</li><li>Tests for exceptions and errors.</li><li>Tests for illegal arguments or bad inputs.</li></ul><p>3A</p><ul><li>arrange</li><li>act</li><li>assert</li></ul><p>Other Good principles</p><ul><li>Know what you’re testing</li><li>use the scenario tested and expected result as part of the test method name. When a developer has a problem naming a test, that means the test lacks focus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/0*H7aQMPJ_DjOxVHy8" /></figure><ul><li>Naming conventions</li><li>When a well-named test fails, it is easier to understand what was tested and why it failed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*S7dbvl1HiBMbEqwv" /></figure><ul><li>Do repeat yourself</li><li>Readability is very important in unit testing, so it is acceptable to have duplicate code.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*UYEyz2uyPmKJC2XF" /></figure><ul><li>Test results, not implementation</li><li>Successful unit testing requires writing tests that would only fail in case of an actual error or requirement change.</li><li>Avoid overspecification</li><li>Use an Isolation framework</li></ul><h3>Additional</h3><h4>What is the difference between TDD and unit test?</h4><p>The purpose of a unit test is to give a developer confidence that a particular part of their application behaves in the way that the developer expects. This is very valuable for regression testing. If you modify code that is covered by unit tests, then you can use the tests to immediately determine whether you have broken existing functionality.</p><p>So how does a TDD test differ from a unit test? Unlike a unit test, a TDD test is used to drive the design of an application. A TDD test is used to express what application code should do before the application code is actually written.</p><p>Like unit tests, TDD tests can be used for regression testing. You can use TDD tests to immediately determine whether a change in code has broken existing application functionality. However, unlike a unit test, a TDD test does not necessarily test one unit of code in isolation.</p><p>Like acceptance tests, TDD tests are used to drive the creation of an application. TDD tests work like mini-acceptance tests. You create a TDD test to express the application functionality that needs to be implemented next. However, unlike an acceptance test, a TDD test is not an end-to-end test. A TDD test does not interact with a live database or web server.</p><h4>What is regression test?</h4><ul><li>Regression testing is re-running functional and non-functional tests to ensure that previously developed and tested software still performs after a change. If not, that would be called a regression. Changes that may require regression testing include bug fixes, software enhancements, configuration changes, and even substitution of electronic components.</li></ul><h3>Reference:</h3><p><a href="https://en.wikipedia.org/wiki/Test-driven_development">https://en.wikipedia.org/wiki/Test-driven_development</a></p><p><a href="https://en.wikipedia.org/wiki/Unit_testing">https://en.wikipedia.org/wiki/Unit_testing</a></p><p><a href="http://agiledata.org/essays/tdd.html">http://agiledata.org/essays/tdd.html</a></p><p><a href="http://stephenwalther.com/archive/2009/04/11/tdd-tests-are-not-unit-tests">http://stephenwalther.com/archive/2009/04/11/tdd-tests-are-not-unit-tests</a></p><p><a href="https://hackernoon.com/test-f-i-r-s-t-65e42f3adc17">https://hackernoon.com/test-f-i-r-s-t-65e42f3adc17</a></p><p><a href="https://esj.com/Articles/2012/09/24/Better-Unit-Testing.aspx?Page=1">https://esj.com/Articles/2012/09/24/Better-Unit-Testing.aspx?Page=1</a></p><p><a href="https://www.ca.com/en/blog-agile-requirements-designer/guide-to-test-driven-development-tdd-vs-bdd-vs-atdd.html">https://www.ca.com/en/blog-agile-requirements-designer/guide-to-test-driven-development-tdd-vs-bdd-vs-atdd.html</a></p><p><a href="https://howtodoinjava.com/best-practices/first-principles-for-good-tests/">https://howtodoinjava.com/best-practices/first-principles-for-good-tests/</a></p><p><a href="https://github.com/ghsukumar/SFDC_Best_Practices/wiki/F.I.R.S.T-Principles-of-Unit-Testing">https://github.com/ghsukumar/SFDC_Best_Practices/wiki/F.I.R.S.T-Principles-of-Unit-Testing</a></p><p><a href="https://builttoadapt.io/why-tdd-489fdcdda05e">https://builttoadapt.io/why-tdd-489fdcdda05e</a></p><p><a href="https://medium.freecodecamp.org/test-driven-development-what-it-is-and-what-it-is-not-41fa6bca02a2">https://medium.freecodecamp.org/test-driven-development-what-it-is-and-what-it-is-not-41fa6bca02a2</a></p><p><a href="https://medium.com/javascript-scene/the-outrageous-cost-of-skipping-tdd-code-reviews-57887064c412">https://medium.com/javascript-scene/the-outrageous-cost-of-skipping-tdd-code-reviews-57887064c412</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62c7c391aaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/testing-tdd-and-unit-testing-a62c7c391aaa">Testing — TDD and Unit Testing</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93">工程師與貓</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Note] Build an Instagram Clone — Retrieving User Data from Firebase (Part 31)]]></title>
            <link>https://medium.com/engineer-cat/note-build-an-instagram-clone-retrieving-user-data-from-firebase-part-31-88fd6a87131d?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/88fd6a87131d</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Sun, 05 Aug 2018 20:46:17 GMT</pubDate>
            <atom:updated>2018-08-05T20:46:17.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh9ZtmHno6WllrN3NUqFhg.png" /></figure><p>The goal of this video is to get the user and user_account_setting node from Firebase, then show the user’s images. But before start the video, I need to make some changes in the HomeActivity, I didn’t use AuthStateListener.</p><p>First, add a new global variable</p><pre>//firebase<br>private FirebaseAuth.AuthStateListener mAuthListener;</pre><p>Then go to the bottom part related to Firebase, modify setupFirebaseAuth,onStart, and onStop</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fc403f2e1ca07c99c305b65ded0774e/href">https://medium.com/media/5fc403f2e1ca07c99c305b65ded0774e/href</a></iframe><p>After finish, we can test it out, make sure no error in the app. Then we can copy all the Firebase code and start the video part.</p><p>First go to ProfileFragment, paste the Firebase code to the bottom. Then go to the top and declare related global variables</p><pre>//firebase<br>private FirebaseAuth mAuth;<br>private FirebaseAuth.AuthStateListener mAuthListener;<br>private FirebaseDatabase mFirebaseDatabase;<br>private DatabaseReference myRef;</pre><p>Back to the code we pasted, we can delete checkCurrentUser and the place declared it. Then under mAuth in setupFirebaseAuth, declare following</p><pre>mFirebaseDatabase = FirebaseDatabase.<em>getInstance</em>();<br>myRef = mFirebaseDatabase.getReference();</pre><p>Add the following code under mAuthListener</p><pre>myRef.addValueEventListener(new ValueEventListener() {<br>    @Override<br>    public void onDataChange(DataSnapshot dataSnapshot) {<br>        // retrieve user information from the database</pre><pre>        // retrieve images for the user in question<br>    }</pre><pre>    @Override<br>    public void onCancelled(DatabaseError databaseError) {</pre><pre>    }<br>});</pre><p>Here we’ve done with ProfileFragment. Next we need to fetch the user_account_setting and user from the Firebase.</p><p>In order to fetch the user_account_setting and user together, we need a java class to get and set these two nodes. So go to models directory, add a new java class named UserSettings</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d93b60171aeba3b844c813b8eb34e271/href">https://medium.com/media/d93b60171aeba3b844c813b8eb34e271/href</a></iframe><p>Next open Utils/FirebaseMathods, make a little bit of change in addNewUser. In the Firebase, there’s no “.” between first name and last name, because we didn’t condense the name in the settings, so modify as the following</p><pre>UserAccountSettings settings = new UserAccountSettings(<br>        description,<br>        username,<br>        0,<br>        0,<br>        0,<br>        profile_photo,<br>        StringManipulation.<em>condenseUsername</em>(username),<br>        website<br>);</pre><p>Then we can add new method under addNewUser</p><pre>public UserSettings getUserAccountSettings(DataSnapshot dataSnapshot) {<br>    Log.<em>d</em>(<em>TAG</em>, &quot;getUserAccountSettings: retrieving user account settings from database&quot;);</pre><pre>}</pre><p>So we need to loop through this dataSnapshot to determine if it’s the usr_account_settings node, we set each data in the node, vice versa. If it’s the user node, we set each data too. The detail code is below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/288e1e1aabfe984c5eaa32a0d09c1947/href">https://medium.com/media/288e1e1aabfe984c5eaa32a0d09c1947/href</a></iframe><p>Here we finish the video part, the rest to be continued.</p><h3>Video</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLgCYzUzKIBE9XqkckEJJA0I1wVKbUAOdv%26start%3D0&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dexi3lGveLbw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fexi3lGveLbw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fb4836475fda37899ee5b33cb6142b4/href">https://medium.com/media/8fb4836475fda37899ee5b33cb6142b4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88fd6a87131d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineer-cat/note-build-an-instagram-clone-retrieving-user-data-from-firebase-part-31-88fd6a87131d">[Note] Build an Instagram Clone — Retrieving User Data from Firebase (Part 31)</a> was originally published in <a href="https://medium.com/engineer-cat">Engineer&amp;Cat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[筆記] Build an Instagram Clone —Retrieving User Data from Firebase (Part 31)]]></title>
            <link>https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/%E7%AD%86%E8%A8%98-build-an-instagram-clone-retrieving-user-data-from-firebase-part-31-f7baad2ce43d?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7baad2ce43d</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Tue, 31 Jul 2018 03:07:00 GMT</pubDate>
            <atom:updated>2018-07-31T03:07:00.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh9ZtmHno6WllrN3NUqFhg.png" /></figure><p>這次影片的進度目標是想要從Firebase取得user跟user_account_setting節點的資料，進一步在將user的圖片顯示出來。不過在開始進入影片的進度之前，我需要先到HomeActivity做一些修改，因為我之前沒有使用AuthStateListener。</p><p>首先在宣告全域變數的地方新增一個變數，</p><pre>//firebase<br>private FirebaseAuth.AuthStateListener mAuthListener;</pre><p>然後到最下面Firebase的地方，修改setupFirebaseAuth , onStart 跟onStop</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fc403f2e1ca07c99c305b65ded0774e/href">https://medium.com/media/5fc403f2e1ca07c99c305b65ded0774e/href</a></iframe><p>完成後可以測試看看程式有沒有錯誤，接著複製所有Firebase程式碼的部分，然後便可開始進入到影片的部分。</p><p>首先到ProfileFragment，將剛剛複製的程式碼貼到最下面，然後到最上面宣告相關的全域變數</p><pre>//firebase<br>private FirebaseAuth mAuth;<br>private FirebaseAuth.AuthStateListener mAuthListener;<br>private FirebaseDatabase mFirebaseDatabase;<br>private DatabaseReference myRef;</pre><p>接著我們便可回到剛剛貼上的程式碼，可以刪掉checkCurrentUser 函式跟有宣告用到它的部分。然後在setupFirebaseAuth 的mAuth底下宣告</p><pre>mFirebaseDatabase = FirebaseDatabase.<em>getInstance</em>();<br>myRef = mFirebaseDatabase.getReference();</pre><p>接著在mAuthListener 下面加入</p><pre>myRef.addValueEventListener(new ValueEventListener() {<br>    @Override<br>    public void onDataChange(DataSnapshot dataSnapshot) {<br>        // retrieve user information from the database<br><br>        // retrieve images for the user in question<br>    }<br><br>    @Override<br>    public void onCancelled(DatabaseError databaseError) {<br><br>    }<br>});</pre><p>到這邊暫時告一段落，接下來我們需要將user_account_setting跟user從Firebase讀取出來。</p><p>為了將user_account_settings跟user一起讀取出來，我們需要一個java class可以get跟set這兩個node。所以到models資料夾新增一個java class叫UserSettings</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d93b60171aeba3b844c813b8eb34e271/href">https://medium.com/media/d93b60171aeba3b844c813b8eb34e271/href</a></iframe><p>接著便可到Utils/FirebaseMethods，先到addNewUser 做一下小修改。在Firebase的資料裡，username的名字跟姓氏沒有&quot;.&quot;在中間，因為我們在這裡的settings宣告沒有condense名字，所以修改如下</p><pre>UserAccountSettings settings = new UserAccountSettings(<br>        description,<br>        username,<br>        0,<br>        0,<br>        0,<br>        profile_photo,<br>        StringManipulation.<em>condenseUsername</em>(username),<br>        website<br>);</pre><p>下一步我們便可在addNewUser 底下宣告一個新的函式，</p><pre>public UserSettings getUserAccountSettings(DataSnapshot dataSnapshot) {<br>    Log.<em>d</em>(<em>TAG</em>, &quot;getUserAccountSettings: retrieving user account settings from database&quot;);</pre><pre>}</pre><p>我們要透過這個dataSnapshot去迴圈判斷如果是user_account_settings節點的話，便去set每一個資料；反之如果是user節點的話便一樣set裡面的資料。詳細的程式碼如下</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/288e1e1aabfe984c5eaa32a0d09c1947/href">https://medium.com/media/288e1e1aabfe984c5eaa32a0d09c1947/href</a></iframe><p>到這邊便完成了影片的部分，未完成的部分待續。</p><h3>影片</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLgCYzUzKIBE9XqkckEJJA0I1wVKbUAOdv%26start%3D0&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dexi3lGveLbw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fexi3lGveLbw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fb4836475fda37899ee5b33cb6142b4/href">https://medium.com/media/8fb4836475fda37899ee5b33cb6142b4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7baad2ce43d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/%E7%AD%86%E8%A8%98-build-an-instagram-clone-retrieving-user-data-from-firebase-part-31-f7baad2ce43d">[筆記] Build an Instagram Clone —Retrieving User Data from Firebase (Part 31)</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93">工程師與貓</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Note] Build an Instagram Clone — Profile Fragment Setup (Part 30)]]></title>
            <link>https://medium.com/engineer-cat/note-build-an-instagram-clone-profile-fragment-setup-part-30-39790ad0c020?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/39790ad0c020</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 02:06:52 GMT</pubDate>
            <atom:updated>2018-07-24T02:06:52.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh9ZtmHno6WllrN3NUqFhg.png" /></figure><p>This part continues previous progress, the main goal in here is to set up the Profile Fragment. First, declare the following global variables in ProfileFragment.java</p><pre>private TextView mPosts, mFollowers, mFollowing, mDisplayName, mUsername, mWebsite, mDescription;<br>private ProgressBar mprogressBar;<br>private CircleImageView mProfilePhoto;<br>private GridView gridView;<br>private Toolbar toolbar;<br>private ImageView profileMenu;<br>private BottomNavigationViewEx bottomNavigationView;</pre><p>Notice here the Toobar need to choose import support.v7 version, you can not choose android.widget</p><pre>import android.support.v7.widget.Toolbar;</pre><p>Then go to onCreateView to initialize each variable</p><pre>View view = inflater.inflate(R.layout.<em>fragment_profile</em>, container, false);<br>mDisplayName = (TextView) view.findViewById(R.id.<em>display_name</em>);<br>mUsername = (TextView) view.findViewById(R.id.<em>username</em>);<br>mWebsite = (TextView) view.findViewById(R.id.<em>website</em>);<br>mDescription = (TextView) view.findViewById(R.id.<em>description</em>);<br>mProfilePhoto = (CircleImageView) view.findViewById(R.id.<em>profile_photo</em>);<br>mPosts = (TextView) view.findViewById(R.id.<em>tvPosts</em>);<br>mFollowers = (TextView) view.findViewById(R.id.<em>tvFollowers</em>);<br>mFollowing = (TextView) view.findViewById(R.id.<em>tvFollowing</em>);<br>mprogressBar = (ProgressBar) view.findViewById(R.id.<em>profileProgressBar</em>);<br>gridView = (GridView) view.findViewById(R.id.<em>gridView</em>);<br>toolbar = (Toolbar) view.findViewById(R.id.<em>profileToolBar</em>);<br>profileMenu = (ImageView) view.findViewById(R.id.<em>profileMenu</em>);<br>bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.<em>bottomNavViewBar</em>);</pre><p>Then go to ProfileActivity, copy the setupToolBar and setupBottomNavigationView method, and go back to ProfileFragment and declare associated variables</p><pre>private static final int <em>ACTIVITY_NUM </em>= 4;</pre><p>and</p><pre>private Context mContext;</pre><p>Two method made few changes, the details please see below</p><p>ProfileFragment.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402a4bfb730269f614e1871903682934/href">https://medium.com/media/402a4bfb730269f614e1871903682934/href</a></iframe><p>Then go to onCreateView and call these two method, and it’s done.</p><h3>Screenshot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGyzrgl4Fox-hplUubmWWA.gif" /></figure><h3>Video</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLgCYzUzKIBE9XqkckEJJA0I1wVKbUAOdv%26start%3D0&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dwii1svFW8d8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fwii1svFW8d8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e513b02a1ce0050fdd5120f061929f02/href">https://medium.com/media/e513b02a1ce0050fdd5120f061929f02/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39790ad0c020" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineer-cat/note-build-an-instagram-clone-profile-fragment-setup-part-30-39790ad0c020">[Note] Build an Instagram Clone — Profile Fragment Setup (Part 30)</a> was originally published in <a href="https://medium.com/engineer-cat">Engineer&amp;Cat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[筆記] Build an Instagram Clone — Profile Fragment Setup (Part 30)]]></title>
            <link>https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/%E7%AD%86%E8%A8%98-build-an-instagram-clone-profile-fragment-setup-part-30-d840fbdfca3c?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d840fbdfca3c</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[android-apps]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Tue, 24 Jul 2018 01:57:06 GMT</pubDate>
            <atom:updated>2018-07-24T02:07:31.910Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh9ZtmHno6WllrN3NUqFhg.png" /></figure><p>這個部分延續之前的進度，主要目的在設置Profile Fragment的部分。首先在ProfileFragment.java宣告相關的全域變數</p><pre>private TextView mPosts, mFollowers, mFollowing, mDisplayName, mUsername, mWebsite, mDescription;<br>private ProgressBar mprogressBar;<br>private CircleImageView mProfilePhoto;<br>private GridView gridView;<br>private Toolbar toolbar;<br>private ImageView profileMenu;<br>private BottomNavigationViewEx bottomNavigationView;</pre><p>這邊要注意的點是Toolbar要選擇support.v7的版本，不能選擇內建的android.widget</p><pre>import android.support.v7.widget.Toolbar;</pre><p>接著到onCreateView裡面做每個變數的初始化</p><pre>View view = inflater.inflate(R.layout.<em>fragment_profile</em>, container, false);<br>mDisplayName = (TextView) view.findViewById(R.id.<em>display_name</em>);<br>mUsername = (TextView) view.findViewById(R.id.<em>username</em>);<br>mWebsite = (TextView) view.findViewById(R.id.<em>website</em>);<br>mDescription = (TextView) view.findViewById(R.id.<em>description</em>);<br>mProfilePhoto = (CircleImageView) view.findViewById(R.id.<em>profile_photo</em>);<br>mPosts = (TextView) view.findViewById(R.id.<em>tvPosts</em>);<br>mFollowers = (TextView) view.findViewById(R.id.<em>tvFollowers</em>);<br>mFollowing = (TextView) view.findViewById(R.id.<em>tvFollowing</em>);<br>mprogressBar = (ProgressBar) view.findViewById(R.id.<em>profileProgressBar</em>);<br>gridView = (GridView) view.findViewById(R.id.<em>gridView</em>);<br>toolbar = (Toolbar) view.findViewById(R.id.<em>profileToolBar</em>);<br>profileMenu = (ImageView) view.findViewById(R.id.<em>profileMenu</em>);<br>bottomNavigationView = (BottomNavigationViewEx) view.findViewById(R.id.<em>bottomNavViewBar</em>);</pre><p>然後到ProfileActivity複製setupToolBar跟setupBottomNavigationView兩個method過來，接著回到ProfileFragment宣告相關的變數</p><pre>private static final int <em>ACTIVITY_NUM </em>= 4;</pre><p>跟</p><pre>private Context mContext;</pre><p>兩個method只做了一些小改動，詳細請參照下面</p><p>ProfileFragment.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/402a4bfb730269f614e1871903682934/href">https://medium.com/media/402a4bfb730269f614e1871903682934/href</a></iframe><p>接著到onCreateView呼叫這兩個method就完成這一部份了。</p><h3>畫面截圖</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGyzrgl4Fox-hplUubmWWA.gif" /></figure><h3>影片</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLgCYzUzKIBE9XqkckEJJA0I1wVKbUAOdv%26start%3D0&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dwii1svFW8d8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fwii1svFW8d8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e513b02a1ce0050fdd5120f061929f02/href">https://medium.com/media/e513b02a1ce0050fdd5120f061929f02/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d840fbdfca3c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/%E7%AD%86%E8%A8%98-build-an-instagram-clone-profile-fragment-setup-part-30-d840fbdfca3c">[筆記] Build an Instagram Clone — Profile Fragment Setup (Part 30)</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93">工程師與貓</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[筆記] Build an Instagram Clone — Firebase User Signout (Part 28)]]></title>
            <link>https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/%E7%AD%86%E8%A8%98-build-an-instagram-clone-firebase-user-signout-part-28-b4cdff711e66?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4cdff711e66</guid>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 02:22:35 GMT</pubDate>
            <atom:updated>2018-07-17T02:22:35.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh9ZtmHno6WllrN3NUqFhg.png" /></figure><p>首先到res/layout底下的fragment_signout.xml做畫面的配置</p><p>fragment_signout.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dd7807a85d77810ed00259ef066b149/href">https://medium.com/media/2dd7807a85d77810ed00259ef066b149/href</a></iframe><p>接著到Profile資料夾底下的SignOutFragment先新增幾個全域變數</p><p>SignOutFragment.java</p><pre>// firebase<br>private FirebaseAuth mAuth;<br>private FirebaseAuth.AuthStateListener mAuthListener;<br>private ProgressBar mProgressBar;<br>private TextView tvSignout, tvSigningout;</pre><p>接著在底下的onCreateView宣告這幾個變數</p><p>SignOutFragment.java</p><pre>tvSignout = (TextView) view.findViewById(R.id.tvConfirmSignout);<br>mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar);<br>tvSigningout = (TextView) view.findViewById(R.id.tvSigningout);<br>Button btnConfirmSingout = (Button) view.findViewById(R.id.btnConfirmSignout);</pre><pre>mProgressBar.setVisibility(View.GONE);</pre><pre>tvSigningout.setVisibility(View.GONE);</pre><p>然後先到Home資料夾底下的HomeActivity複製所有Firebase的程式碼, 將它貼到onCreateView的下方</p><p>SignOutFragment.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce2550fd1b38b2a2a957173df0fcb69f/href">https://medium.com/media/ce2550fd1b38b2a2a957173df0fcb69f/href</a></iframe><p>將checkCurrentUser刪除, 底下有呼叫到這函式的也一併刪除. 接著在setupFirebaseAuth宣告mAuthListener, 當AuthState狀態改變時, AuthStateListener會抓到這個狀態, 將畫面導回到LoginActivity登入畫面, 然後回到登入畫面前我們需要將Activity clear掉, 不然我們登出在按返回鍵的話, 程式還是會導回到之前登入的畫面.</p><p>SignOutFragment.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6de06bfa985d96603f6cd07b9efbae0e/href">https://medium.com/media/6de06bfa985d96603f6cd07b9efbae0e/href</a></iframe><p>到這邊就完成了影片中所介紹的部分, 不過我在輸入密碼的時候發現密碼顯示不是*符號, 所以回到res/layout,activity_login將password的type改成正確的</p><p>activity_login.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e836d5ea44829a32ad81289299298bbd/href">https://medium.com/media/e836d5ea44829a32ad81289299298bbd/href</a></iframe><h3>畫面截圖</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GR6tJ_MUaJ6L5XNdAiCcQ.gif" /></figure><h3>影片</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrScEX_w4Z0Y%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrScEX_w4Z0Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrScEX_w4Z0Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e6416dfe5ba39934c156535bfae7406/href">https://medium.com/media/3e6416dfe5ba39934c156535bfae7406/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4cdff711e66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93/%E7%AD%86%E8%A8%98-build-an-instagram-clone-firebase-user-signout-part-28-b4cdff711e66">[筆記] Build an Instagram Clone — Firebase User Signout (Part 28)</a> was originally published in <a href="https://medium.com/%E5%B7%A5%E7%A8%8B%E5%B8%AB%E8%88%87%E8%B2%93">工程師與貓</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Note] Build an Instagram Clone — Profile Fragment (Part 29)]]></title>
            <link>https://medium.com/engineer-cat/note-build-an-instagram-clone-profile-fragment-part-29-98c15f5258a1?source=rss-f9d1014a9ffb------2</link>
            <guid isPermaLink="false">https://medium.com/p/98c15f5258a1</guid>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Yu]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 02:15:10 GMT</pubDate>
            <atom:updated>2018-07-17T02:15:10.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh9ZtmHno6WllrN3NUqFhg.png" /></figure><p>This video mainly focuses on refactor ProfileActivity part, because the author thinks the previous architect is bad design, so he would like to redesign the Profile part before moving to process data.</p><h3>Code</h3><h4>fragment_profile.xml</h4><p>So let’s get started to the code. First, add a new Layout resource file under res/layout directory, the new file names fragment_profile.xml, then copy all the content in activity_profile.xml into this new layout file. The author’s thought is to inject this fragment_profile.xml into activity_profile.xml. So in the code we just copied, change the CoordinatorLayout to RelativeLayout.</p><p>Then change the first nested RelativeLayout’s properties layout_weight to wrap content, this layout is designed to contain personal information, for example, the number of posts, following people, and followed people. And give the RelativeLayout an id relLayout1, then we can arrange following content by this id. Then open layout_center_profile.xml, cut the snippet_top_profilebar part and delete the while Top Section, and then back to the RelativeLayout put the profilebar. Here we finish the top section of the layout.</p><p>The top section’s code is as below</p><pre>&lt;RelativeLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:id=&quot;@+id/relLayout1&quot;&gt;</pre><pre>    &lt;include layout=&quot;@layout/snippet_top_profilebar&quot;/&gt;</pre><pre>&lt;/RelativeLayout&gt;</pre><p>Next type a new RelativeLayout，put the previous copied code</p><pre>&lt;include layout=&quot;@layout/layout_center_profile&quot; /&gt;</pre><p>in the RelativeLayout，then use layout_below put this RelativeLayout under the top RelativeLayout.</p><pre>&lt;RelativeLayout<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_below=&quot;@+id/relLayout1&quot;<br>    android:id=&quot;@+id/relLayout2&quot;&gt;</pre><pre>    &lt;include layout=&quot;@layout/layout_center_profile&quot;/&gt;</pre><pre>&lt;/RelativeLayout&gt;</pre><p>Then put the original ProgressBar and layout_bottom_navigation_view below this RelativeLayout, here we finish the fragment_profile.</p><p>The complete code sees below</p><p>fragment_profile.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a110032cc200f71bfe7373d8780f68d/href">https://medium.com/media/2a110032cc200f71bfe7373d8780f68d/href</a></iframe><h4>ProfileFragment.java</h4><p>Go to Profile directory in java src folder, new a Java class, give a name ProfileFragment, open it and extends its class to Fragment. Then add a new override method onCreate. Inside the onCreate method, declare a view, and use inflater to fragment_Profile.</p><p>ProfileFragment.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a18c7f78fd659d6f6953119d84316e22/href">https://medium.com/media/a18c7f78fd659d6f6953119d84316e22/href</a></iframe><h4>activity_profile.xml</h4><p>Delete the content inside the RelativeLayout, just put the FrameLayout, the height and width set to match_parent, and give a id container</p><p>activity_profile.xml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f9e08be0c70cd7456aa768fb10f82c5/href">https://medium.com/media/9f9e08be0c70cd7456aa768fb10f82c5/href</a></iframe><p>Before move to to the next section, go to res/values/strings.xml and add a new string</p><pre>&lt;string name=&quot;profile_fragment&quot;&gt;Profile&lt;/string&gt;</pre><h4>ProfileActivity.java</h4><p>First, comment out all the methods except the onCreate method, then create a new method called init , and set up the profile fragment</p><pre>private void init(){<br>    Log.<em>d</em>(<em>TAG</em>, &quot;init: inflating &quot; + getString(R.string.<em>profile_fragment</em>));</pre><pre>    ProfileFragment fragment = new ProfileFragment();<br>    android.support.v4.app.FragmentTransaction transaction = ProfileActivity.this.getSupportFragmentManager().beginTransaction();<br>    transaction.replace(R.id.<em>container</em>, fragment);<br>    transaction.addToBackStack(getString(R.string.<em>profile_fragment</em>));<br>    transaction.commit();<br>}</pre><p>Then call this init method in the onCreate, and comment out all the other methods. Then we call test out the program.</p><p>ProfileActivity.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b316052087a54bc0748ef9c3eca14d5b/href">https://medium.com/media/b316052087a54bc0748ef9c3eca14d5b/href</a></iframe><h3>ScreenShot</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BtDWkAImWXVcC7tswZXqw.gif" /></figure><h3>Video</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLgCYzUzKIBE9XqkckEJJA0I1wVKbUAOdv%26start%3D0&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2q6wpSc_Dus&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2q6wpSc_Dus%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b035b68409295fa82e6a16d10a4a0f/href">https://medium.com/media/c5b035b68409295fa82e6a16d10a4a0f/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98c15f5258a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/engineer-cat/note-build-an-instagram-clone-profile-fragment-part-29-98c15f5258a1">[Note] Build an Instagram Clone — Profile Fragment (Part 29)</a> was originally published in <a href="https://medium.com/engineer-cat">Engineer&amp;Cat</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>