<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[joshskeen.com]]></title><description><![CDATA[Josh Skeen's personal web page, where i talk about Kotlin, Java, and Android Software development, as well as other code, music, and art projects. ]]></description><link>http://joshskeen.com/</link><generator>Ghost 0.11</generator><lastBuildDate>Tue, 09 Mar 2021 19:15:49 GMT</lastBuildDate><atom:link href="http://joshskeen.com/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Drop the temp!]]></title><description><![CDATA[<p>In classic Java, it is a common idiom to set up a temp variable to hold some value, populate it in a for loop (often after checking some condition for values to add), and then subsequently return the temp variable: </p>

<pre><code class="language-java">public List&lt;Person&gt; getFilteredUsers(List&lt;Person&gt;</code></pre>]]></description><link>http://joshskeen.com/drop-the-temp-2/</link><guid isPermaLink="false">07d0cd61-4402-4db5-b74b-836a1a39f627</guid><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Wed, 03 Mar 2021 22:20:21 GMT</pubDate><content:encoded><![CDATA[<p>In classic Java, it is a common idiom to set up a temp variable to hold some value, populate it in a for loop (often after checking some condition for values to add), and then subsequently return the temp variable: </p>

<pre><code class="language-java">public List&lt;Person&gt; getFilteredUsers(List&lt;Person&gt; personsToFilter) {  
    List&lt;Person&gt; result = new ArrayList&lt;&gt;();
    for(person : personsToFilter) {
        if(person.getAge() &gt;= 15 &amp;&amp; person.getJobTitle().equals("Developer")) {
            result.add(person);
        }
    }
    return result;
}
</code></pre>

<p>When migrating to Kotlin, it's understandable then that this "java-flavoured" idiom would stick for developers picking up Kotlin's syntax:</p>

<pre><code class="language-kotlin">fun getFilteredUsers(personsToFilter: List&lt;Person&gt;): List&lt;Person&gt; {  
    val result = mutableListOf&lt;Person&gt;()
    for(person in personsToFilter) {
       if(person.age &gt;= 15 &amp;&amp; person.jobTitle == "Developer") {
           result += person
       }
    }
    return result
}
</code></pre>

<p>Java-flavoured Kotlin code is all too common, and reasonably so. It's part of adopting any new language to work in the style that you are most recently familiar with, and what you know comfortably.</p>

<p>A couple of guiding ideas can help to adopt a Kotlin style when moving from Java: </p>

<ul>
<li>Favor val over var</li>
<li>Favor read-only over mutable</li>
</ul>

<p>With these ideas in mind, you can ask the question: "can i drop the mutable list?". Fortunately, Kotlin has <em>many</em> niceties built into the language to help with exactly these sort of situations, without requiring adding mutable state: </p>

<pre><code class="language-kotlin">fun getFilteredUsers(personsToFilter: List&lt;Person&gt;): List&lt;Person&gt; {  
    return personsToFilter.filter { it.age &gt;= 15 &amp;&amp; it.jobTitle == "Developer" }
}
</code></pre>

<p>Ah! Much better. The Kotlin filter operator accepts the left-hand collection, creating a new collection with any element that matches the condition you specify in the {}'s. Now you've accomplished the same work, without requiring declaring a temp. If you find yourself declaring a temp variable in Kotlin, chances are a function on iterable exists to handle exactly the problem you're facing. </p>

<p>Now, you might be thinking "yes, this is cool - but, what if this were a more complicated situation - like a map for example?" Fortunately Kotlin's collection api has many goodies baked in with these further complicated situations in mind. For example, what if getFilteredUsers should return a map of user's age associated with user instead? Let's see that in the Old Java style: </p>

<pre><code class="language-java">public Map&lt;Integer, Person&gt; getFilteredUsers(List&lt;Person&gt; personsToFilter) {  
    Map&lt;Integer, Person&gt; result = new HashMap&lt;&gt;();
    for (Person person : personsToFilter) {
        if(person.getAge() &gt;= 15 &amp;&amp; person.getJobTitle().equals("Developer")) {
            result.put(person.getAge(), person);
        }
    }
    return result;
}
</code></pre>

<p>Fortunately, Kotlin has you covered for these (and far more complicated) cases as well!</p>

<pre><code class="language-kotlin">fun getFilteredUsers(personsToFilter: List&lt;Person&gt;): Map&lt;Int, Person&gt; {  
    return personsToFilter.filter { it.age &gt;= 15 &amp;&amp; it.jobTitle == "Developer" }
            .associateBy { it.age }
}
</code></pre>

<p>By the way, now that your statement is written as expression, you can flex an extra benefit of the Kotlin language and convert that function to a <em>single-expression function</em>:</p>

<pre><code class="language-kotlin">fun getFilteredUsers(personsToFilter: List&lt;Person&gt;) =  
    personsToFilter.filter { it.age &gt;= 15 &amp;&amp; it.jobTitle == "Developer" }.associateBy { it.age }
</code></pre>

<p>Whenever you declare a temp variable in Kotlin, let it trigger the thought: can I use the collections API instead to solve this without a temp or mutable state? Chances are, the answer is "yes!"</p>]]></content:encoded></item><item><title><![CDATA[Kotlin Riddler: Legit Syntax?]]></title><description><![CDATA[<p>will the following compile?</p>

<pre><code class="language-kotlin">class Qaz {  
    var bar = "hey"
}
class Foo(private var qaz: Qaz?) {  
    fun assignBarMkayyy() {
        if (qaz != null) {
            qaz.bar = "hey!"
        }
    }
}
</code></pre>]]></description><link>http://joshskeen.com/kotlin-riddler-legit-syntax/</link><guid isPermaLink="false">ac258d4e-0074-45c0-b540-eaec95708990</guid><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Wed, 13 Dec 2017 18:24:42 GMT</pubDate><content:encoded><![CDATA[<p>will the following compile?</p>

<pre><code class="language-kotlin">class Qaz {  
    var bar = "hey"
}
class Foo(private var qaz: Qaz?) {  
    fun assignBarMkayyy() {
        if (qaz != null) {
            qaz.bar = "hey!"
        }
    }
}
</code></pre>]]></content:encoded></item><item><title><![CDATA[How to get Kotlin JS to work with JQuery (or other external libraries)]]></title><description><![CDATA[<p>If you have tried to get external javascript libraries working with Kotlin (when compiling to javascript) it can be somewhat puzzling to get external libraries to work with Kotlin while at the same time being typesafe. <br>
Kotlin provides <a href="https://kotlinlang.org/docs/reference/dynamic-type.html">https://kotlinlang.org/docs/reference/dynamic-type.html</a> to work around this, but</p>]]></description><link>http://joshskeen.com/how-to-get-kotlin-js-to-work-with-jquery-or-other-external-libraries/</link><guid isPermaLink="false">2da93f98-4d7a-4a22-a202-f3a73fb94127</guid><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Fri, 17 Nov 2017 22:03:51 GMT</pubDate><content:encoded><![CDATA[<p>If you have tried to get external javascript libraries working with Kotlin (when compiling to javascript) it can be somewhat puzzling to get external libraries to work with Kotlin while at the same time being typesafe. <br>
Kotlin provides <a href="https://kotlinlang.org/docs/reference/dynamic-type.html">https://kotlinlang.org/docs/reference/dynamic-type.html</a> to work around this, but this sort of defeats the point of using the static language IMO. A nicer option exists: generate a header for the javascript file that kotlin can apply typechecking to. Here are the steps involved. Github repo for the example is at the bottom of the article.</p>

<ul>
<li><em>curl <a href="https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/index.d.ts">https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/jquery/index.d.ts</a> > jquery.d.ts</em></li>
<li>install the typescript-to-kotlin converter: <em>npm -g install ts2kt</em> ( <a href="https://github.com/Kotlin/ts2kt">https://github.com/Kotlin/ts2kt</a> )  </li>
<li>convert jquery.d.ts to jquery.kt by running ts2kt -d headers jquery.d.ts  </li>
<li>create a new kotlin project and target js for the runtime  </li>
<li>within the src directory in your project, create 2 packages: <em>jslibs</em> and <em>jsheaders</em>  </li>
<li>download <em>jquery.js</em> from <a href="https://jquery.com/download/">https://jquery.com/download/</a> and place it in <em>jslibs</em>  </li>
<li>move the <em>jquery.kt</em> header file you generated (should be in the headers dir where you ran ts2kt) to <em>jsheaders</em>  </li>
<li>create a new html file within the Kotlin project. the project should have an index.html file at the top level that includes the following:  </li>
</ul>

<pre><code class="language-xml">&lt;!DOCTYPE html&gt;  
&lt;html lang="en"&gt;  
&lt;head&gt;  
    &lt;meta charset="UTF-8"&gt;
    &lt;title&gt;kotlinjquerytest&lt;/title&gt;
&lt;/head&gt;  
&lt;body&gt;

&lt;script type="text/javascript" src="out/production/{name of project}/lib/kotlin.jslibs"&gt;&lt;/script&gt;  
&lt;script type="text/javascript" src="out/production/{name_of_project}/jslibs/jquery-3.2.1.min.jslibs"&gt;&lt;/script&gt;  
&lt;script type="text/javascript" src="out/production/{name_of_project}/{name_of_project}.jslibs"&gt;&lt;/script&gt;  
&lt;div id="app" style="width:200px; height: 200px;border:1px solid red;"&gt;&lt;/div&gt;  
&lt;/body&gt;  
&lt;/html&gt;  
</code></pre>

<p>make sure to change name<em>of</em>project to... the name of the project you chose</p>

<ul>
<li>create a kotlin file within source called Main.kt with the following:</li>
</ul>

<pre><code class="language-kotlin">fun jQuery(x: String) = jQuery(x, null as JQuery?)

fun main(args: Array&lt;String&gt;) {  
    jQuery {
        Main.doApp()
    }
}

object Main {  
    fun doApp() {
        val jQuery1 = jQuery("#app")
        jQuery1[0]?.innerHTML = "&lt;p&gt;hey!&lt;/p&gt;"
    }
}
</code></pre>

<ul>
<li>double click the index.html file</li>
<li>at the top right, select a browser icon to open the file  </li>
<li>congrats!</li>
</ul>

<p>Download the example project at: <a href="http://github.com/mutexkid/kotlinjquerytest">http://github.com/mutexkid/kotlinjquerytest</a></p>]]></content:encoded></item><item><title><![CDATA[how to implement an anonymous abstract class in Kotlin]]></title><description><![CDATA[<p>TIL how to implement an anonymous abstract class in Kotlin. This is something you do all the time in Java with Android for example, when an interface calls for a single abstract method implementation. Consider the following Java code for example. </p>

<pre><code class="language-java">abstract class Foobar {  
  abstract String foo();
}

Foobar = new Foobar(</code></pre>]]></description><link>http://joshskeen.com/how-to-implement-an-anonymous-abstract-class-in-kotlin/</link><guid isPermaLink="false">1a8e5b7d-8b40-4b66-8a1e-7a3ec7101eed</guid><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Thu, 29 Jun 2017 19:10:29 GMT</pubDate><content:encoded><![CDATA[<p>TIL how to implement an anonymous abstract class in Kotlin. This is something you do all the time in Java with Android for example, when an interface calls for a single abstract method implementation. Consider the following Java code for example. </p>

<pre><code class="language-java">abstract class Foobar {  
  abstract String foo();
}

Foobar = new Foobar() {  
    @Override
    String foo() {
      return "foo!";
    }
}
</code></pre>

<p>In Kotlin, the syntax proved a bit more tricky to track down - easily doable, just slightly elusive:</p>

<pre><code class="language-kotlin">abstract class Foobar {  
    abstract fun foo(): String
}

class UsesFoo {  
    fun foo(foo:Foobar) {
        println(foo)
    }
}

fun main(args: Array&lt;String&gt;) {  
    UsesFoo().foo(object: Foobar() {
        override fun foo(): String {
            return "foo!"
        }
    })
}
</code></pre>

<p>Notice the "object:" portion of the above code? </p>]]></content:encoded></item><item><title><![CDATA[Keeping Android Secrets Secure with Fingerprint Authentication and the Keystore]]></title><description><![CDATA[<p>I spoke at DevNexus 2017 about how to get cryptography right on Android, and how to work with the fingerprint API to ensure robust security is in place ,especially for apps that need to store authentication details (like an authentication token). </p>

<p><strong>title:</strong> Keeping Android Secrets Secure with Fingerprint Authentication and</p>]]></description><link>http://joshskeen.com/keeping-android-secrets-secure-with-fingerprint-authentication-and-the-keystore/</link><guid isPermaLink="false">b8ce4c7b-4df6-4286-92a9-c86d62785db4</guid><category><![CDATA[Android]]></category><category><![CDATA[java]]></category><category><![CDATA[security]]></category><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Tue, 27 Jun 2017 03:29:08 GMT</pubDate><content:encoded><![CDATA[<p>I spoke at DevNexus 2017 about how to get cryptography right on Android, and how to work with the fingerprint API to ensure robust security is in place ,especially for apps that need to store authentication details (like an authentication token). </p>

<p><strong>title:</strong> Keeping Android Secrets Secure with Fingerprint Authentication and the Keystore</p>

<p><strong>description:</strong> Getting cryptography right on Android is challenging. There are code examples without much explanation about what is really going on.
In this talk you will learn the details you need to implement a subset of Android security: user authorization. <br>
We will discuss how to implement robust user authorization using the new Fingerprint API and the Android Keystore, <br>
and we will explore how to correctly use the Keystore to keep your application secrets secure. </p>

<p>Here are the slides from my <a href="http://https://www.devnexus.com/s/speakers/17984">DevNexus 2017 Presentation</a> entitled "Keeping Android Secrets Secure with Fingerprint Authentication and the Keystore".  </p>

<script async class="speakerdeck-embed" data-id="ae113f22c51a474ba09bdadeb11750af" data-ratio="1.77777777777778" src="//speakerdeck.com/assets/embed.js"></script>

<p>Github code here: <a href="https://github.com/bignerdranch/android-securebank">android securebank example</a></p>]]></content:encoded></item><item><title><![CDATA[Kotlin's invoke operator]]></title><description><![CDATA[<p>An interesting feature of the Kotlin language is the ability to define an "invoke operator". When you specify an invoke operator on a class, it can be called on any instances of the class without a method name! <br>
This trick seems especially useful for classes that really only have one</p>]]></description><link>http://joshskeen.com/kotlins-invoke-operator/</link><guid isPermaLink="false">4a4b0885-03eb-4a18-a594-2aad2122e520</guid><category><![CDATA[kotlin]]></category><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Mon, 26 Jun 2017 20:36:44 GMT</pubDate><content:encoded><![CDATA[<p>An interesting feature of the Kotlin language is the ability to define an "invoke operator". When you specify an invoke operator on a class, it can be called on any instances of the class without a method name! <br>
This trick seems especially useful for classes that really only have one method to be used. </p>

<p>For example, consider the following example:</p>

<pre><code class="language-kotlin">class Socket  
class UrlScraper(val socket: Socket) {

    inner class ParseResult

    operator fun invoke(url: String): List&lt;ParseResult&gt; {
        //do cool stuff here with the url
        //eventually produces a list of ParseResult objects
        return listOf(ParseResult(), ParseResult())
    }
}
</code></pre>

<p>Once you specify the <span class="token property">invoke</span> operator, <span class="token property">UrlScraper</span> can perform it's work without any need for calling a method on it, since it does only one thing - scrapes a url! You can now simply pass the url to the instance like so:</p>

<pre><code class="language-kotlin">fun main(args: Array&lt;String&gt;) {  
    val urlScraper = UrlScraper(Socket())
    urlScraper("www.google.com") //calls the invoke method you specified
}
</code></pre>

<p>I really like this trick, especially for classes that have just one public method - a <span class="token property">perform</span> method, for example - since it further simplifies how the API can be used.</p>]]></content:encoded></item><item><title><![CDATA[How to build a single-choice RecyclerView]]></title><description><![CDATA[<p>In this article, i'll walk through one way to build a single-choice RecyclerView in Android. This will result in a general purpose RecyclerView-based component that mimics a typical "radio group" component you may be familiar with from html. This gives you a list of radiobuttons with one selection maximum. </p>

<p><span class="token property">RadioAdapter.</span></p>]]></description><link>http://joshskeen.com/building-a-radiogroup-recyclerview/</link><guid isPermaLink="false">914963fa-09d5-4d3e-93e8-163a90b6bf1d</guid><category><![CDATA[Android]]></category><category><![CDATA[java]]></category><category><![CDATA[kotlin]]></category><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Wed, 22 Apr 2015 04:57:00 GMT</pubDate><content:encoded><![CDATA[<p>In this article, i'll walk through one way to build a single-choice RecyclerView in Android. This will result in a general purpose RecyclerView-based component that mimics a typical "radio group" component you may be familiar with from html. This gives you a list of radiobuttons with one selection maximum. </p>

<p><span class="token property">RadioAdapter.java</span>  </p>

<pre><code class="language-java">public abstract class RadioAdapter&lt;T&gt; extends RecyclerView.Adapter&lt;RadioAdapter.ViewHolder&gt; {  
    public int mSelectedItem = -1;
    public List&lt;T&gt; mItems;
    private Context mContext;

    public RadioAdapter(Context context, List&lt;T&gt; items) {
        mContext = context;
        mItems = items;
    }

    @Override
    public void onBindViewHolder(RadioAdapter.ViewHolder viewHolder, final int i) {
        viewHolder.mRadio.setChecked(i == mSelectedItem);
    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(mContext);
        final View view = inflater.inflate(R.layout.view_item, viewGroup, false);
        return new ViewHolder(view);
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        public RadioButton mRadio;
        public TextView mText;

        public ViewHolder(final View inflate) {
            super(inflate);
            mText = (TextView) inflate.findViewById(R.id.text);
            mRadio = (RadioButton) inflate.findViewById(R.id.radio);
            View.OnClickListener clickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectedItem = getAdapterPosition();
                    notifyDataSetChanged();
                }
            };
            itemView.setOnClickListener(clickListener);
            mRadio.setOnClickListener(clickListener);
        }
    }
}
</code></pre>

<p>A generic view for displaying a radiobutton and title: <br>
<span class="token property">view_item.xml</span>  </p>

<pre><code class="language-html">&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="horizontal"&gt;

    &lt;RadioButton
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        /&gt;

    &lt;TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        /&gt;
&lt;/LinearLayout&gt;  
</code></pre>

<p>To actually use this abstract class, subclass it and construct with your specific data. Also, implement onBindViewHolder to do the specific data set up for your backing model:</p>

<p><span class="token property">PersonAdapter.java</span>  </p>

<pre><code class="language-java">public class PersonAdapter extends RadioAdapter&lt;Person&gt; {  
    public PersonAdapter(Context context, List&lt;Person&gt; items){
        super(context, items);        
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int i) {
        super.onBindViewHolder(viewHolder, i);
        viewHolder.mText.setText(mItems.get(i).mLocationName);
    }    
}
</code></pre>

<p>Just for sake of demonstration, the Person object in all its glory: <br>
<span class="token property">Person.java</span>  </p>

<pre><code class="language-java">class Person{  
    public String mName;
    public Person(String name){
        mName = name;
    }
}
</code></pre>

<p>Finally, let's set it up! <br>
<span class="token property">MainActivity.java</span>  </p>

<pre><code class="language-java">@Override
public View onCreate(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
    setContentView(R.layout.activity_main);
    RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
    List&lt;Person&gt; persons = Arrays.asList(new Person("Larry"), 
                  new Person("Moe"), 
                  new Person("Curly"));
    //basic yak shaving required
    recyclerView.setLayoutManager(new LinearLayoutManager(this));    
    recyclerView.setAdapter(new PersonAdapter(this, persons));
}
</code></pre>

<p>Here's what it looks like: <br>
<img src="http://joshskeen.com/content/images/2015/04/r4mhZd3Izr.gif" alt=""></p>

<p>Download the source here <a href="https://github.com/mutexkid/radiogroup-recyclerview">at github</a></p>

<h2 id="update">Update</h2>

<p>For the Kotlin fans, i've added an updated version of the code  example here: <br>
<a href="https://github.com/mutexkid/kotlin-radio-group-example">https://github.com/mutexkid/kotlin-radio-group-example</a> . </p>

<h2 id="test">Test</h2>]]></content:encoded></item><item><title><![CDATA[Implementing Swipe to Refresh, a Material Design UI Pattern]]></title><description><![CDATA[<p>One of the great ideas formalized in the new Material Design user interface guidelines is the <a href="http://www.google.com/design/spec/patterns/swipe-to-refresh.html">Swipe to Refresh UI pattern</a>. In fact, you’ve probably already seen and used the Swipe to Refresh pattern. It's found its way into many popular Android apps like Facebook, Google Newsstand, Trello, Gmail</p>]]></description><link>http://joshskeen.com/implementing-swipe-to-refresh-a-material-design-ui-pattern/</link><guid isPermaLink="false">73c2300a-8555-4de0-9017-50c03ec331ac</guid><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Fri, 06 Feb 2015 16:46:07 GMT</pubDate><content:encoded><![CDATA[<p>One of the great ideas formalized in the new Material Design user interface guidelines is the <a href="http://www.google.com/design/spec/patterns/swipe-to-refresh.html">Swipe to Refresh UI pattern</a>. In fact, you’ve probably already seen and used the Swipe to Refresh pattern. It's found its way into many popular Android apps like Facebook, Google Newsstand, Trello, Gmail and many others. </p>

<p>Here's what it looks like: <br>
<img src="http://wwww.joshskeen.com/content/images/2014/12/FdQupwLg41.gif" alt="catnames gif"></p>

<p>The Swipe to Refresh pattern is a nice fit for adapter-backed views (<a href="http://www.bignerdranch.com/blog/recyclerview-part-1-fundamentals-for-listview-experts/">RecyclerView and ListView</a>, for example) that also need to support user-requested refreshes, like a list that displays a Twitter newsfeed that’s updated by a user, on demand. </p>

<p>Introduced alongside KitKat and enhanced with the Lollipop release of the v4 Android support library, a working implementation of the <a href="http://www.google.com/design/spec/patterns/swipe-to-refresh.html">Swipe-to-refresh UI pattern</a> is included, called SwipeRefreshLayout . All we have to do is set it up! For your reference, the project we'll build is <a href="http://github.com/mutexkid/swipe-to-refresh-demo">available for download on github here</a>.</p>

<h2 id="settingupswipetorefresh">Setting up Swipe To Refresh</h2>

<p>We begin implementing the Swipe-to-Refresh pattern with a brand new Android Studio project and the most recent version of the Android Support Library (your SDK manager should show an Android Support Library version of at least 21.0). </p>

<p>The first thing we need to do is add the support library to our application’s <code>build.gradle</code> file.</p>

<pre><code class="language-javascript">compile 'com.android.support:support-v4:21.0.+'  
</code></pre>

<p>Gradle sync your project and open the layout file that was generated when we created our first Activity from the new project wizard, named <code>res/layouts/activity_main.xml</code>. We're going to add a ListView and a SwipeRefreshLayout widget to the layout file. The ListView will display content we want to update using the Swipe to Refresh pattern, and the SwipeRefreshLayout widget will provide the basic functionality.</p>

<pre><code class="language-xml"> &lt;android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/activity_main_swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"&gt;

        &lt;ListView
            android:id="@+id/activity_main_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            &gt;
        &lt;/ListView&gt;

    &lt;/android.support.v4.widget.SwipeRefreshLayout&gt;
</code></pre>

<p>Notice that ListView is nested within the SwipeRefreshLayout. Any time we swipe the ListView beyond the edge of the SwipeRefreshLayout, the SwipeRefreshLayout widget will display a loading icon and trigger an onRefresh event. This event is a hook for adding our own on-demand data refresh behavior for the list.</p>

<h2 id="wiringuptheadapter">Wiring up the Adapter</h2>

<p>Now that we've got our layout file ready, let's set up a simple data adapter. In real life, our adapter would likely be backed by a web service, remote API or database, but to keep things simple we’ll fake a web API response. Include the following xml snippet in your <span class="token property">res/strings.xml</span> file: </p>

<pre><code class="language-xml">&lt;string-array name="cat_names"&gt;  
    &lt;item&gt;George&lt;/item&gt;
    &lt;item&gt;Zubin&lt;/item&gt;
    &lt;item&gt;Carlos&lt;/item&gt;
    &lt;item&gt;Frank&lt;/item&gt;
    &lt;item&gt;Charles&lt;/item&gt;
    &lt;item&gt;Simon&lt;/item&gt;
    &lt;item&gt;Fezra&lt;/item&gt;
    &lt;item&gt;Henry&lt;/item&gt;
    &lt;item&gt;Schuster&lt;/item&gt;
&lt;/string-array&gt;  
</code></pre>

<p>and set up an adapter to fake out new responses from the “cat names web API ” for our experiment.</p>

<pre><code class="language-java">class MainActivity extends Activity {

  ListView mListView;
  SwipeRefreshLayout mSwipeRefreshLayout;
  Adapter mAdapter;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.acivity_main);
    SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);
    mListView = findViewById(R.id.activity_main_list_view);
 mListView.setAdapter(new ArrayAdapter&lt;String&gt;(){
    String[] fakeTweets = getResources().getStringArray(R.array.fake_tweets);
    mAdapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_list_item_1, fakeTweets)
    listView.setAdapter(mAdapter);
  });
  }
}
</code></pre>

<h2 id="definingourdatarefresh">Defining our Data Refresh</h2>

<p>Now that our adapter is set up, we can wire up the refresh triggered by swiping down. We'll get an animated loading indicator already "for free"; we just need to define what happens to our ListView. We will do that by defining the SwipeRefreshLayout widget's expected OnRefreshListener interface. We'll also simulate getting new data back from the CatNames webservice (we'll build a method called <span class="token property">getNewCatNames()</span> that will build an array of randomly shuffled fake responses from the cat names API). </p>

<pre><code class="language-java">@Override
  public void onCreate(Bundle savedInstanceState) {
  …
    listView.setAdapter();
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override
      public void onRefresh() {
            refreshContent();
          ...
  }

  // fake a network operation's delayed response 
  // this is just for demonstration, not real code!
  private void refreshContent(){ 
    new Handler().postDelayed(new Runnable() {
          @Override
          public void run() {
    mAdapter = new ArrayAdapter&lt;String&gt;(MainActivity.this, android.R.layout.simple_list_item_1, getNewTweets());
    mListView.setAdapter(mAdapter);
    mSwipeRefreshLayout.setRefreshing(false);
    });
  }

  // get new cat names. 
  // Normally this would be a call to a webservice using async task,
  // or a database operation

 private List&lt;String&gt; getNewCatNames() {
        List&lt;String&gt; newCatNames = new ArrayList&lt;String&gt;();
        for (int i = 0; i &lt; mCatNames.size(); i++) {
            int randomCatNameIndex = new Random().nextInt(mCatNames.size() - 1);
            newCatNames.add(mCatNames.get(randomCatNameIndex));
        }
        return newCatNames;
    }
</code></pre>

<p>Notice the last line in <span class="token property">refreshContent()</span> in the previous listing: <span class="token property">setRefreshing(false);</span> This notifies the SwipeRefreshLayout widget instance that the work we wanted to do in <span class="token property">onRefresh</span> completed, and to stop displaying the loader animation. </p>

<p>Now, try running your app. Try swiping the ListView down and verify that the SwipeRefreshLayout loading icon displays, is dismissed, and that new tweets are loaded into the ListView. Congratulations, you've implemented the Swipe-to-Refresh pattern in your app!</p>

<h2 id="customization">Customization</h2>

<p>You can also customize SwipeRefreshLayout’s appearance. To define your own custom color scheme to use with SwipeRefreshLayout's animated loading icon, use the appropriately named <span class="token property">setColorSchemeResources()</span> method. This takes a varargs of color resource ids.</p>

<p>First, define colors you want to appear in the SwipeRefreshLayout's animated loader:  </p>

<pre><code class="language-xml">&lt;resources&gt;  
    &lt;color name="orange"&gt;#FF9900&lt;/color&gt;
    &lt;color name="green"&gt;#009900&lt;/color&gt;
    &lt;color name="blue"&gt;#000099&lt;/color&gt;
&lt;/resources&gt;  
</code></pre>

<p>Then call <code>setColorSchemeResources(R.color.orange, R.color.green, R.color.blue);</code> in the <code>onCreate</code> portion of your activity, after the SwipeRefreshLayout is loaded. <br>
Deploy your program and notice the customized colors the swipe animation now uses: <br>
<img src="http://wwww.joshskeen.com/content/images/2014/12/catnames_color.gif" alt="catnames, with color!"></p>

<p>SwipeRefreshLayout will rotate through the colors we provided as the loader continues to be displayed. </p>

<p>As you can see from this simple example, Swipe-to-Refresh is a great pattern for simplifying the problem of user-requested data updates in your app. For more info about available API options for SwipeRefreshLayout, check out the official <a href="https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html">Android documentation page</a>.     </p>]]></content:encoded></item><item><title><![CDATA[RxJava Koans - a Functional Reactive Programming learning tool]]></title><description><![CDATA[<p>In my quest to attain an understanding of <a href="http://en.wikipedia.org/wiki/Functional_reactive_programming">Functional Reactive Programming</a>, especially as it relates to Java and android, i've started the <a href="https://github.com/mutexkid/rxjava-koans">rxjava-koans</a> project. The project demonstrates how <a href="https://github.com/ReactiveX/RxJava">RxJava</a> works with the goal of cultivating understanding through initially failing unit tests. Each file of the project shows a different principle</p>]]></description><link>http://joshskeen.com/rxjava-koans-a-functional-reactive-programming-learning-tool/</link><guid isPermaLink="false">41d07e2b-77ec-45f6-99c2-509f08b73467</guid><category><![CDATA[Android]]></category><category><![CDATA[pro]]></category><category><![CDATA[java]]></category><category><![CDATA[functional reactive programming]]></category><category><![CDATA[rxjava]]></category><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Fri, 12 Dec 2014 20:14:31 GMT</pubDate><content:encoded><![CDATA[<p>In my quest to attain an understanding of <a href="http://en.wikipedia.org/wiki/Functional_reactive_programming">Functional Reactive Programming</a>, especially as it relates to Java and android, i've started the <a href="https://github.com/mutexkid/rxjava-koans">rxjava-koans</a> project. The project demonstrates how <a href="https://github.com/ReactiveX/RxJava">RxJava</a> works with the goal of cultivating understanding through initially failing unit tests. Each file of the project shows a different principle of the library. Your task as neophyte FRP disciple is to make the test suite pass (and in the act of doing so, attain <br>
<a href="http://joshskeen.com/content/images/2015/02/B5oIZCXCMAI_vTn.jpg">Reactive Programming Enlightenment</a>!)</p>]]></content:encoded></item><item><title><![CDATA[octatrack tr-8 midi sequencing template]]></title><description><![CDATA[<p>I made a template for the octatrack that sets up the octatrack's midi tracks to use 8 of the TR-8's instruments and also make use of it's Continuous Control mapping values. </p>

<p>To use: </p>

<ol>
<li>set TR-8 MIDI in on channel 8.  </li>
<li>load the TR8_TEMPLATE up on your octatrack  </li>
<li>have fun!</li></ol>]]></description><link>http://joshskeen.com/octatrack-tr-8-midi-sequencing-template/</link><guid isPermaLink="false">b539b3f9-1cf8-44e8-8886-751e67c28508</guid><category><![CDATA[octatrack]]></category><category><![CDATA[tr-8]]></category><category><![CDATA[music]]></category><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Tue, 04 Nov 2014 01:43:40 GMT</pubDate><media:content url="http://joshskeen.com/content/images/2014/11/1097950_10152024560194576_1901034045_n.jpg" medium="image"/><content:encoded><![CDATA[<img src="http://joshskeen.com/content/images/2014/11/1097950_10152024560194576_1901034045_n.jpg" alt="octatrack tr-8 midi sequencing template"><p>I made a template for the octatrack that sets up the octatrack's midi tracks to use 8 of the TR-8's instruments and also make use of it's Continuous Control mapping values. </p>

<p>To use: </p>

<ol>
<li>set TR-8 MIDI in on channel 8.  </li>
<li>load the TR8_TEMPLATE up on your octatrack  </li>
<li>have fun!</li>
</ol>

<p><a href="http://db.orangedox.com/80rAcUYCsXE9bqOZF6/ocatrack_tr8_template.zip">download here</a></p>

<table class="table table-bordered">  
<tr>  
<th>track</th>  
<th>instrument</th>  
<th>page: effect2</th>  
<th>page: effect1</th>  
</tr>  
<tr>  
<td>t1</td>  
<td>BD</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob B: attack</li>
  <li>knob C: comp</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>-</td>  
</tr>

<tr>  
<td>t2</td>  
<td>SD</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob B: snappy</li>
  <li>knob C: comp</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>-</td>  
</tr>

<tr>  
<td>t3</td>  
<td>LT</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>-</td>  
</tr>

<tr>  
<td>t4</td>  
<td>RS</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>-</td>  
</tr>

<tr>  
<td>t5</td>  
<td>HC</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>-</td>  
</tr>  
<tr>  
<td>t6</td>  
<td>CH</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>  
<ol>  
  <li>knob C: accent level</li>
  <li>knob D: scatter mode</li>
  <li>knob E: scatter depth</li>
  <li>knob F: scatter on/off (value 63 & lower = off, > 63 = on)</li>
</ol>  
</td>  
</tr>

<tr>  
<td>t7</td>  
<td>OH</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>  
<ol>  
  <li>knob D: delay level</li>
  <li>knob E: delay time</li>
  <li>knob F: delay feedback</li>
</ol>  
</td>  
</tr>

<tr>  
<td>t8</td>  
<td>CC</td>  
<td>  
<ol>  
  <li>knob A: tune</li>
  <li>knob D: decay</li>
</ol>  
</td>  
<td>  
<ol>  
  <li>knob D: reverb level</li>
  <li>knob E: reverb time</li>
  <li>knob F: reverb gate</li>
</ol>  
</td>  
</tr>

</table>]]></content:encoded></item><item><title><![CDATA[Mocking Webservices with Robolectric & WireMock]]></title><description><![CDATA[<p>At the <a href="http://www.bignerdranch.com">Big Nerd Ranch</a>, we create Android applications that talk to REST APIs (often written in-house by the Rails backend team). To build these projects with confidence, having tests that verify the interaction with the REST service are critical. <br>
I've blogged already about my recommended software test stack and</p>]]></description><link>http://joshskeen.com/mocking-webservices-with-robolectric-wiremock/</link><guid isPermaLink="false">f82c9634-1c8b-4e1c-ae33-f2ddfef9ac81</guid><category><![CDATA[programming]]></category><category><![CDATA[Android]]></category><category><![CDATA[test-driven-development]]></category><dc:creator><![CDATA[Josh Skeen]]></dc:creator><pubDate>Thu, 30 Oct 2014 20:28:07 GMT</pubDate><content:encoded><![CDATA[<p>At the <a href="http://www.bignerdranch.com">Big Nerd Ranch</a>, we create Android applications that talk to REST APIs (often written in-house by the Rails backend team). To build these projects with confidence, having tests that verify the interaction with the REST service are critical. <br>
I've blogged already about my recommended software test stack and setup (have a look at <a href="http://www.bignerdranch.com/blog/testing-the-android-way/">this article</a> for details), but I haven't yet talked about how we can have tests which allow us to interact with our webservices while at the same time keeping our tests fast, and our code simple - that's the point of <em>this</em> article!</p>

<p>First, why not test against the live services themselves? After all, doesn't this ensure nothing broke on the server-side we're dependent upon? While this is certainly true - and it may be that we have a test group of integration tests which do hit the live REST API, we don't want this to be part of our main test suite. A few reasons we will want to "mock" (if you're puzzled by what i mean by "mock" check out <a href="http://en.wikipedia.org/wiki/Mock_object">http://en.wikipedia.org/wiki/Mock_object</a>) these interactions instead:</p>

<ul>
<li>We may have a certain number of requests we're limited to for the api we're using. Every time our tests run, it will weigh against that limit. </li>
<li>Tests that have to hit the remote network to pass or fail will invariably slow our suite down</li>
<li>The service may be down temporarily. We don't want our test suite to fail because the server was rebooted!</li>
</ul>

<hr>

<h3 id="enterwiremock">Enter WireMock</h3>

<p>An easy to use solution for avoiding live requests to actual REST services is to instead mock the responses from the server. I've found a library called called <a href="https://github.com/tomakehurst/wiremock">WireMock</a> that easily facilitates this task. WireMock is designed to allow us to record requests to a webserver, and then programmatically play back those recordings when requests match a particular url pattern. We can define what urls we want WireMock to match in our tests like so: </p>

<pre><code class="language-java">stubFor(get(urlMatching("/api/.*"))  
        .willReturn(aResponse()
        .withStatus(200)
        .withBodyFile("atlanta-conditions.json")));
</code></pre>

<p>It lets us completely avoid building one-off test "Adapter"" objects for our service layer just to support the tests - in other words by using WireMock, we can use the live service classes, but get canned responses that don't hit a live webservice, with a minimum of glue code to support this test behavior!</p>

<hr>

<h3 id="gettingstarted">Getting Started</h3>

<p>With our new Android Studio project, we'll need to define our library dependencies in our project's gradle file. Here's the configuration i'm using - which relies on robolectric as a test runner setup for android. If you don't know how to go about setting this up in Android Studio, i have a boilerplate project for getting that setup right <a href="https://github.com/mutexkid/android-studio-robolectric-example">Here On Github</a></p>

<hr>

<h3 id="gradlesetup">Gradle Setup</h3>

<pre><code class="language-javascript">dependencies {  
    compile 'com.squareup.retrofit:retrofit:1.7.1'
    compile 'com.squareup:dagger:0.9.1'
    provided 'com.squareup:dagger-compiler:0.9.1'
    testCompile 'com.github.tomakehurst:wiremock:1.51:standalone'
    testCompile 'org.robolectric:robolectric:2.3'
    testCompile 'org.easytesting:fest:1.0.16'
    testCompile 'junit:junit:4.+'
    testCompile 'com.squareup:fest-android:1.0.8'
}
</code></pre>

<p>notice <code>testCompile 'com.github.tomakehurst:wiremock:1.51:standalone'</code> - i wasn't able to get wiremock to "play nice" (clashing dependencies) with robolectric without the standalone classifier, so make sure you include it in your gradle dependencies list, as you see above. </p>

<hr>

<h3 id="ourservicelayer">Our Service Layer</h3>

<p>Let's imagine we've got Service Interface and Manager classes that makes a request to Weather Underground to give us the weather data for a particular city. The code example below uses <a href="http://square.github.io/retrofit/">Retrofit</a> to define the webservice endpoints and interface, but if you don't know how retrofit works yet, don't worry too much about it - the focus here is the test setup itself.</p>

<p><code>WeatherServiceInterface.java:</code></p>

<pre><code class="language-java">public interface WeatherServiceInterface {  
    //defines the http method we want to use using retrofit's handy syntax
    //in this case, we want to 
    //hit api.wunderground.com/api/APIKEY/conditions/q/CA/Atlanta
    @GET("/conditions/q/CA/{location}.json")
    public ConditionsServiceResponse getConditions(@Path("location") String location);
}
</code></pre>

<p><code>WeatherServiceManager.java:</code></p>

<pre><code class="language-java">public class WeatherServiceManager {  
    private String mWeatherServiceEndpoint;
    private final WeatherServiceInterface mWeatherServiceInterface;

    public WeatherServiceManager(String weatherServiceEndpoint) {
        mWeatherServiceEndpoint = weatherServiceEndpoint;
        mWeatherServiceInterface = buildRestAdapter()
                .create(WeatherServiceInterface.class);
    }
    //uses the getConditions(String location) interface, with "Atlanta" for the location path attribute
    public List&lt;WeatherCondition&gt; getConditionsForAtlanta() {
        return mWeatherServiceInterface.getConditions("Atlanta")
                .getConditionsResponse()
                .getWeatherConditions();
    }
    //a retrofit rest adapter - read more about this at:
    //http://square.github.io/retrofit/javadoc/retrofit/RestAdapter.Builder.html
    private RestAdapter buildRestAdapter() {
        return new RestAdapter.Builder()
                .setEndpoint(mWeatherServiceEndpoint)
                .build();
    }
}
</code></pre>

<p><code>ConditionsServiceResponse.java</code> </p>

<p>maps the json response from Weather Underground (using a library called <a href="https://code.google.com/p/google-gson/">GSON</a> which Retrofit handily supports out of the box) that comes back from the server for that particular request - in this case the weather for Atlanta.</p>

<pre><code class="language-java">public class ConditionsResponse {  
        @SerializedName("results")
        public List&lt;WeatherCondition&gt; mWeatherConditions;
}
</code></pre>

<p>Finally, in use, here's what it looks like:  </p>

<pre><code class="language-java">String serviceEndpoint = "http://api.wunderground.com/api/" + BuildConfig.WEATHERVIEW_API_KEY + "/";  
List&lt;WeatherConditions&gt; conditions = new WeatherServiceManager(serviceEndpoint).getConditionsForAtlanta();  
</code></pre>

<hr>

<h3 id="writingthetest">Writing the Test</h3>

<p>Ok, now that we've explained the service and how it's put together we're ready to start explaining how the mocking for the webservice test is put together. Here's our test setup: </p>

<pre><code class="language-java">@RunWith(RobolectricTestRunner.class)
class WeatherServiceManagerTest{

    public WeatherServiceManager mWeatherServiceManager;

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(1111);

     @Before
    public void setup() {
        String serviceEndpoint = "http://localhost:1111/api/" + BuildConfig.WEATHERVIEW_API_KEY + "/";
        mWeatherServiceManager = new WeatherServiceManager(serviceEndpoint);
    }    
}
</code></pre>

<p>A couple key things about this setup code. The first is our WireMockRule definition. <br>
This will tell the WireMock library to spin up a server instance, which runs locally, on port 1111. <br>
We also pass in a serviceEndpoint resolving to localhost instead of the live api endpoint. </p>

<p>Next, we'll add a test that asserts the number of results we expected would come back, actually came back.</p>

<pre><code class="language-java">@RunWith(RobolectricTestRunner.class)
class WeatherServiceManagerTest{  
    ...
    @Test
    public void testGetCurrentWeatherReturnsExpected() {
        stubFor(get(urlMatching("/api/.*"))
                    .atPriority(5)
                    .willReturn(aResponse()
                            .withStatus(200)
                            .withBodyFile("atlanta-conditions.json")));
            List&lt;WeatherCondition&gt; conditionsForAtlanta = mWeatherServiceManager.getConditionsForAtlanta();
            assertThat(conditionsForAtlanta.size()).isEqualTo(1);
        }
    ...
}
</code></pre>

<p>What this setup says is that any time i make a request matching "/api/*", return a response with 200 as its status, containing the content within the file "atlanta-conditions.json" as it's response body! <br>
By default, wiremock will pull that file from : test/resources/__files/ - so add a new file called atlanta-conditions.json. I copied a response from the live webservice API earlier into that file:  </p>

<pre><code class="language-javascript">{
  "response": {
  "version":"0.1",
  "termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
  "features": {
  "conditions": 1
  }
        , "results": [
        {
        "name": "Atlanta",
        "city": "Atlanta",
        "state": "GA",
        "country": "US",
        "country_iso3166":"US",
        "country_name":"USA",
        "zmw": "30301.1.99999",
        "l": "/q/zmw:30301.1.99999"
        }

        ]
    }
}
</code></pre>

<p>With the addition of this file, we can then run our test - which should pass. So - what have we done? We've mocked the response from the webserver, decoupling our test from dependence on a live webserver,  and provided a canned response that speeds up our test suite because it's local data, doesn't incur a hit against the api limit, and is immune to the service going down.</p>

<hr>

<h3 id="examplecodeweatherview">Example Code: Weatherview</h3>

<p>I hope this article helped to outline how mocking a REST webservice can be accomplished easily by using WireMock! I wrote a quick example project of how you can use WireMock to test your services that i've put <a href="http://github.com/mutexkid/weatherview">Right Here</a> on github. Check it out (and let me know if you have questions or ideas about mocking with webservices)!</p>]]></content:encoded></item></channel></rss>