<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Adam Speakman]]></title>
  <link href="http://adamsp.github.com/speakman-website/atom.xml" rel="self"/>
  <link href="http://adamsp.github.com/speakman-website/"/>
  <updated>2019-04-07T15:35:05-07:00</updated>
  <id>http://adamsp.github.com/speakman-website/</id>
  <author>
    <name><![CDATA[Adam]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Mockito UnfinishedStubbingException in tests]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2019/04/07/mockito-unfinishedstubbingexception-in-tests/"/>
    <updated>2019-04-07T13:05:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2019/04/07/mockito-unfinishedstubbingexception-in-tests</id>
    <content type="html"><![CDATA[<p>Ever wonder why Mockito will occasionally give you an <code>UnfinishedStubbingException</code> even though you <em>clearly</em> finished the stubbing?</p>

<p>For example, the following code will fail at runtime (<code>mockChannel</code> has been setup earlier):</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="n">whenever</span><span class="p">(</span><span class="n">mockChannelNameProvider</span><span class="p">.</span><span class="n">nameForChannel</span><span class="p">(</span><span class="n">mockChannel</span><span class="p">))</span>
</span><span class='line'>    <span class="p">.</span><span class="n">thenReturn</span><span class="p">(</span><span class="n">mockChannel</span><span class="p">.</span><span class="n">id</span><span class="p">())</span>
</span></code></pre></td></tr></table></div></figure>


<p>With an exception like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="n">org</span><span class="p">.</span><span class="n">mockito</span><span class="p">.</span><span class="n">exceptions</span><span class="p">.</span><span class="n">misusing</span><span class="p">.</span><span class="n">UnfinishedStubbingException</span><span class="p">:</span>
</span><span class='line'><span class="n">Unfinished</span> <span class="n">stubbing</span> <span class="n">detected</span> <span class="n">here</span><span class="p">:</span>
</span><span class='line'><span class="p">-&gt;</span> <span class="n">at</span> <span class="n">ExampleFailingTestKotlin</span><span class="p">.</span><span class="n">setupChannelName</span><span class="p">(</span><span class="n">ExampleInterfacesTest</span><span class="p">.</span><span class="n">kt</span><span class="p">:</span><span class="m">30</span><span class="p">)</span>
</span><span class='line'>
</span><span class='line'><span class="n">E</span><span class="p">.</span><span class="n">g</span><span class="p">.</span> <span class="n">thenReturn</span><span class="p">()</span> <span class="n">may</span> <span class="n">be</span> <span class="n">missing</span><span class="p">.</span>
</span><span class='line'><span class="n">Examples</span> <span class="n">of</span> <span class="n">correct</span> <span class="n">stubbing</span><span class="p">:</span>
</span><span class='line'>    <span class="k">when</span><span class="p">(</span><span class="n">mock</span><span class="p">.</span><span class="n">isOk</span><span class="p">()).</span><span class="n">thenReturn</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>
</span><span class='line'>    <span class="k">when</span><span class="p">(</span><span class="n">mock</span><span class="p">.</span><span class="n">isOk</span><span class="p">()).</span><span class="n">thenThrow</span><span class="p">(</span><span class="n">exception</span><span class="p">);</span>
</span><span class='line'>    <span class="n">doThrow</span><span class="p">(</span><span class="n">exception</span><span class="p">).</span><span class="k">when</span><span class="p">(</span><span class="n">mock</span><span class="p">).</span><span class="n">someVoidMethod</span><span class="p">();</span>
</span><span class='line'><span class="n">Hints</span><span class="p">:</span>
</span><span class='line'> <span class="m">1.</span> <span class="n">missing</span> <span class="n">thenReturn</span><span class="p">()</span>
</span><span class='line'> <span class="m">2.</span> <span class="n">you</span> <span class="n">are</span> <span class="n">trying</span> <span class="n">to</span> <span class="n">stub</span> <span class="n">a</span> <span class="k">final</span> <span class="n">method</span><span class="p">,</span> <span class="n">which</span> <span class="k">is</span> <span class="n">not</span> <span class="n">supported</span>
</span><span class='line'> <span class="m">3</span><span class="p">:</span> <span class="n">you</span> <span class="n">are</span> <span class="n">stubbing</span> <span class="n">the</span> <span class="n">behaviour</span> <span class="n">of</span> <span class="n">another</span> <span class="n">mock</span> <span class="n">inside</span> <span class="n">before</span> <span class="err">&#39;</span><span class="n">thenReturn</span><span class="err">&#39;</span> <span class="n">instruction</span> <span class="k">is</span> <span class="n">completed</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is a very good exception message. It gives you some common examples of what you might have done wrong, and how to fix them. However, our code doesn&#8217;t match any of the examples.</p>

<!-- more -->


<p>If we look at the generated Java for this (<code>Tools &gt; Kotlin &gt; Show Kotlin Bytecode &gt; Decompile</code>), it <em>still</em> looks like it should work - we definitely finish the stubbing:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">Channel</span> <span class="n">var10001</span> <span class="o">=</span> <span class="k">this</span><span class="o">.</span><span class="na">mockChannel</span><span class="o">;</span>
</span><span class='line'><span class="k">if</span> <span class="o">(</span><span class="n">var10001</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">Intrinsics</span><span class="o">.</span><span class="na">throwUninitializedPropertyAccessException</span><span class="o">(</span><span class="s">&quot;mockChannel&quot;</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">OngoingStubbing</span> <span class="n">var2</span> <span class="o">=</span> <span class="n">Mockito</span><span class="o">.</span><span class="na">when</span><span class="o">(</span><span class="n">var1</span><span class="o">.</span><span class="na">nameForChannel</span><span class="o">(</span><span class="n">var10001</span><span class="o">));</span>
</span><span class='line'><span class="n">var10001</span> <span class="o">=</span> <span class="k">this</span><span class="o">.</span><span class="na">mockChannel</span><span class="o">;</span>
</span><span class='line'><span class="k">if</span> <span class="o">(</span><span class="n">var10001</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">Intrinsics</span><span class="o">.</span><span class="na">throwUninitializedPropertyAccessException</span><span class="o">(</span><span class="s">&quot;mockChannel&quot;</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="n">var2</span><span class="o">.</span><span class="na">thenReturn</span><span class="o">(</span><span class="n">var10001</span><span class="o">.</span><span class="na">id</span><span class="o">());</span>
</span></code></pre></td></tr></table></div></figure>


<p>So why do we get an <code>UnfinishedStubbingException</code>? <em>Because we&#8217;re accessing a mock before we finish the stubbing.</em></p>

<p>The failure happens on this line from the decompiled Kotlin bytecode:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">var2</span><span class="o">.</span><span class="na">thenReturn</span><span class="o">(</span><span class="n">var10001</span><span class="o">.</span><span class="na">id</span><span class="o">());</span>
</span></code></pre></td></tr></table></div></figure>


<p>Let&#8217;s make this a little clearer by using descriptive names:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">ongoingStubbing</span><span class="o">.</span><span class="na">thenReturn</span><span class="o">(</span><span class="n">mockChannel</span><span class="o">.</span><span class="na">id</span><span class="o">());</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can break this apart a little further:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">String</span> <span class="n">id</span> <span class="o">=</span> <span class="n">mockChannel</span><span class="o">.</span><span class="na">id</span><span class="o">();</span>
</span><span class='line'><span class="n">ongoingStubbing</span><span class="o">.</span><span class="na">thenReturn</span><span class="o">(</span><span class="n">id</span><span class="o">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>So we have a reference to an <code>OngoingStubbing</code>. Internally, Mockito statically maintains a reference to a <code>MockingProgress</code>. When we access the mock (<code>mockChannel.id()</code>) after we&#8217;ve already started the stubbing, Mockito goes off to the <code>MockingProgress</code> and <a href="https://github.com/mockito/mockito/blob/49e07acc30fb486a8af773977e461cf4d1c876ec/src/main/java/org/mockito/internal/handler/MockHandlerImpl.java#L64">calls through to a <code>validateState()</code> method</a>, which does this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kt">void</span> <span class="nf">validateState</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">validateMostStuff</span><span class="o">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">//validate stubbing:</span>
</span><span class='line'>  <span class="k">if</span> <span class="o">(</span><span class="n">stubbingInProgress</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">Location</span> <span class="n">temp</span> <span class="o">=</span> <span class="n">stubbingInProgress</span><span class="o">;</span>
</span><span class='line'>      <span class="n">stubbingInProgress</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
</span><span class='line'>      <span class="k">throw</span> <span class="nf">unfinishedStubbing</span><span class="o">(</span><span class="n">temp</span><span class="o">);</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Because a stubbing is still in progress, we get an <code>UnfinishedStubbingException</code>. 💥</p>

<p>We can fix this by pulling the variable out of the mock on the line before we start the stubbing:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">val</span> <span class="py">channelName</span> <span class="p">=</span> <span class="n">mockChannel</span><span class="p">.</span><span class="n">id</span><span class="p">()</span>
</span><span class='line'><span class="n">whenever</span><span class="p">(</span><span class="n">mockChannelNameProvider</span><span class="p">.</span><span class="n">nameForChannel</span><span class="p">(</span><span class="n">mockChannel</span><span class="p">)).</span><span class="n">thenReturn</span><span class="p">(</span><span class="n">channelName</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Of course, make sure to comment <em>why</em> you&#8217;re doing this for the next developer who comes along and tries to simplify this by inlining the variable.</p>

<p>Now that we see why it&#8217;s happening, it makes sense. Accessing a mock while setting up a different one is a bit of a code smell - they should probably be accessing some constant value. One of the best ways to prevent this situation is to use fakes not mocks for your models. Obviously, this isn&#8217;t always easy though - you might have legacy concerns that prevent this or you might need to make sure that you return the same thing from two different interfaces.</p>

<p>This can be a very confusing error to debug, especially when it&#8217;s deep in some utility or setup method (where it might not even be obvious that you&#8217;re accessing something on a mock), or when you&#8217;re in the process of converting some legacy code. Next time you encounter it, consider whether you can do some refactoring to make it harder to hit.</p>

<p>You can find the <a href="https://github.com/adamsp/mockito-tests">source code for this post here</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Asynchronously loading data using Googles Paging Library]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2017/10/09/asynchronously-loading-data-using-googles-paging-library/"/>
    <updated>2017-10-09T14:42:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2017/10/09/asynchronously-loading-data-using-googles-paging-library</id>
    <content type="html"><![CDATA[<p>The recently released <a href="https://developer.android.com/topic/libraries/architecture/paging.html">Paging Library</a> from Google gives you an easy way to page data into memory off of the main thread. If you want to use it with <a href="https://developer.android.com/topic/libraries/architecture/room.html">Room</a>, then the built-in support makes it trivial. However, if you&#8217;d like to page data that exists elsewhere - from the network or disk, for example - then you have to do a little extra work.</p>

<p>Here I demonstrate how to take existing code that loads a list of screenshots from disk and convert it to load asynchronously using the Paging Library. This example could easily be adapted for network calls.</p>

<!-- more -->


<p>Throughout this post we&#8217;ll be using a <code>Screenshot</code> class defined as follows:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="n">@Parcelize</span>
</span><span class='line'><span class="k">class</span> <span class="nc">Screenshot</span><span class="p">(</span><span class="k">val</span> <span class="py">uri</span><span class="p">:</span> <span class="n">Uri</span><span class="p">,</span> <span class="k">val</span> <span class="py">width</span><span class="p">:</span> <span class="n">Int</span><span class="p">,</span> <span class="k">val</span> <span class="py">height</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">:</span> <span class="n">Parcelable</span>
</span></code></pre></td></tr></table></div></figure>


<p>You will also need to import the library:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="n">implementation</span> <span class="s">&quot;android.arch.paging:runtime:1.0.0-alpha2&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Existing code</h2>

<p>When the app launches, it shows the user a list of images from a directory they supply during setup. My existing code was a simple repository that loaded <em>all</em> screenshots (as a Uri and width/height values) from this directory via Android&#8217;s storage access framework. The code was similar to the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">override</span> <span class="k">fun</span> <span class="nf">allScreenshots</span><span class="p">():</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">screenshots</span> <span class="p">=</span> <span class="n">documentsAtUri</span><span class="p">(</span><span class="n">screenshotDirectory</span><span class="p">)</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">screenshots</span><span class="p">.</span><span class="n">map</span> <span class="p">{</span>
</span><span class='line'>      <span class="n">getScreenshotFromUri</span><span class="p">(</span><span class="n">DocumentsContract</span><span class="p">.</span><span class="n">buildDocumentUriUsingTree</span><span class="p">(</span><span class="n">it</span><span class="p">.</span><span class="n">path</span><span class="p">,</span> <span class="n">it</span><span class="p">.</span><span class="n">id</span><span class="p">))</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">private</span> <span class="k">fun</span> <span class="nf">getScreenshotFromUri</span><span class="p">(</span><span class="n">uri</span><span class="p">:</span> <span class="n">Uri</span><span class="p">):</span> <span class="n">Screenshot</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">val</span> <span class="err">(</span><span class="py">width</span><span class="p">,</span> <span class="n">height</span><span class="p">)</span> <span class="p">=</span> <span class="n">getDimens</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">Screenshot</span><span class="p">(</span><span class="n">uri</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">height</span><span class="p">)</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">private</span> <span class="k">fun</span> <span class="nf">getDimens</span><span class="p">(</span><span class="n">uri</span><span class="p">:</span> <span class="n">Uri</span><span class="p">):</span> <span class="n">Pair</span><span class="p">&lt;</span><span class="n">Int</span><span class="p">,</span> <span class="n">Int</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">opts</span> <span class="p">=</span> <span class="n">BitmapFactory</span><span class="p">.</span><span class="n">Options</span><span class="p">()</span>
</span><span class='line'>    <span class="n">opts</span><span class="p">.</span><span class="n">inJustDecodeBounds</span> <span class="p">=</span> <span class="k">true</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">parcelFileDescriptor</span> <span class="p">=</span> <span class="n">contentResolver</span><span class="p">.</span><span class="n">openFileDescriptor</span><span class="p">(</span><span class="n">uri</span><span class="p">,</span> <span class="s">&quot;r&quot;</span><span class="p">)</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">fileDescriptor</span> <span class="p">=</span> <span class="n">parcelFileDescriptor</span><span class="o">!!</span><span class="p">.</span><span class="n">fileDescriptor</span>
</span><span class='line'>    <span class="n">BitmapFactory</span><span class="p">.</span><span class="n">decodeFileDescriptor</span><span class="p">(</span><span class="n">fileDescriptor</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="n">opts</span><span class="p">)</span>
</span><span class='line'>    <span class="k">return</span> <span class="n">Pair</span><span class="p">(</span><span class="n">opts</span><span class="p">.</span><span class="n">outWidth</span><span class="p">,</span> <span class="n">opts</span><span class="p">.</span><span class="n">outHeight</span><span class="p">)</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, we have to go to disk to get information about every screenshot. This is expensive! On my test device I&#8217;ve only got around 100 screenshots - on a device that&#8217;s been around longer a user could have many hundreds or thousands of screenshots in this folder. Rather than loading these all up front, I need to load these asynchronously. In addition, since these are in a list there&#8217;s a high likelihood that the items further down the list won&#8217;t even be needed. The Paging Library helps with these problems.</p>

<h2>Paging Library Fundamentals</h2>

<p>The Paging Library has 3 different &#8220;levels&#8221; that build on top of each other.</p>

<p>At the base, we have a kind of <a href="https://developer.android.com/reference/android/arch/paging/DataSource.html"><code>DataSource</code></a>. This can be either &#8220;keyed&#8221; (such that you need to know about the item at index N-1 in order to know about the item at index N - like a linked list), or &#8220;tiled&#8221; (such that you can access elements at arbitray indices - like an array list).</p>

<p>Above that, we have a <a href="https://developer.android.com/reference/android/arch/paging/PagedList.html"><code>PagedList</code></a>, which as its name suggests, is a list that pages its data in from a <code>DataSource</code>.</p>

<p>Finally we have the <a href="https://developer.android.com/reference/android/arch/paging/PagedListAdapter.html"><code>PagedListAdapter</code></a>, which is a <code>RecyclerView.Adapter</code> that neatly wraps a <code>PagedList</code>, calling the correct <code>notifyItem...</code> methods for you as your data changes (when you call <code>setList</code> with a new <code>PagedList</code>) or loads in. This is fairly standard <code>RecyclerView</code> boilerplate. If you need some custom behaviour, you can duplicate its functionality - it&#8217;s just a handy wrapper around the <a href="https://developer.android.com/reference/android/arch/paging/PagedListAdapterHelper.html"><code>PagedListAdapterHelper</code></a>.</p>

<h2>Constructing a Data Source</h2>

<p>A <code>DataSource</code> is reasonably simple. For a list like this, we implement a <code>TiledDataSource</code>, doing the expensive disk IO in the <code>loadRange</code> method. The <code>PagedList</code> will call this from a background thread when it is time to load a new page of data.</p>

<p>Note that it does <em>not</em> clamp ranges for you - so if you have 10 items and a page size of 6, your second page will be <code>startPosition = 6</code> and <code>count = 6</code> - which will give you an <code>IndexOutOfBoundsException</code>. Make sure to clamp your inputs as I do here.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">val</span> <span class="py">screenshots</span> <span class="p">=</span> <span class="n">documentsAtUri</span><span class="p">(</span><span class="n">loadScreenshotDirectory</span><span class="p">())</span>
</span><span class='line'>
</span><span class='line'><span class="k">val</span> <span class="py">dataSource</span><span class="p">:</span> <span class="n">DataSource</span><span class="p">&lt;</span><span class="n">Int</span><span class="p">,</span> <span class="n">Screenshot</span><span class="p">&gt;</span> <span class="p">=</span> <span class="k">object</span> <span class="err">: </span><span class="nc">TiledDataSource</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">override</span> <span class="k">fun</span> <span class="nf">countItems</span><span class="p">():</span> <span class="n">Int</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">screenshots</span><span class="p">.</span><span class="n">size</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">override</span> <span class="k">fun</span> <span class="nf">loadRange</span><span class="p">(</span><span class="n">startPosition</span><span class="p">:</span> <span class="n">Int</span><span class="p">,</span> <span class="n">count</span><span class="p">:</span> <span class="n">Int</span><span class="p">):</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>      <span class="k">val</span> <span class="py">end</span> <span class="p">=</span> <span class="n">minOf</span><span class="p">(</span><span class="n">startPosition</span> <span class="p">+</span> <span class="n">count</span><span class="p">,</span> <span class="n">countItems</span><span class="p">())</span>
</span><span class='line'>      <span class="k">return</span> <span class="n">screenshots</span><span class="p">.</span><span class="n">subList</span><span class="p">(</span><span class="n">startPosition</span><span class="p">,</span> <span class="n">end</span><span class="p">).</span><span class="n">map</span> <span class="p">{</span>
</span><span class='line'>            <span class="n">getScreenshot</span><span class="p">(</span><span class="n">DocumentsContract</span><span class="p">.</span><span class="n">buildDocumentUriUsingTree</span><span class="p">(</span><span class="n">it</span><span class="p">.</span><span class="n">path</span><span class="p">,</span> <span class="n">it</span><span class="p">.</span><span class="n">id</span><span class="p">))</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Building a Paged List</h2>

<p>For my use-case, 8 elements on a &#8216;page&#8217; was sufficient. I&#8217;m showing elements in a 2-column list; most of the elements are around half the window height. You&#8217;ll need to decide what works well for you.</p>

<p>Note that here we use the default prefetch distance of <code>pageSize</code> - that is, as soon as the first item in a given page of data is requested, the next page will begin loading. Depending on your data, you may want this to be smaller or larger.</p>

<p>We also enable placeholders (this is actually enabled by default). Since we know exactly how many elements are going to be in our list (we have Uris for every screenshot, even if we don&#8217;t have any details about that screenshot yet) we can use null placeholders while the images load - helping avoid weird scrollbars. Our <code>onBindViewHolder</code> has to deal with this later. I&#8217;d recommend <a href="https://developer.android.com/reference/android/arch/paging/PagedList.html">reading the <code>PagedList</code> docs</a> - they go into more detail on placeholders.</p>

<p>You need to supply two <a href="https://developer.android.com/reference/java/util/concurrent/Executor.html"><code>Executor</code></a>s - one for posting back to the main thread, and another for background work. In this example we create a main thread <code>Handler</code> and post events to it directly, but our disk IO <code>Executor</code> is injected from elsewhere.</p>

<p>Finally, this code has one subtle gotcha - the first two pages will be loaded immediately on whatever thread <code>build()</code> is called from! From the docs:</p>

<blockquote><p>Creating a PagedList loads data from the DataSource immediately, and should for this reason be done on a background thread. The constructed PagedList may then be passed to and used on the UI thread. This is done to prevent passing a list with no loaded content to the UI thread, which should generally not be presented to the user.</p></blockquote>

<p>In this case, we&#8217;ll be going to disk 16 times (8 for the first page, and then another 8 as the second page is pre-fetched). I address this later when I wire everything together.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">val</span> <span class="py">mainHandler</span> <span class="p">=</span> <span class="n">Handler</span><span class="p">(</span><span class="n">Looper</span><span class="p">.</span><span class="n">getMainLooper</span><span class="p">())</span>
</span><span class='line'>
</span><span class='line'><span class="k">val</span> <span class="py">pagedList</span> <span class="p">=</span> <span class="n">PagedList</span><span class="p">.</span><span class="n">Builder</span><span class="p">&lt;</span><span class="n">Int</span><span class="p">,</span> <span class="n">Screenshot</span><span class="p">&gt;()</span>
</span><span class='line'>    <span class="p">.</span><span class="n">setDataSource</span><span class="p">(</span><span class="n">dataSource</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">setMainThreadExecutor</span><span class="p">({</span> <span class="n">mainHandler</span><span class="p">.</span><span class="n">post</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">})</span>
</span><span class='line'>    <span class="p">.</span><span class="n">setBackgroundThreadExecutor</span><span class="p">(</span><span class="n">diskExecutor</span><span class="p">)</span>
</span><span class='line'>    <span class="p">.</span><span class="n">setConfig</span><span class="p">(</span><span class="n">PagedList</span><span class="p">.</span><span class="n">Config</span><span class="p">.</span><span class="n">Builder</span><span class="p">()</span>
</span><span class='line'>            <span class="p">.</span><span class="n">setPageSize</span><span class="p">(</span><span class="m">8</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">setEnablePlaceholders</span><span class="p">(</span><span class="k">true</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">build</span><span class="p">())</span>
</span><span class='line'>    <span class="p">.</span><span class="n">build</span><span class="p">()</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Adding the Adapter</h2>

<p>The simplest part of all. We just extend <code>PagedListAdapter</code>, supplying a simple <code>DiffCallback</code> for comparing <code>Screenshot</code> objects, and implement <code>onBindViewHolder</code> and <code>onCreateViewHolder</code> like normal.</p>

<p>Note if you have custom logic (such as a custom <code>BindingAdapter</code> - not shown here) you need to be aware that the object returned from <code>getItem</code> <em>can be</em> <code>null</code> - these are the placeholders we enabled earlier, and will be <code>null</code> while the data at that index loads. If your page sizes are appropriate, receiving a <code>null</code> object will be rare, but you <em>must</em> handle it.</p>

<figure class='code'><figcaption><span>ScreenshotPickerAdapter.kt</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">val</span> <span class="py">DIFF_CALLBACK</span> <span class="p">=</span> <span class="k">object</span> <span class="err">: </span><span class="nc">DiffCallback</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;()</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">override</span> <span class="k">fun</span> <span class="nf">areItemsTheSame</span><span class="p">(</span><span class="n">oldItem</span><span class="p">:</span> <span class="n">Screenshot</span><span class="p">,</span> <span class="n">newItem</span><span class="p">:</span> <span class="n">Screenshot</span><span class="p">):</span> <span class="n">Boolean</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">oldItem</span><span class="p">.</span><span class="n">uri</span> <span class="p">==</span> <span class="n">newItem</span><span class="p">.</span><span class="n">uri</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">override</span> <span class="k">fun</span> <span class="nf">areContentsTheSame</span><span class="p">(</span><span class="n">oldItem</span><span class="p">:</span> <span class="n">Screenshot</span><span class="p">,</span> <span class="n">newItem</span><span class="p">:</span> <span class="n">Screenshot</span><span class="p">):</span> <span class="n">Boolean</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">oldItem</span><span class="p">.</span><span class="n">uri</span> <span class="p">==</span> <span class="n">newItem</span><span class="p">.</span><span class="n">uri</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">class</span> <span class="nc">ScreenshotPickerAdapter</span><span class="p">(</span><span class="k">val</span> <span class="py">clickHandler</span><span class="p">:</span> <span class="n">ScreenshotPickerSelectionHandler</span><span class="p">)</span>
</span><span class='line'>    <span class="p">:</span> <span class="n">PagedListAdapter</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">,</span> <span class="n">ScreenshotViewHolder</span><span class="p">&gt;(</span><span class="n">DIFF_CALLBACK</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">override</span> <span class="k">fun</span> <span class="nf">onBindViewHolder</span><span class="p">(</span><span class="n">holder</span><span class="p">:</span> <span class="n">ScreenshotViewHolder</span><span class="p">,</span> <span class="n">position</span><span class="p">:</span> <span class="n">Int</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">val</span> <span class="py">screenshot</span> <span class="p">=</span> <span class="n">getItem</span><span class="p">(</span><span class="n">position</span><span class="p">)</span>
</span><span class='line'>        <span class="n">holder</span><span class="p">.</span><span class="n">screenshot</span> <span class="p">=</span> <span class="n">screenshot</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">override</span> <span class="k">fun</span> <span class="nf">onCreateViewHolder</span><span class="p">(</span><span class="n">parent</span><span class="p">:</span> <span class="n">ViewGroup</span><span class="p">?,</span> <span class="n">viewType</span><span class="p">:</span> <span class="n">Int</span><span class="p">):</span> <span class="n">ScreenshotViewHolder</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">val</span> <span class="py">binding</span><span class="p">:</span> <span class="n">PickerListItemBinding</span> <span class="p">=</span> <span class="n">DataBindingUtil</span><span class="p">.</span><span class="n">inflate</span><span class="p">(</span>
</span><span class='line'>          <span class="n">LayoutInflater</span><span class="p">.</span><span class="n">from</span><span class="p">(</span><span class="n">parent</span><span class="o">?.</span><span class="n">context</span><span class="p">),</span> <span class="n">R</span><span class="p">.</span><span class="n">layout</span><span class="p">.</span><span class="n">picker_list_item</span><span class="p">,</span> <span class="n">parent</span><span class="p">,</span> <span class="k">false</span><span class="p">)</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">ScreenshotViewHolder</span><span class="p">(</span><span class="n">binding</span><span class="p">,</span> <span class="n">clickHandler</span><span class="p">)</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Wiring it all up</h2>

<p>Now we have all the pieces we can put them together. Note that I supply an async callback for loading the screenshots - we use the disk executor we supply in the constructor to do the actual building (since this loads the first page or more, as mentioned above!) and then set the result on our list once that load has finished.</p>

<p>For brevity, this code doesn&#8217;t consider configuration changes or other kinds of activity destruction.</p>

<figure class='code'><figcaption><span>Executors.kt</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="c1">// Define a disk IO executor that can be re-used elsewhere</span>
</span><span class='line'><span class="k">val</span> <span class="py">diskExecutor</span> <span class="p">=</span> <span class="n">Executors</span><span class="p">.</span><span class="n">newFixedThreadPool</span><span class="p">(</span><span class="m">2</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>MainActivity.kt</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">var</span> <span class="py">screenshotLoader</span><span class="p">:</span> <span class="n">ScreenshotLoader</span><span class="p">?</span> <span class="p">=</span> <span class="k">null</span>
</span><span class='line'><span class="k">var</span> <span class="py">adapter</span><span class="p">:</span> <span class="n">ScreenshotPickerAdapter</span><span class="p">?</span> <span class="p">=</span> <span class="k">null</span>
</span><span class='line'>
</span><span class='line'><span class="k">override</span> <span class="k">fun</span> <span class="nf">onCreate</span><span class="p">(</span><span class="n">savedInstanceState</span><span class="p">:</span> <span class="n">Bundle</span><span class="p">?)</span> <span class="p">{</span>
</span><span class='line'>    <span class="k">super</span><span class="p">.</span><span class="n">onCreate</span><span class="p">(</span><span class="n">savedInstanceState</span><span class="p">)</span>
</span><span class='line'>    <span class="n">setContentView</span><span class="p">(</span><span class="n">R</span><span class="p">.</span><span class="n">layout</span><span class="p">.</span><span class="n">activity_main</span><span class="p">)</span>
</span><span class='line'>    <span class="n">screenshotLoader</span> <span class="p">=</span> <span class="n">SAFScreenshotLoader</span><span class="p">(</span><span class="n">contentResolver</span><span class="p">,</span> <span class="n">diskExecutor</span><span class="p">)</span>
</span><span class='line'>    <span class="n">adapter</span> <span class="p">=</span> <span class="n">ScreenshotPickerAdapter</span><span class="p">(</span><span class="k">this</span><span class="p">)</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">recycler</span> <span class="p">=</span> <span class="n">findViewById</span><span class="p">(</span><span class="n">R</span><span class="p">.</span><span class="n">id</span><span class="p">.</span><span class="n">main_recycler</span><span class="p">)</span> <span class="k">as</span> <span class="n">RecyclerView</span><span class="p">?</span>
</span><span class='line'>    <span class="n">recycler</span><span class="o">?.</span><span class="n">layoutManager</span> <span class="p">=</span> <span class="n">GridLayoutManager</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="m">2</span><span class="p">)</span>
</span><span class='line'>    <span class="n">recycler</span><span class="o">?.</span><span class="n">adapter</span> <span class="p">=</span> <span class="n">adapter</span>
</span><span class='line'>    <span class="n">loadScreenshots</span><span class="p">()</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="k">private</span> <span class="k">fun</span> <span class="nf">loadScreenshots</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="n">screenshotLoader</span><span class="o">?.</span><span class="n">allScreenshots</span><span class="p">({</span>
</span><span class='line'>        <span class="c1">// We could explode here if the activity has been killed</span>
</span><span class='line'>        <span class="n">runOnUiThread</span> <span class="p">{</span>
</span><span class='line'>            <span class="n">adapter</span><span class="o">?.</span><span class="n">setList</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">})</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>SAFScreenshotLoader.kt</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
</pre></td><td class='code'><pre><code class='kotlin'><span class='line'><span class="k">override</span> <span class="k">fun</span> <span class="nf">allScreenshots</span><span class="p">(</span><span class="n">resultListener</span><span class="p">:</span> <span class="p">(</span><span class="n">PagedList</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;)</span> <span class="p">-&gt;</span> <span class="n">Unit</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="c1">// This assumes retrieving the Uris is cheap - this whole block could be moved off thread</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">screenshotUris</span> <span class="p">=</span> <span class="n">documentsAtUri</span><span class="p">(</span><span class="n">loadScreenshotDirectory</span><span class="p">())</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">dataSource</span><span class="p">:</span> <span class="n">DataSource</span><span class="p">&lt;</span><span class="n">Int</span><span class="p">,</span> <span class="n">Screenshot</span><span class="p">&gt;</span> <span class="p">=</span> <span class="k">object</span> <span class="err">: </span><span class="nc">TiledDataSource</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;()</span> <span class="p">{</span>
</span><span class='line'>        <span class="k">override</span> <span class="k">fun</span> <span class="nf">countItems</span><span class="p">():</span> <span class="n">Int</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">screenshotUris</span><span class="p">.</span><span class="n">size</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">override</span> <span class="k">fun</span> <span class="nf">loadRange</span><span class="p">(</span><span class="n">startPosition</span><span class="p">:</span> <span class="n">Int</span><span class="p">,</span> <span class="n">count</span><span class="p">:</span> <span class="n">Int</span><span class="p">):</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Screenshot</span><span class="p">&gt;</span> <span class="p">{</span>
</span><span class='line'>            <span class="k">val</span> <span class="py">end</span> <span class="p">=</span> <span class="n">minOf</span><span class="p">(</span><span class="n">startPosition</span> <span class="p">+</span> <span class="n">count</span><span class="p">,</span> <span class="n">countItems</span><span class="p">())</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">screenshotUris</span><span class="p">.</span><span class="n">subList</span><span class="p">(</span><span class="n">startPosition</span><span class="p">,</span> <span class="n">end</span><span class="p">).</span><span class="n">map</span> <span class="p">{</span>
</span><span class='line'>                <span class="n">getScreenshot</span><span class="p">(</span><span class="n">DocumentsContract</span><span class="p">.</span><span class="n">buildDocumentUriUsingTree</span><span class="p">(</span><span class="n">it</span><span class="p">.</span><span class="n">path</span><span class="p">,</span> <span class="n">it</span><span class="p">.</span><span class="n">id</span><span class="p">))</span>
</span><span class='line'>            <span class="p">}</span>
</span><span class='line'>        <span class="p">}</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>    <span class="k">val</span> <span class="py">builder</span> <span class="p">=</span> <span class="n">PagedList</span><span class="p">.</span><span class="n">Builder</span><span class="p">&lt;</span><span class="n">Int</span><span class="p">,</span> <span class="n">Screenshot</span><span class="p">&gt;()</span>
</span><span class='line'>            <span class="p">.</span><span class="n">setDataSource</span><span class="p">(</span><span class="n">dataSource</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">setMainThreadExecutor</span><span class="p">({</span> <span class="n">mainHandler</span><span class="p">.</span><span class="n">post</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="p">})</span>
</span><span class='line'>            <span class="p">.</span><span class="n">setBackgroundThreadExecutor</span><span class="p">(</span><span class="n">diskExecutor</span><span class="p">)</span>
</span><span class='line'>            <span class="p">.</span><span class="n">setConfig</span><span class="p">(</span><span class="n">PagedList</span><span class="p">.</span><span class="n">Config</span><span class="p">.</span><span class="n">Builder</span><span class="p">()</span>
</span><span class='line'>                    <span class="p">.</span><span class="n">setPageSize</span><span class="p">(</span><span class="m">8</span><span class="p">)</span>
</span><span class='line'>                    <span class="p">.</span><span class="n">setEnablePlaceholders</span><span class="p">(</span><span class="k">true</span><span class="p">)</span>
</span><span class='line'>                    <span class="p">.</span><span class="n">build</span><span class="p">())</span>
</span><span class='line'>    <span class="c1">// Note the actual construction happens on an IO thread - the build() call goes to disk</span>
</span><span class='line'>    <span class="n">diskExecutor</span><span class="p">.</span><span class="n">execute</span> <span class="p">{</span>
</span><span class='line'>        <span class="n">resultListener</span><span class="p">(</span><span class="n">builder</span><span class="p">.</span><span class="n">build</span><span class="p">())</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Gotchas</h2>

<ul>
<li>You may have to specify a <code>minHeight</code> on your list items, or otherwise specify the height when a placeholder is used. If you don&#8217;t, the adapter will query for (and the list will try to load) your whole list of 0-height items.</li>
<li>Don&#8217;t forget the first page is loaded when you call <code>PagedList.Builder.build()</code> - do this off the main thread!</li>
<li>Experiment with page sizes and prefetch windows. This is entirely dependent on your data.</li>
<li>Already loaded objects are <strong>not</strong> unloaded. If the user scrolls to the bottom of the list, the first items stay in memory. This is potentially a problem if your objects are large, or your list is long. Here I let <a href="http://square.github.io/picasso/">Picasso</a> load (and unload) the actual memory-intensive bitmaps for me. Storing a list of Uris is cheap.</li>
<li>You <strong>must</strong> handle null objects returned from <code>getItem</code> if you enable placeholders, even if you never encounter them in your testing.</li>
<li>The <code>loadRange</code> call is not bounded to the size of the list; you need to do this yourself. It will happily handle results smaller than the requested count, however (i.e. when you&#8217;re at the end of the list).</li>
<li>If you&#8217;re using <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html"><code>LiveData</code></a>, look into <a href="https://developer.android.com/reference/android/arch/paging/LivePagedListProvider.html"><code>LivePagedListProvider</code></a> as it will do most of this overhead for you.</li>
<li>The library is still in alpha at the time of this writing; the APIs described here could still change before release.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Tensorflow in Windows Bash]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2017/01/24/tensorflow-in-windows-bash/"/>
    <updated>2017-01-24T21:27:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2017/01/24/tensorflow-in-windows-bash</id>
    <content type="html"><![CDATA[<p>My first job out of university was at a startup doing natural language processing (NLP). Recently I&#8217;ve been rekindling my interest in machine learning, and have been playing with the <a href="https://www.tensorflow.org/">Tensorflow</a> library from Google. I work on a Mac, but at home I&#8217;m switching between a Mac and a PC - and ideally I&#8217;d like things to just work on whatever machine I&#8217;m on. The Tensorflow <a href="https://www.tensorflow.org/get_started/os_setup">setup guide</a> says it requires Python 3.5 for Windows, but I&#8217;m using Python 2.7 on my Mac and would like to be able to use files across platforms.</p>

<p>Here&#8217;s a quick intro to getting set up with Tensorflow for Python 2.7 on Windows (using the recently released <a href="https://msdn.microsoft.com/en-us/commandline/wsl/about">Bash on Windows</a>).</p>

<!-- more -->


<h1>Step 1 - Install Bash for Windows</h1>

<p>This is pretty trivial. Just <a href="https://msdn.microsoft.com/en-us/commandline/wsl/install_guide">follow the instructions</a>. I installed this on a Windows 10 64 bit machine with no problems.</p>

<h1>Step 2 - Install Tensorflow</h1>

<p>Now you have a bash shell (which comes with Python 2.7.4), we have to intall &amp; upgrade pip (Tensorflow requires pip 8.1 or later):</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>sudo apt-get install python-pip
</span><span class='line'>sudo pip install --ugprade pip
</span><span class='line'>source ~/.bashrc
</span><span class='line'>sudo pip install tensorflow</span></code></pre></td></tr></table></div></figure>


<p>You can test that everything worked by opening up a Python interpreter (ie, just type <code>python</code> and hit enter) then importing Tensorflow:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>import tensorflow as tf</span></code></pre></td></tr></table></div></figure>


<p>If you get no output, everything worked! <code>exit()</code> that and carry on.</p>

<h1>Step 3 - Usage</h1>

<p>If you&#8217;d like to edit your files in the shell, you&#8217;re basically good to go - though you&#8217;ll need to install git.</p>

<p>However if you&#8217;d like to use a nice GUI editor (such as Github&#8217;s <a href="https://atom.io/">Atom</a>) you have to beware. There&#8217;s a blog post which is very explicit that you <a href="https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/"><em>must not change Linux files from Windows</em></a>. Instead we go the other way, and access the Windows filesystem from the shell. This lets us edit our files in an editor while in a Windows environment but then run our changes from our bash shell (which we just set up with Tensorflow).</p>

<p>The Windows filesystem is located under <code>/mnt/c</code> (or other drive letter), but if things are stored in your user directory then the paths can get a bit long. So first (this is optional) I like to add a shortcut to my working directory so it&#8217;s easily accessible by adding the following to my <code>~/.profile</code> file:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>export TFSCRATCH=/mnt/c/Users/Adam/SomeDirectory</span></code></pre></td></tr></table></div></figure>


<p>You&#8217;ll need to <code>source ~/.profile</code>, then you can just <code>cd $TFSCRATCH</code> whenever you want to get to your working directory.</p>

<p>If you&#8217;re using Atom (like I am) there&#8217;s a handy included extension called <a href="https://github.com/atom/line-ending-selector">Line Ending Selector</a> - it allows you to specify which line endings you&#8217;d like to use. Swap it to <code>LF</code> when editing your Python files.</p>

<p>Now, running code is as you&#8217;d expect from a bash shell. Here I run the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/mnist/mnist_softmax.py">basic MNIST sample from Google</a>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>adam@ADAM-PC:~$ cd $TFSCRATCH
</span><span class='line'>adam@ADAM-PC:/mnt/c/Users/Adam/...$ python mnist_basic_google.py
</span><span class='line'>Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
</span><span class='line'>Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz
</span><span class='line'>Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
</span><span class='line'>Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz
</span><span class='line'>Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
</span><span class='line'>Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz
</span><span class='line'>Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
</span><span class='line'>Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz
</span><span class='line'>0.9174</span></code></pre></td></tr></table></div></figure>


<p>So; edit in Windows, run in bash. Easy.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Implementing GCM Network Manager for periodic network requests on Android]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2016/04/26/implementing-gcm-network-manager-for-periodic-network-requests-on-android/"/>
    <updated>2016-04-26T14:55:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2016/04/26/implementing-gcm-network-manager-for-periodic-network-requests-on-android</id>
    <content type="html"><![CDATA[<p>In the process of rebuilding <a href="https://github.com/adamsp/wsnz-android">What&#8217;s Shaking, NZ?</a>, I needed to implement a periodic network request (literally polling an API). I wanted to use the new <a href="https://developer.android.com/reference/android/app/job/JobScheduler.html">Job Scheduler</a> API, but unfortunately, this is only available on API 21 and above. Luckily we can get similar functionality by using <a href="https://developers.google.com/cloud-messaging/network-manager">GCM Network Manager</a>, as <a href="http://stackoverflow.com/q/25203254/1217087">suggested on StackOverflow</a>. Note that the GCM Network Manager actually uses Job Scheduler behind the scenes in API 21+.</p>

<p>The <a href="https://developers.google.com/cloud-messaging/network-manager">documentation</a> for this is somewhat hand-wavy. Here I attempt to provide a true step-by-step guide to implementing this. I assume you&#8217;re <em>not</em> already using GCM for something else in your app (as that was the case for me).</p>

<!-- more -->


<h1>Implement GcmTaskService</h1>

<p>The first step is to import GCM in your <code>build.gradle</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>compile 'com.google.android.gms:play-services-gcm:8.4.0'</span></code></pre></td></tr></table></div></figure>


<p>Now you can implement <a href="https://developers.google.com/android/reference/com/google/android/gms/gcm/GcmTaskService"><code>GcmTaskService</code></a>. This is as simple as the following:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>import com.google.android.gms.gcm.GcmNetworkManager;
</span><span class='line'>import com.google.android.gms.gcm.GcmTaskService;
</span><span class='line'>import com.google.android.gms.gcm.TaskParams;
</span><span class='line'>
</span><span class='line'>public class SyncService extends GcmTaskService {
</span><span class='line'>    @Override
</span><span class='line'>    public int onRunTask(TaskParams taskParams) {
</span><span class='line'>        // Perform your network request. Note you're already off the main thread here.
</span><span class='line'>        return GcmNetworkManager.RESULT_SUCCESS;
</span><span class='line'>    }
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>Great. So you get a callback, on a different thread, where you can do your stuff.</p>

<h1>Add the service to the manifest</h1>

<p>The instructions say to add the service to the manifest and &#8220;Add all applicable intent filters. See details for intent filter support in the GcmTaskService API reference.&#8221;</p>

<p>Note that the <a href="https://developers.google.com/android/reference/com/google/android/gms/gcm/GcmTaskService#constants">GcmTaskService documentation</a> has <code>SERVICE_ACTION_EXECUTE_TASK</code> as the name for the <code>com.google.android.gms.gcm.ACTION_TASK_READY</code> intent filter. This is right now the only thing we need to care about.</p>

<p>We also need to add the <code>RECEIVE_BOOT_COMPLETED</code> permission so that our periodic sync will persist across reboots.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;uses-permission</span> <span class="na">android:name=</span><span class="s">&quot;android.permission.INTERNET&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'><span class="nt">&lt;uses-permission</span> <span class="na">android:name=</span><span class="s">&quot;android.permission.RECEIVE_BOOT_COMPLETED&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>
</span><span class='line'><span class="nt">&lt;application</span> <span class="err">...</span> <span class="nt">&gt;</span>
</span><span class='line'>  <span class="nt">&lt;service</span>
</span><span class='line'>      <span class="na">android:name=</span><span class="s">&quot;.SyncService&quot;</span>
</span><span class='line'>      <span class="na">android:exported=</span><span class="s">&quot;true&quot;</span>
</span><span class='line'>      <span class="na">android:permission=</span><span class="s">&quot;com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>      <span class="nt">&lt;intent-filter&gt;</span>
</span><span class='line'>          <span class="nt">&lt;action</span> <span class="na">android:name=</span><span class="s">&quot;com.google.android.gms.gcm.ACTION_TASK_READY&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>      <span class="nt">&lt;/intent-filter&gt;</span>
</span><span class='line'>  <span class="nt">&lt;/service&gt;</span>
</span><span class='line'><span class="nt">&lt;/application&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<h1>Schedule a persistent task</h1>

<p>You construct a <a href="https://developers.google.com/android/reference/com/google/android/gms/gcm/PeriodicTask"><code>PeriodicTask</code></a> object using a <a href="https://developers.google.com/android/reference/com/google/android/gms/gcm/PeriodicTask.Builder"><code>Builder</code></a>, and then pass that task to a <code>GcmNetworkManager</code> instance - and that&#8217;s it! You can put this in your <code>SyncService</code> class and call <code>SyncService.scheduleSync(context)</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">scheduleSync</span><span class="o">(</span><span class="n">Context</span> <span class="n">ctx</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">GcmNetworkManager</span> <span class="n">gcmNetworkManager</span> <span class="o">=</span> <span class="n">GcmNetworkManager</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="n">ctx</span><span class="o">);</span>
</span><span class='line'>    <span class="n">PeriodicTask</span> <span class="n">periodicTask</span> <span class="o">=</span> <span class="k">new</span> <span class="n">PeriodicTask</span><span class="o">.</span><span class="na">Builder</span><span class="o">()</span>
</span><span class='line'>            <span class="o">.</span><span class="na">setPeriod</span><span class="o">(</span><span class="n">SYNC_PERIOD_SECONDS</span><span class="o">)</span> <span class="c1">// occurs at *most* once this many seconds - note that you can&#39;t control when</span>
</span><span class='line'>            <span class="o">.</span><span class="na">setRequiredNetwork</span><span class="o">(</span><span class="n">PeriodicTask</span><span class="o">.</span><span class="na">NETWORK_STATE_CONNECTED</span><span class="o">)</span> <span class="c1">// various connectivity scenarios are available</span>
</span><span class='line'>            <span class="o">.</span><span class="na">setTag</span><span class="o">(</span><span class="n">PERIODIC_SYNC_TAG</span><span class="o">)</span> <span class="c1">// returned at execution time to your endpoint</span>
</span><span class='line'>            <span class="o">.</span><span class="na">setService</span><span class="o">(</span><span class="n">SyncService</span><span class="o">.</span><span class="na">class</span><span class="o">)</span> <span class="c1">// the GcmTaskServer you created earlier</span>
</span><span class='line'>            <span class="o">.</span><span class="na">setPersisted</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="c1">// persists across reboots or not</span>
</span><span class='line'>            <span class="o">.</span><span class="na">setUpdateCurrent</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span> <span class="c1">// replace an existing task with a matching tag - defaults to false! </span>
</span><span class='line'>            <span class="o">.</span><span class="na">build</span><span class="o">();</span>
</span><span class='line'>    <span class="n">gcmNetworkManager</span><span class="o">.</span><span class="na">schedule</span><span class="o">(</span><span class="n">periodicTask</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>I&#8217;ve used the <a href="https://github.com/jonfinerty/Once">Once</a> library to ensure that my periodic sync is scheduled once per app install (on first launch). I just call this method from my Application class <code>onCreate</code>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">private</span> <span class="kt">void</span> <span class="nf">scheduleSync</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="o">(!</span><span class="n">Once</span><span class="o">.</span><span class="na">beenDone</span><span class="o">(</span><span class="n">Once</span><span class="o">.</span><span class="na">THIS_APP_INSTALL</span><span class="o">,</span> <span class="n">INIT_SYNC_ON_INSTALL</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">SyncService</span><span class="o">.</span><span class="na">scheduleSync</span><span class="o">(</span><span class="k">this</span><span class="o">);</span>
</span><span class='line'>        <span class="n">Once</span><span class="o">.</span><span class="na">markDone</span><span class="o">(</span><span class="n">INIT_SYNC_ON_INSTALL</span><span class="o">);</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<h1>Re-schedule on app update</h1>

<p>Finally, we need to ensure that our periodic task is re-scheduled after an app update by overriding the <code>onInitializeTasks</code> method.</p>

<blockquote><p>When your package is removed or updated, all of its network tasks are cleared by the GcmNetworkManager. You can override this method to reschedule them in the case of an updated package. This is not called when your application is first installed.</p>

<p>This is called on your application’s main thread.</p></blockquote>

<p>This is trivial enough to do:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="nd">@Override</span>
</span><span class='line'><span class="kd">public</span> <span class="kt">void</span> <span class="nf">onInitializeTasks</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>    <span class="kd">super</span><span class="o">.</span><span class="na">onInitializeTasks</span><span class="o">();</span>
</span><span class='line'>    <span class="c1">// Re-schedule periodic task on app upgrade.</span>
</span><span class='line'>    <span class="n">SyncService</span><span class="o">.</span><span class="na">scheduleSync</span><span class="o">(</span><span class="k">this</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<h1>Test it</h1>

<p>You can test that your background process works by firing off the intent that triggers it:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='bash'><span class='line'>adb shell am broadcast -a <span class="s2">&quot;com.google.android.gms.gcm.ACTION_TRIGGER_TASK&quot;</span> <span class="se">\</span>
</span><span class='line'>    -e component speakman.whatsshakingnz/.network.SyncService <span class="se">\</span>
</span><span class='line'>    -e tag speakman.whatsshakingnz.network.SyncService.PERIODIC_SYNC
</span></code></pre></td></tr></table></div></figure>


<p>Note <code>speakman.whatsshakingnz</code> is the package, and <code>.network.SyncService</code> is the component name within that package. You need to specify the tag you used earlier, too. If you&#8217;ve got a debugger attached you can hit a breakpoint inside your <code>onRunTask</code> method and note that you&#8217;re <em>not</em> on the main thread.</p>

<h1>Gotchas</h1>

<ul>
<li>you <strong>have to reschedule on app update</strong> - this is simple enough to do, make sure you remember to do it!</li>
<li>check for Play Services! It&#8217;s required for this to work.</li>
<li>if the network is unavailable/doesn&#8217;t meet the criteria you specified, you can&#8217;t force the task to trigger via ADB (useful to remember if you keep your test device in airplane mode!)</li>
<li>use the tags to filter out different events in the same service - <code>taskParams.getTag()</code> returns the tag that the task was created with.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Handling RealmMigrationNeededException on a fresh installation on Android]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2016/04/21/handling-realmmigrationneededexception-on-a-fresh-installation-on-android/"/>
    <updated>2016-04-21T18:33:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2016/04/21/handling-realmmigrationneededexception-on-a-fresh-installation-on-android</id>
    <content type="html"><![CDATA[<p>Back in November, I had just started using <a href="https://realm.io/">Realm</a> on Android and was having some troubles. I&#8217;d occasionally need to make a model change, and being early on in development I was happy to just delete the Realm and start again - in production you&#8217;d want to perform a migration so you don&#8217;t lose any user data.</p>

<p>However, the &#8220;delete and re-install&#8221; approach wasn&#8217;t working as expected - I kept getting a <code>RealmMigrationNeededException</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>io.realm.exceptions.RealmMigrationNeededException: RealmMigration must be provided</span></code></pre></td></tr></table></div></figure>


<p>This doesn&#8217;t make sense! I should be able to uninstall an app and upon reinstalling it I should have a fresh slate to work with. As it turns out, not quite. I couldn&#8217;t figure out why at the time, but <a href="https://github.com/realm/realm-java/issues/1856">the workaround</a> was to simply add a <code>deleteRealmMigrationIfNeeded()</code> call to my Realm configuration when building it. I made a note to deal with this before release, and carried on my way.</p>

<!-- more -->


<p>This morning I was getting ready to publish and Lint warned me that I didn&#8217;t handle <a href="http://developer.android.com/intl/es/training/backup/autosyncapi.html">Android 6.0 Marshmallow automatic backup</a>. After some investigation, I realised that this was backing up and restoring my Realm files! The order of operations which caused the above issue was:</p>

<ol>
<li>app backup occurs</li>
<li>uninstall app</li>
<li>install app (ie launching from Android Studio)</li>
<li>restore backup (note before the app launches!)</li>
<li>continue launching app</li>
</ol>


<p>It seemed simple enough to handle - I&#8217;d just exclude the <code>default.realm</code> and <code>default.realm.lock</code> files from backup and it&#8217;d work. Unfortunately this still backs up the Realm log files, all preference files (plenty of third party libraries make use of shared prefs) and even files related to instant-run! This makes a &#8220;clean install&#8221; not quite what you&#8217;d expect - not clean at all.</p>

<p>My recommendation is to explicitly <em>include</em> only the things you want. For example, I only care about my users settings - I can re-retrieve everything else remotely - so my <code>xml/backup.xml</code> looks like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="cp">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span>
</span><span class='line'><span class="nt">&lt;full-backup-content&gt;</span>
</span><span class='line'>    <span class="nt">&lt;include</span> <span class="na">domain=</span><span class="s">&quot;sharedpref&quot;</span> <span class="na">path=</span><span class="s">&quot;speakman.whatsshakingnz_preferences.xml&quot;</span><span class="nt">/&gt;</span>
</span><span class='line'><span class="nt">&lt;/full-backup-content&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>You also need to reference this file in your manifest:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;manifest</span> <span class="err">...</span> <span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;application</span> <span class="err">...</span>
</span><span class='line'>        <span class="na">android:fullBackupContent=</span><span class="s">&quot;@xml/backup&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>        ...
</span><span class='line'><span class="nt">&lt;/manifest&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that you <a href="http://stackoverflow.com/q/36773020/1217087">must specify the <code>.xml</code> extension</a> when backing up shared preferences files - this is an implementation detail we unfortunately have to worry about, which is a bit strange, especially as we both specify a domain for the file and do <em>not</em> specify the file extension in code.</p>

<p>If you&#8217;re having trouble with this, I&#8217;d also recommend <a href="http://stackoverflow.com/q/33743941/1217087">reading through this StackOverflow question &amp; answer</a>, as following through this helped a lot with figuring out what was going on.</p>

<p>Finally, the last useful bit of info I have is how to <em>wipe</em> a backup. You <em>must have the app installed</em>, and then you can wipe the existing server-side backup with:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'>adb shell bmgr wipe com.google.android.gms/.backup.BackupTransportService com.yourpackage
</span></code></pre></td></tr></table></div></figure>


<p>Note that the <code>BackupTransportService</code> part refers to the default transport for backup - you should check what yours is by running <code>adb shell bmgr list transports</code> - the default will be marked with a <code>*</code>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Automating iOS build numbers]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2015/08/30/automating-ios-build-numbers/"/>
    <updated>2015-08-30T13:21:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2015/08/30/automating-ios-build-numbers</id>
    <content type="html"><![CDATA[<p>I recently encountered some problems where I was accidentallly duplicating build numbers for our iOS app. At <a href="http://gobridgit.com">Bridgit</a> we&#8217;re big fans of automation, so I went about finding a way to avoid this human error and let the machines do the work for me.</p>

<!-- more -->


<p>We use Twitter&#8217;s <a href="http://fabric.io">Fabric</a> platform to distribute our iOS app for internal testing. The &#8220;Beta&#8221; dashboard looks a little like this:</p>

<p><img src="http://adamsp.github.com/speakman-website/images/ios-automation/fabric-beta-dashboard.png"></p>

<p>If you aren&#8217;t using this yet, I can&#8217;t recommend it enough - I can distribute a beta build to a select set of testers immediately after archive. I don&#8217;t have to deal with iTunes Connect, and as you can see, I get some great info on that distribution, such as who installed it, who&#8217;s experienced a crash, and more.</p>

<p>As you can see, each build I send out has a build number attached to it - this is set by <code>CFBundleVersion</code> in your app&#8217;s Info.plist file, or alternately by adjusting the value of the &#8220;Build&#8221; field in the &#8220;General&#8221; tab of your app target configuration.</p>

<p>You might also have noticed that some of the builds in that screenshot have the same number. Whoops. Bit difficult to check if someone&#8217;s on the latest version if the build number didn&#8217;t change! At the time, my build process was &#8220;Remember to increment build number, commit changes, press Archive, distribute build&#8221;. You can see how that might fall down - any process that includes &#8220;Remember to X&#8221; is going to fall over eventually.</p>

<h1>Avoiding human error through automation</h1>

<p>To avoid this kind of human error, we now have a handy script we&#8217;ve injected into our build process which automates the process of incrementing the build number.</p>

<figure class='code'><figcaption><span>increment-build-number.sh </span><a href='https://gist.github.com/adamsp/da0e0bab0e25412779ff'>gist</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="c">#!/bin/sh</span>
</span><span class='line'>
</span><span class='line'><span class="k">if</span> <span class="o">[</span> <span class="nv">$CONFIGURATION</span> <span class="o">==</span> Release <span class="o">]</span><span class="p">;</span> <span class="k">then</span>
</span><span class='line'><span class="k">if</span> <span class="o">[[</span> -n <span class="k">$(</span>git status --porcelain<span class="k">)</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then</span>
</span><span class='line'><span class="nb">echo</span> <span class="s2">&quot;Repository is dirty, commit your changes.&quot;</span><span class="p">;</span>
</span><span class='line'><span class="nb">exit </span>2
</span><span class='line'><span class="k">fi</span>
</span><span class='line'><span class="nb">echo</span> <span class="s2">&quot;Incrementing build number...&quot;</span>
</span><span class='line'><span class="nv">plist</span><span class="o">=</span><span class="k">${</span><span class="nv">PROJECT_DIR</span><span class="k">}</span>/<span class="k">${</span><span class="nv">INFOPLIST_FILE</span><span class="k">}</span>
</span><span class='line'>
</span><span class='line'><span class="c"># increment the build number (ie 115 to 116)</span>
</span><span class='line'><span class="nv">buildnum</span><span class="o">=</span><span class="k">$(</span>/usr/libexec/PlistBuddy -c <span class="s2">&quot;Print CFBundleVersion&quot;</span> <span class="s2">&quot;${plist}&quot;</span><span class="k">)</span>
</span><span class='line'><span class="k">if</span> <span class="o">[[</span> <span class="s2">&quot;${buildnum}&quot;</span> <span class="o">==</span> <span class="s2">&quot;&quot;</span> <span class="o">]]</span><span class="p">;</span> <span class="k">then</span>
</span><span class='line'><span class="nb">echo</span> <span class="s2">&quot;No build number in $plist&quot;</span>
</span><span class='line'><span class="nb">exit </span>2
</span><span class='line'><span class="k">fi</span>
</span><span class='line'>
</span><span class='line'><span class="nv">buildnum</span><span class="o">=</span><span class="k">$(</span>expr <span class="nv">$buildnum</span> + 1<span class="k">)</span>
</span><span class='line'>/usr/libexec/Plistbuddy -c <span class="s2">&quot;Set CFBundleVersion $buildnum&quot;</span> <span class="s2">&quot;${plist}&quot;</span>
</span><span class='line'><span class="nb">echo</span> <span class="s2">&quot;Bumped build number to $buildnum&quot;</span>
</span><span class='line'>
</span><span class='line'>git add <span class="k">${</span><span class="nv">plist</span><span class="k">}</span>
</span><span class='line'>git commit -m <span class="s2">&quot;Increment build number ($buildnum)&quot;</span>
</span><span class='line'>git tag build-<span class="nv">$buildnum</span>
</span><span class='line'>
</span><span class='line'><span class="k">else</span>
</span><span class='line'><span class="nb">echo</span> <span class="nv">$CONFIGURATION</span> <span class="s2">&quot; build - Not bumping build number.&quot;</span>
</span><span class='line'><span class="k">fi</span>
</span></code></pre></td></tr></table></div></figure>


<p>This script does the following:</p>

<ul>
<li>checks to see if the current build is a Release (archive) build

<ul>
<li>if NOT a Release build, do nothing (we don&#8217;t want to increment the build number for every Test or Debug build)</li>
</ul>
</li>
<li>checks to see if <code>git status --porcelain</code> prints anything

<ul>
<li>if something is printed, then the git repository is dirty and we shouldn&#8217;t be doing a build, abort the build</li>
</ul>
</li>
<li>checks for an existing build number

<ul>
<li>if no existing build number, abort the build</li>
</ul>
</li>
<li>increments the build number</li>
<li>commits the build number increment change to git</li>
<li>tags the new commit with the build number so we can easily find it again later</li>
</ul>


<p>Much of this I pieced together from parts of <a href="http://stackoverflow.com/q/9258344/1217087">this StackOverflow question and its answers</a>.</p>

<p>To use this, make sure it&#8217;s executable (<code>chmod +x increment-build-number.sh</code>), then add a new &#8220;Run Script Phase&#8221; to the &#8220;Build Phases&#8221; tab of your target configuration and drop in the path. I left the script at the top level of my project directory so my path is <code>${PROJECT_DIR}/increment-build-number.sh</code>.</p>

<p>To test that it&#8217;s working, make a change, don&#8217;t commit it, and attempt to build an archive - it should fail. Undo your changes, build an archive, and if it succeeds you should see a new tag listed when you run <code>git tag --list</code>.</p>

<h1>Benefits</h1>

<p>Now I can guarantee a new build number for every archive I distribute. Every time a tester reports a problem or I get a crash report, I can confirm which version they&#8217;re running without wondering if it&#8217;s <em>actually</em> the latest build or not. I no longer get submission rejections from the App Store because I forgot to increment the build.</p>

<p>Importantly, I now have git tags for every build - so if a problem shows up, I can easily find the exact place in our git history where it was introduced.</p>

<h1>Caveats</h1>

<p>This script works well as a starter solution, but it has a few caveats. I&#8217;ll address some of these in a future post - however if you&#8217;re the only developer working on a simple application, this example is likely fine to use as-is.</p>

<ul>
<li>build numbers can be duplicated if multiple developers are doing releases</li>
<li>build numbers can be duplicated if releases happen on multiple branches</li>
<li>if the git tag already exists, by the time this fails the commit has already happened and the archive process completes (but applying the tag fails quietly)</li>
<li>fails to consider different schemes and special behaviour you may want for those</li>
<li>doesn&#8217;t push the tag to remote</li>
</ul>


<p>These are all things we can fix (either through process or further automation) - <del>I&#8217;ll go over these fixes in a later post</del>.</p>

<p><strong>Edit Feb 22nd 2016:</strong> Well, I never got around to fixing the above caveats. I&#8217;m no longer with Bridgit, and never had the chance to fix the above (with the exception of the schemes issue). My entire time with Bridgit I was either the sole iOS developer, or at least the only person doing releases - so I didn&#8217;t have to worry about conflicts. My recommendation is to simply use the current epoch for build numbers (which you can acquire through <code>date +"%s"</code>), and to have a dedicated build/release machine.</p>

<p>For dealing with schemes, if I recall correctly I had 4 schemes - Debug, Development, Staging, Release. Each of these had a regular build configuration, and an archive configuration. I&#8217;d only increment build numbers if the build configuration name included &#8220;Archive&#8221;, otherwise I&#8217;d bail out (avoiding incrementing the build number every time you ran the app on the simulator!). We also used these configurations to enable analytics only on archive.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[A bug in (and a fix for) the way FragmentStatePagerAdapter handles fragment restoration]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2014/02/20/a-bug-in-and-a-fix-for-the-way-fragmentstatepageradapter-handles-fragment-restoration/"/>
    <updated>2014-02-20T21:25:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2014/02/20/a-bug-in-and-a-fix-for-the-way-fragmentstatepageradapter-handles-fragment-restoration</id>
    <content type="html"><![CDATA[<p>Ever used a <a href="https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html"><code>FragmentStatePagerAdapter</code></a>? We&#8217;re using one at work for our ticket purchasing wizard. The user enters the wizard, and can progress to the next page once they&#8217;ve completed the current one. We control this by manipulating the stack of pages and notifying the adapter that the data has changed when a new page is available.</p>

<p>Unfortunately, when changing pages that have already been loaded, there&#8217;s an unexpected bug. Specifically, when you load a page, remove it and then insert a new one in its place, the next time the fragment at that index is loaded, it receives the <code>savedInstanceState</code> bundle for the <em>old</em> fragment.</p>

<!-- more -->


<h1>How&#8217;d you find <em>that</em>?</h1>

<p>The specific use case where I discovered this was the case where a customer is purchasing tickets to a film, and they change their mind about which type of tickets they want.</p>

<p>First, the customer selects tickets that require manually selected seats. We save the tickets, receive the seating data, and send the customer to the next page where they can select from a seat in a map.</p>

<p>If the customer changes their mind at this stage and returns to the previous page, as soon as they make a change to their selected tickets we consider all future pages invalid. We &#8216;remove&#8217; the seat selection fragment and notify the adapter. If the customer has now selected tickets that <em>don&#8217;t</em> require manual seat selection (that is, they&#8217;ve chosen tickets for an unallocated seating area), we save the tickets, receive empty seating data, and know to send them on to the &#8220;details&#8221; page where they can enter in their name and email.</p>

<p>This is where the process breaks down. Since the two fragments are different (one&#8217;s called <code>SeatingFragment</code> and the other is <code>CustomerDetailsFragment</code>, say), I wasn&#8217;t expecting to receive any saved instance state on the first load of the new fragment - however I was getting state passed in! This caused a crash, as I was depending on the state being null to assume first-load.</p>

<p>The state I was seeing was the state for the previously loaded fragment at that index. That is, when the <code>CustomerDetailsFragment</code> in the example scenario was loaded (replacing the <code>SeatingFragment</code>), it was receiving the saved state bundle for the <code>SeatingFragment</code>, when it should&#8217;ve been receiving no saved state bundle at all.</p>

<h1>Can you reproduce it?</h1>

<p>I&#8217;ve written a <a href="https://github.com/adamsp/FragmentStatePagerIssueExample">very simple example app</a> which shows this behaviour. If you swipe backwards and forwards you can see the fragments labeled &#8220;1&#8221;, &#8220;2&#8221;, &#8220;3&#8221;, colored Red, Yellow and Green. Now, press the &#8216;Switch Fragment&#8217; button. You&#8217;ll be sent back to index 0 (fragment &#8220;1&#8221;). This forces the removal of fragment &#8220;3&#8221;, which gets its state saved. But we&#8217;ve changed the content of the adapter - so next time you load fragment &#8220;3&#8221;, you&#8217;ll see that its color has changed to Blue. <strong>This is a different fragment</strong>, but it&#8217;s label has been restored from the previous fragments saved state! If you rotate your device, or simply swipe back to the first view and then back to the third again, you&#8217;ll see the correct label of &#8220;4&#8221; (it saves the state fresh when it removes it, resulting in the correct saved state next time it&#8217;s loaded).</p>

<h1>Why does this occur?</h1>

<p>If we take a look at the source code <a href="https://android.googlesource.com/platform/frameworks/support/+/6d6186b9a2503200844febe1b8ba083206c7cbcd/v4/java/android/support/v4/app/FragmentStatePagerAdapter.java">as of this writing</a>, we can see that the <code>FragmentStatePagerAdapter</code> stores a list of states:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>private ArrayList&lt;Fragment.SavedState&gt; mSavedState = new ArrayList&lt;Fragment.SavedState&gt;();</span></code></pre></td></tr></table></div></figure>


<p>Looking through the code we can see that this array is used in four places. It&#8217;s used in <code>instantiateItem</code>, <code>destroyItem</code>, <code>saveState</code> and <code>restoreState</code>.  We can ignore <code>saveState</code> and <code>restoreState</code> for now, as they&#8217;re just saving the adapters overall state into an external bundle, and then loading it back up.</p>

<p>First, let&#8217;s take a look at what&#8217;s going on in <code>destroyItem</code>. When a fragment is due to be destroyed, this method first starts a transaction (if one isn&#8217;t already started), then pads out the <code>mSavedState</code> array with null entries until it&#8217;s at least the size of the index of the fragment we&#8217;re removing.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>@Override
</span><span class='line'>public void destroyItem(ViewGroup container, int position, Object object) {
</span><span class='line'>    Fragment fragment = (Fragment)object;
</span><span class='line'>
</span><span class='line'>    if (mCurTransaction == null) {
</span><span class='line'>        mCurTransaction = mFragmentManager.beginTransaction();
</span><span class='line'>    }
</span><span class='line'>    if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
</span><span class='line'>            + " v=" + ((Fragment)object).getView());
</span><span class='line'>    while (mSavedState.size() &lt;= position) {
</span><span class='line'>        mSavedState.add(null);
</span><span class='line'>    }</span></code></pre></td></tr></table></div></figure>


<p>Nothing too exciting there. It then saves the state of the fragment that is being removed into the corresponding index in the <code>mSavedState</code> list, and removes the fragment:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
</span><span class='line'>    mFragments.set(position, null);
</span><span class='line'>
</span><span class='line'>    mCurTransaction.remove(fragment);
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>Now let&#8217;s see what happens in the other direction - instantiating an item. First thing to do is check and see if we already have a <code>Fragment</code> object created and stored at the given position. Short-circuit back out with this if we do:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>@Override
</span><span class='line'>public Object instantiateItem(ViewGroup container, int position) {
</span><span class='line'>    // If we already have this item instantiated, there is nothing
</span><span class='line'>    // to do.  This can happen when we are restoring the entire pager
</span><span class='line'>    // from its saved state, where the fragment manager has already
</span><span class='line'>    // taken care of restoring the fragments we previously had instantiated.
</span><span class='line'>    if (mFragments.size() &gt; position) {
</span><span class='line'>        Fragment f = mFragments.get(position);
</span><span class='line'>        if (f != null) {
</span><span class='line'>            return f;
</span><span class='line'>        }
</span><span class='line'>    }</span></code></pre></td></tr></table></div></figure>


<p>If however we <em>don&#8217;t</em> have a fragment there, we have to create one. This could be because we&#8217;ve never seen this page of the <code>ViewPager</code> before, or it could be because the page was removed due to the left/right limits (recall a <code>ViewPager</code> will only keep the first page to the left and right of the current one, by default).</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    if (mCurTransaction == null) {
</span><span class='line'>        mCurTransaction = mFragmentManager.beginTransaction();
</span><span class='line'>    }
</span><span class='line'>
</span><span class='line'>    Fragment fragment = getItem(position);
</span><span class='line'>    if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);</span></code></pre></td></tr></table></div></figure>


<p>Now, here&#8217;s the important part. After we&#8217;ve asked our concrete subclass to create/instantiate a fragment for us (through the <code>getItem(position)</code> call), we check to see if we have any saved state <em>at that position</em>. There&#8217;s the crucial part - we&#8217;re <strong>checking for saved state based on the fragments index in an array, rather than on some unique property of the fragment</strong>.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    if (mSavedState.size() &gt; position) {
</span><span class='line'>        Fragment.SavedState fss = mSavedState.get(position);
</span><span class='line'>        if (fss != null) {
</span><span class='line'>            fragment.setInitialSavedState(fss);
</span><span class='line'>        }
</span><span class='line'>    }</span></code></pre></td></tr></table></div></figure>


<p>The issue with this is that the fragment at that position may no longer be the same fragment as was there last time we displayed the page at this position! So that saved state bundle may no longer be the correct one.</p>

<p>Finally, we add the fragment to our list of fragments and display it:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    while (mFragments.size() &lt;= position) {
</span><span class='line'>        mFragments.add(null);
</span><span class='line'>    }
</span><span class='line'>    fragment.setMenuVisibility(false);
</span><span class='line'>    fragment.setUserVisibleHint(false);
</span><span class='line'>    mFragments.set(position, fragment);
</span><span class='line'>    mCurTransaction.add(container.getId(), fragment);
</span><span class='line'>
</span><span class='line'>    return fragment;
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<h1>Fixes or workarounds?</h1>

<p>Luckily, there&#8217;s a way around this problem! Hurrah!</p>

<p>We simply need some way of identifying the fragments, and comparing whether this identifying value is the same or not when we try to restore state to a freshly instantiated fragment. The best way to do this is to ask our concrete subclass for an identifier for this fragment - a tag.</p>

<p>So, let&#8217;s copy the <a href="https://android.googlesource.com/platform/frameworks/support/+/master/v4/java/android/support/v4/app/FragmentStatePagerAdapter.java">entire source of <code>FragmentStatePagerAdapter</code></a> and get started. First thing to do is add a way of getting tags from our subclasses. Since we don&#8217;t want to break existing implementations that don&#8217;t actually care about swapping out fragments, we won&#8217;t make this method abstract. Instead it&#8217;ll just <code>return null;</code> by default, and we treat that as the default case, reproducing existing behaviour.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>public String getTag(int position) {
</span><span class='line'>    return null;
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>Ok, so now we have a way of getting the tags, let&#8217;s add an <code>ArrayList&lt;String&gt;</code> member variable to track our fragment tags:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>private ArrayList&lt;String&gt; mSavedFragmentTags = new ArrayList&lt;String&gt;();</span></code></pre></td></tr></table></div></figure>


<p>Now we go through and handle this in all 4 places where <code>mSavedState</code> is touched.</p>

<p>In <code>instantiateItem</code> we must find the tag for the newly instantiated fragment first. Once we&#8217;ve got that, if we have saved state we can then compare this new tag with the saved tag. If they match, then we restore the state! If they don&#8217;t, then we don&#8217;t restore state. Easy.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    Fragment fragment = getItem(position);
</span><span class='line'>    String fragmentTag = getTag(position);
</span><span class='line'>    if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment + " t=" + fragmentTag);
</span><span class='line'>    if (mSavedState.size() &gt; position) {
</span><span class='line'>        String savedTag = mSavedFragmentTags.get(position);
</span><span class='line'>        if (TextUtils.equals(fragmentTag, savedTag)) {
</span><span class='line'>            Fragment.SavedState fss = mSavedState.get(position);
</span><span class='line'>            if (fss != null) {
</span><span class='line'>                fragment.setInitialSavedState(fss);
</span><span class='line'>            }
</span><span class='line'>        }
</span><span class='line'>    }</span></code></pre></td></tr></table></div></figure>


<p>Note that we also add the fragment using the <a href="https://developer.android.com/reference/android/support/v4/app/FragmentTransaction.html#add(int,"><code>FragmentTransaction#add (int containerViewId, Fragment fragment, String tag)</code></a> signature - that is, we actually use the tag when adding our fragment:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    mCurTransaction.add(container.getId(), fragment, fragmentTag);
</span><span class='line'>
</span><span class='line'>    return fragment;
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>In <code>destroyItem</code> we just mirror what&#8217;s done to <code>mSavedState</code>. We pad it out if necessary&#8230;</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object
</span><span class='line'>            + " v=" + ((Fragment)object).getView() + " t=" + fragment.getTag());
</span><span class='line'>    while (mSavedState.size() &lt;= position) {
</span><span class='line'>        mSavedState.add(null);
</span><span class='line'>        mSavedFragmentTags.add(null);
</span><span class='line'>    }</span></code></pre></td></tr></table></div></figure>


<p>&#8230;then we save the tag at that location.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>    mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
</span><span class='line'>    mSavedFragmentTags.set(position, fragment.getTag());
</span><span class='line'>    mFragments.set(position, null);
</span><span class='line'>
</span><span class='line'>    mCurTransaction.remove(fragment);
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>Finally we have the <code>saveState</code> and <code>restoreState</code> methods. These are pretty trival changes. In <code>saveState</code> we put the saved fragment tags into the <code>Bundle</code>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>state.putStringArrayList("tags", mSavedFragmentTags);</span></code></pre></td></tr></table></div></figure>


<p>And then in <code>restoreState</code>, surprise, we restore the saved fragment tags from the bundle:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>mSavedFragmentTags = bundle.getStringArrayList("tags");</span></code></pre></td></tr></table></div></figure>


<p>Two last things to do:</p>

<ul>
<li>Change your subclass to override your new, fixed, adapter (rather than the one in the support library)</li>
<li>Remember to <strong>override <code>getTag(int position)</code></strong> to return a unique tag for each fragment</li>
</ul>


<p>If you forget either of these things, you&#8217;ll just have the same behaviour as before. In my <a href="https://github.com/adamsp/FragmentStatePagerIssueExample">demo app</a>, this would look something like the following - obviously you&#8217;ll need to adjust this to suit your own data source:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>@Override
</span><span class='line'>public String getTag(int position) {
</span><span class='line'>    return labels[position];
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>And that&#8217;s it! Those&#8217;re the changes we need to make to the <code>FragmentStatePagerAdapter</code> for it to stop misbehaving and restoring the wrong state to fragments in different locations.</p>

<p>You can find a complete example of this fixed class <a href="https://github.com/adamsp/FragmentStatePagerIssueExample/blob/master/app/src/main/java/com/example/fragmentstatepagerissueexample/app/FixedFragmentStatePagerAdapter.java">in the sample project</a>. There&#8217;s some lines commented out in the adapter in <code>MainActivity</code>; just swap the class definition and uncomment the method and you&#8217;ve magically got an adapter working as expected!</p>

<h1>That&#8217;s great! Any gotchas?</h1>

<p>Sure are.</p>

<ul>
<li>Remember to override <code>getTag(int position)</code>, or else you&#8217;ll continue to see the old behaviour.</li>
<li><code>getTag(int position)</code> must return a <em>unique</em> tag for each fragment.</li>
<li>If your <code>FragmentStatePagerAdapter</code> is an inner class of a <code>Fragment</code>, <em>and</em> you&#8217;re calling that fragments <code>getTag()</code> method, then that call will now give a compile error. You&#8217;ll need to change it to <code>MyParentFragment.this.getTag()</code> instead, <em>or</em> change the fixed adapter to use a different method signature - <code>getFragmentTag(int position)</code>, perhaps.</li>
<li>You won&#8217;t automatically receive bug fixes and updates to the <code>FragmentStatePagerAdapter</code> when the support library updates. This is unlikely to be an issue though - it&#8217;s been in source for <a href="https://android.googlesource.com/platform/frameworks/support/+log/refs/heads/master/v4/java/android/support/v4/app/FragmentStatePagerAdapter.java">over 18 months as of this writing</a> (Feb 20, 2014) without a single change (the <a href="https://android.googlesource.com/platform/frameworks/support/+log/refs/heads/master/v13/java/android/support/v13/app/FragmentStatePagerAdapter.java">v13 version, too</a>).</li>
<li>If you want to use a different key to put the saved tags into/restore from the bundle (other than just &#8220;tags&#8221; like I&#8217;ve used here), make sure it doesn&#8217;t start with &#8220;f&#8221; - note how a little further down in the <code>restoreState</code> method it checks for keys starting with &#8220;f&#8221; and assumes they&#8217;re fragments!</li>
</ul>


<h1>Thanks! You saved the day.</h1>

<p>No worries! Maybe one day you&#8217;ll write a post on how to fix some obscure bug that I&#8217;m having trouble with.</p>

<p>If you have any questions, you can ask me on <a href="https://twitter.com/adamsnz">Twitter</a>, or <a href="https://plus.google.com/+AdamSpeakman">Google+</a>, or open an issue on (or send a pull request to) the <a href="https://github.com/adamsp/FragmentStatePagerIssueExample">Github project</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Broken JSONObject creation from a UTF-8 input String]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/12/17/broken-jsonobject-creation-from-a-utf-8-input-string/"/>
    <updated>2013-12-17T06:04:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/12/17/broken-jsonobject-creation-from-a-utf-8-input-string</id>
    <content type="html"><![CDATA[<blockquote><p>12-16 12:01:40.446: W/System.err(3873): org.json.JSONException: Value ﻿  of type java.lang.String cannot be converted to JSONObject</p></blockquote>

<p>Faced this issue, again, at work today. We have a build system with build variants for different customers. To add a new customer, we just create a new folder, add the images and add a JSON config file to suit the new customers settings. We read from that file and into a JSON string (and then into a JSON object) something like this:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>InputStream inStream = context.getResources().openRawResource(R.raw.local_config);
</span><span class='line'>String json = IOUtils.toString(inStream);
</span><span class='line'>JSONObject jsonObject = new JSONObject(json);</span></code></pre></td></tr></table></div></figure>


<p>Sometimes, new customers speak a language other than English, and we have to save non-ASCII characters. In this case, the file gets saved as UTF-8. Testing this isn&#8217;t a problem on my devices (Galaxy S2/Nexus 7) - but my tester has twice come back to me now and said that it doesn&#8217;t work on our 2.3 device.</p>

<!-- more -->


<p>Figuring out the problem this time was pretty quick - I plugged her test phone in, saw this error popping up in Logcat and it triggered my memory about what was wrong. The problem is that the value hidden in that error message (encoded in this case as <code>0xEF 0xBB 0xBF</code>, often showing up as ï»¿ - see the <a href="http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding">Wikipedia page</a>) is a Byte Order Mark. This is used to signal the <a href="http://en.wikipedia.org/wiki/Endianness">endianess</a> of the text stream. However, in UTF-8 it probably shouldn&#8217;t even be there (but is still technically legitimate):</p>

<blockquote><p>The Unicode Standard permits the BOM in UTF-8, but does not require nor recommend its use. Byte order has no meaning in UTF-8, so its only use in UTF-8 is to signal at the start that the text stream is encoded in UTF-8.</p><footer><strong>Wikipedia</strong> <cite><a href='http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8'>en.wikipedia.org/wiki/&hellip;</a></cite></footer></blockquote>


<p>Because of this, Java doesn&#8217;t actually support automatically reading the BOM as an indicator of encoding - it adds it as part of the string, so you have to strip it out.  If you don&#8217;t, automatic parsers such as the one built into JSONObject may freak out and give you a confusing error like the one above. Reading the message, it <em>appears</em> that it can&#8217;t convert a String, which doesn&#8217;t make sense, as the constructor takes a String. It&#8217;s actually referring to the invisible (or in some cases barely visible) BOM character between the words &#8220;Value&#8221; and &#8220;of&#8221;.</p>

<p>So why is it working correctly on my devices? <a href="https://code.google.com/p/android/issues/detail?id=18508">This bug</a> logged in 2011 was &#8216;fixed&#8217; by updating the built in JSON reader to handle UTF-8 strings with or without the Byte Order Mark. This change came in with Ice Cream Sandwich (Android 4.0) - hence why my tester is seeing the problem and I am not.</p>

<p>The fix in our case has been to simply fix the file - the BOM shouldn&#8217;t be there anyway, so we just remove it. You can do this in Notepad++ by opening the UTF-8 file, clicking the Encoding menu and selecting &#8220;Encode in UTF-8 without BOM&#8221;. This may show up as &#8220;ANSI as UTF-8&#8221; in the encoding field at the bottom-right.</p>

<p>The other, more general option (if you can&#8217;t control the source of the JSON you&#8217;re trying to parse) is to always &#8216;clean&#8217; your incoming JSON string. This workaround was suggested in the original bug:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>public Reader inputStreamToReader(InputStream in) throws IOException {
</span><span class='line'>    in.mark(3);
</span><span class='line'>    int byte1 = in.read();
</span><span class='line'>    int byte2 = in.read();
</span><span class='line'>    if (byte1 == 0xFF && byte2 == 0xFE) {
</span><span class='line'>      return new InputStreamReader(in, "UTF-16LE");
</span><span class='line'>    } else if (byte1 == 0xFF && byte2 == 0xFF) {
</span><span class='line'>      return new InputStreamReader(in, "UTF-16BE");
</span><span class='line'>    } else {
</span><span class='line'>      int byte3 = in.read();
</span><span class='line'>      if (byte1 == 0xEF && byte2 == 0xBB && byte3 == 0xBF) {
</span><span class='line'>        return new InputStreamReader(in, "UTF-8");
</span><span class='line'>      } else {
</span><span class='line'>        in.reset();
</span><span class='line'>        return new InputStreamReader(in);
</span><span class='line'>      }
</span><span class='line'>    }
</span><span class='line'>}</span></code></pre></td></tr></table></div></figure>


<p>There are also <a href="http://stackoverflow.com/questions/1835430/byte-order-mark-screws-up-file-reading-in-java">many</a>, <a href="http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/input/BOMInputStream.html">many</a> other solutions available.</p>

<p>Wonderful. Note that if you know your file is encoded a certain way, you should <em>always</em> pass the encoding to the reader - never depend on the default charset to be what you need. It&#8217;s worth spending some time reading about <a href="http://en.wikipedia.org/wiki/Unicode">Unicode</a> and the various encodings you&#8217;re likely to encounter - <a href="http://en.wikipedia.org/wiki/Windows-1252">Windows-1252 (or CP-1252)</a>, <a href="http://en.wikipedia.org/wiki/UTF-8">UTF-8</a> and <a href="http://en.wikipedia.org/wiki/UTF-16">UTF-16</a>, and how to interpret the bytes for these encodings. I find <a href="http://www.fileformat.info/info/unicode/char/FEFF/index.htm">fileformat.info</a> to be extremely useful, as well as the <a href="http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/">HexEditor Notepad++ plugin</a> for looking directly at the bytes (which is reportedly a bit unstable with the latest version of NP++, though I&#8217;ve never had any issues) - there will no doubt be something similar either built in to or available for your text editor of choice.</p>

<p>Text encoding problems are painful to deal with - and if you&#8217;re not sure what you should be using, <a href="http://www.utf8everywhere.org/">use UTF-8</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Getting started with Volley for Android]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/11/25/getting-started-with-volley-for-android/"/>
    <updated>2013-11-25T17:55:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/11/25/getting-started-with-volley-for-android</id>
    <content type="html"><![CDATA[<p><a href="https://android.googlesource.com/platform/frameworks/volley">Volley</a> is a new Android networking library from Google (well, by ‘new’ I mean from <a href="https://developers.google.com/events/io/sessions/325304728">May, at I/O 2013</a> - so some 7 months ago). It has some cool features - request queueing with priorities, automatic selection of the best HTTP library <a href="https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/Volley.java">depending on Android version</a>, and a nifty view for <a href="https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/NetworkImageView.java">automatically loading images</a>. Unfortunately, even 7 months on, there’s pretty minimal documentation available. However across StackOverflow, a bunch of blogs and the source code, there’s plenty to go on to figure out how to do some basic tasks.</p>

<!-- more -->


<p></p>

<h2>Getting the library</h2>

<p>I’ll assume you have <a href="http://git-scm.com/">git</a> and <a href="http://ant.apache.org/">ant</a> installed.</p>

<p>First, we have to get the library:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>git clone https://android.googlesource.com/platform/frameworks/volley</span></code></pre></td></tr></table></div></figure>


<p>Now we have the source code, we need to build it:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>cd volley
</span><span class='line'>ant jar</span></code></pre></td></tr></table></div></figure>


<p>Now, we have <code>volley.jar</code> in the <code>bin</code> directory. Copy this into <code>libs</code> in Eclipse (via drag &amp; drop through the GUI so it sets everything up properly) or set it up in your <code>build.gradle</code> if you’re using Studio. Wonderful.</p>

<h2>Some basic setup</h2>

<p>Volley works by sending requests to a <code>RequestQueue</code>. To create one of these requests, you override the <code>Request</code> object and implement a few methods:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">queue</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="k">new</span> <span class="n">Request</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;(</span><span class="n">Method</span><span class="o">.</span><span class="na">GET</span><span class="o">,</span> <span class="n">url</span><span class="o">,</span> <span class="n">errorListener</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">protected</span> <span class="n">Response</span><span class="o">&lt;</span><span class="n">String</span><span class="o">&gt;</span> <span class="nf">parseNetworkResponse</span><span class="o">(</span><span class="n">NetworkResponse</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// TODO Auto-generated method stub</span>
</span><span class='line'>      <span class="k">return</span> <span class="kc">null</span><span class="o">;</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">protected</span> <span class="kt">void</span> <span class="nf">deliverResponse</span><span class="o">(</span><span class="n">String</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// TODO Auto-generated method stub</span>
</span><span class='line'>      
</span><span class='line'>  <span class="o">}});</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can send these with a priority (by overriding <code>getPriority()</code>), so that higher priority requests get sent to the front of the queue, not the back. Useful if, for example, you’re loading some images in the background, but the user clicks on something that needs immediate download.</p>

<p>Before we can use a queue, we have to set one up. This should done as a singleton. Since the easiest way of creating a <code>RequestQueue</code> requires a <code>Context</code>, you can either subclass <code>Application</code> (which the official docs advise against) or do it this way:</p>

<figure class='code'><figcaption><span>VolleyProvider.java</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">VolleyProvider</span> <span class="o">{</span>
</span><span class='line'>    <span class="kd">private</span> <span class="kd">static</span> <span class="n">RequestQueue</span> <span class="n">queue</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="nf">VolleyProvider</span><span class="o">()</span> <span class="o">{</span> <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="kd">static</span> <span class="kd">synchronized</span> <span class="n">RequestQueue</span> <span class="nf">getQueue</span><span class="o">(</span><span class="n">Context</span> <span class="n">ctx</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">queue</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="n">queue</span> <span class="o">=</span> <span class="n">Volley</span><span class="o">.</span><span class="na">newRequestQueue</span><span class="o">(</span><span class="n">ctx</span><span class="o">.</span><span class="na">getApplicationContext</span><span class="o">());</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">queue</span><span class="o">;</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And usage:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">RequestQueue</span> <span class="n">queue</span> <span class="o">=</span> <span class="n">VolleyProvider</span><span class="o">.</span><span class="na">getQueue</span><span class="o">(</span><span class="n">mContext</span><span class="o">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are a few other ways of constructing a queue, allowing you to specify your own HTTP stack, cache, thread pool size, etc.</p>

<h2>Now let’s GET some JSON</h2>

<p>So now we&#8217;ve got our default queue set up, we can send a request. As you saw earlier, a request requires you to implement two methods - <code>parseNetworkResponse</code> and <code>deliverResponse</code>. The first of these methods parses your network response into some object that you&#8217;re expecting, <strong>from a worker thread</strong>. The second delivers that response back to your UI thread, <strong>unless <code>parseNetworkResponse</code> returns <code>null</code></strong>.</p>

<p>To fetch some simple JSON back from a given URL, there&#8217;s a convenient utility class that comes packaged in <code>com.android.volley.toolbox</code> called <code>JsonRequest</code>.</p>

<p>This class manages parsing any request body string into a byte array (the <code>getBody</code> method returns a <code>byte[]</code>), as well as specifying the content type headers, etc. You still have to implement the <code>parseNetworkResponse</code> abstract method from before, though you now supply a listener for the success case instead of an override. So now our request looks a bit like this (using <a href="https://code.google.com/p/google-gson/">Gson</a> for parsing the response, because it&#8217;s awesome):</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Person</span> <span class="o">{</span>
</span><span class='line'>  <span class="kt">long</span> <span class="n">id</span><span class="o">;</span>
</span><span class='line'>  <span class="n">String</span> <span class="n">firstName</span><span class="o">;</span>
</span><span class='line'>  <span class="n">String</span> <span class="n">lastName</span><span class="o">;</span>
</span><span class='line'>  <span class="n">String</span> <span class="n">address</span><span class="o">;</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">...</span>
</span><span class='line'>
</span><span class='line'><span class="n">String</span> <span class="n">url</span> <span class="o">=</span> <span class="s">&quot;http://person.com/person?id=1234&quot;</span><span class="o">;</span>
</span><span class='line'><span class="n">Request</span> <span class="n">request</span> <span class="o">=</span> <span class="k">new</span> <span class="n">JsonRequest</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;(</span><span class="n">Method</span><span class="o">.</span><span class="na">GET</span><span class="o">,</span> <span class="n">url</span><span class="o">,</span> <span class="kc">null</span><span class="o">,</span> <span class="k">new</span> <span class="n">Listener</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;()</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onResponse</span><span class="o">(</span><span class="n">Person</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// Do something with our person object </span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">},</span> <span class="k">new</span> <span class="n">Response</span><span class="o">.</span><span class="na">ErrorListener</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onErrorResponse</span><span class="o">(</span><span class="n">VolleyError</span> <span class="n">error</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// Handle the error </span>
</span><span class='line'>      <span class="c1">// error.networkResponse.statusCode</span>
</span><span class='line'>      <span class="c1">// error.networkResponse.data</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">})</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">protected</span> <span class="n">Response</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="nf">parseNetworkResponse</span><span class="o">(</span><span class="n">NetworkResponse</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">String</span> <span class="n">jsonString</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">String</span><span class="o">(</span><span class="n">response</span><span class="o">.</span><span class="na">data</span><span class="o">,</span> <span class="n">HttpHeaderParser</span><span class="o">.</span><span class="na">parseCharset</span><span class="o">(</span><span class="n">response</span><span class="o">.</span><span class="na">headers</span><span class="o">));</span>
</span><span class='line'>      <span class="n">Person</span> <span class="n">person</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">GsonBuilder</span><span class="o">().</span><span class="na">create</span><span class="o">().</span><span class="na">fromJson</span><span class="o">(</span><span class="n">jsonString</span><span class="o">,</span> <span class="n">Person</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
</span><span class='line'>      <span class="n">Response</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="n">result</span> <span class="o">=</span> <span class="n">Response</span><span class="o">.</span><span class="na">success</span><span class="o">(</span><span class="n">person</span><span class="o">,</span> <span class="n">HttpHeaderParser</span><span class="o">.</span><span class="na">parseCacheHeaders</span><span class="o">(</span><span class="n">response</span><span class="o">));</span>
</span><span class='line'>      <span class="k">return</span> <span class="n">result</span><span class="o">;</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">};</span>
</span><span class='line'><span class="n">queue</span><span class="o">.</span><span class="na">add</span><span class="o">(</span><span class="n">request</span><span class="o">);</span>
</span></code></pre></td></tr></table></div></figure>


<h2>And POST some back to the server</h2>

<p>POSTing JSON back is equally as easy! Instead of passing in null for our body, we pass in a JSON String.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">String</span> <span class="n">url</span> <span class="o">=</span> <span class="s">&quot;http://person.com/person/update?id=1234&quot;</span><span class="o">;</span>
</span><span class='line'><span class="n">String</span> <span class="n">body</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">GsonBuilder</span><span class="o">().</span><span class="na">create</span><span class="o">().</span><span class="na">toJson</span><span class="o">(</span><span class="n">somePerson</span><span class="o">);</span>
</span><span class='line'><span class="n">Request</span> <span class="n">request</span> <span class="o">=</span> <span class="k">new</span> <span class="n">JsonRequest</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;(</span><span class="n">Method</span><span class="o">.</span><span class="na">POST</span><span class="o">,</span> <span class="n">url</span><span class="o">,</span> <span class="n">body</span><span class="o">,</span> <span class="k">new</span> <span class="n">Listener</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;()</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onResponse</span><span class="o">(</span><span class="n">Person</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// Do something with our person object </span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">},</span> <span class="k">new</span> <span class="n">Response</span><span class="o">.</span><span class="na">ErrorListener</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onErrorResponse</span><span class="o">(</span><span class="n">VolleyError</span> <span class="n">error</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// Handle the error </span>
</span><span class='line'>      <span class="c1">// error.networkResponse.statusCode</span>
</span><span class='line'>      <span class="c1">// error.networkResponse.data</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">})</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">protected</span> <span class="n">Response</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="nf">parseNetworkResponse</span><span class="o">(</span><span class="n">NetworkResponse</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">String</span> <span class="n">jsonString</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">String</span><span class="o">(</span><span class="n">response</span><span class="o">.</span><span class="na">data</span><span class="o">,</span> <span class="n">HttpHeaderParser</span><span class="o">.</span><span class="na">parseCharset</span><span class="o">(</span><span class="n">response</span><span class="o">.</span><span class="na">headers</span><span class="o">));</span>
</span><span class='line'>      <span class="n">Person</span> <span class="n">person</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">GsonBuilder</span><span class="o">().</span><span class="na">create</span><span class="o">().</span><span class="na">fromJson</span><span class="o">(</span><span class="n">jsonString</span><span class="o">,</span> <span class="n">Person</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
</span><span class='line'>      <span class="n">Response</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;</span> <span class="n">result</span> <span class="o">=</span> <span class="n">Response</span><span class="o">.</span><span class="na">success</span><span class="o">(</span><span class="n">person</span><span class="o">,</span> <span class="n">HttpHeaderParser</span><span class="o">.</span><span class="na">parseCacheHeaders</span><span class="o">(</span><span class="n">response</span><span class="o">));</span>
</span><span class='line'>      <span class="k">return</span> <span class="n">result</span><span class="o">;</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">};</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Is there an easier way?</h2>

<p>Sort-of. I&#8217;ve abstracted the JSON parsing out so you only have to handle the success and the failure cases. If you&#8217;ve got more complex objects that need custom type adapters, you could put the Gson object creation and type adapter registration into another class somewhere and call it from here. Just drop this <code>GsonRequest</code> class in and you can use it by simply passing in the class of object you expect, as follows.</p>

<figure class='code'><figcaption><span>GsonRequest.java </span><a href='https://gist.github.com/adamsp/7637132'>link</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
<span class='line-number'>49</span>
<span class='line-number'>50</span>
<span class='line-number'>51</span>
<span class='line-number'>52</span>
<span class='line-number'>53</span>
<span class='line-number'>54</span>
<span class='line-number'>55</span>
<span class='line-number'>56</span>
<span class='line-number'>57</span>
<span class='line-number'>58</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="cm">/**</span>
</span><span class='line'><span class="cm"> * Copyright 2013 Adam Speakman</span>
</span><span class='line'><span class="cm"> * </span>
</span><span class='line'><span class="cm"> * Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);</span>
</span><span class='line'><span class="cm"> * you may not use this file except in compliance with the License.</span>
</span><span class='line'><span class="cm"> * You may obtain a copy of the License at</span>
</span><span class='line'><span class="cm"> * </span>
</span><span class='line'><span class="cm"> *    http://www.apache.org/licenses/LICENSE-2.0</span>
</span><span class='line'><span class="cm"> * </span>
</span><span class='line'><span class="cm"> * Unless required by applicable law or agreed to in writing, software</span>
</span><span class='line'><span class="cm"> * distributed under the License is distributed on an &quot;AS IS&quot; BASIS,</span>
</span><span class='line'><span class="cm"> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.</span>
</span><span class='line'><span class="cm"> * See the License for the specific language governing permissions and</span>
</span><span class='line'><span class="cm"> * limitations under the License.</span>
</span><span class='line'><span class="cm"> */</span>
</span><span class='line'><span class="kn">package</span> <span class="n">your</span><span class="o">.</span><span class="na">package</span><span class="o">.</span><span class="na">here</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'><span class="kn">import</span> <span class="nn">java.io.UnsupportedEncodingException</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.NetworkResponse</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.ParseError</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.Response</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.Response.ErrorListener</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.Response.Listener</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.toolbox.HttpHeaderParser</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.android.volley.toolbox.JsonRequest</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.google.gson.GsonBuilder</span><span class="o">;</span>
</span><span class='line'><span class="kn">import</span> <span class="nn">com.google.gson.JsonSyntaxException</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">GsonRequest</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="kd">extends</span> <span class="n">JsonRequest</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">Class</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">mResponseClass</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="nf">GsonRequest</span><span class="o">(</span><span class="kt">int</span> <span class="n">method</span><span class="o">,</span> <span class="n">String</span> <span class="n">url</span><span class="o">,</span> <span class="n">String</span> <span class="n">requestBody</span><span class="o">,</span> <span class="n">Class</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">responseClass</span><span class="o">,</span> <span class="n">Listener</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">listener</span><span class="o">,</span>
</span><span class='line'>            <span class="n">ErrorListener</span> <span class="n">errorListener</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="kd">super</span><span class="o">(</span><span class="n">method</span><span class="o">,</span> <span class="n">url</span><span class="o">,</span> <span class="n">requestBody</span><span class="o">,</span> <span class="n">listener</span><span class="o">,</span> <span class="n">errorListener</span><span class="o">);</span>
</span><span class='line'>        <span class="n">mResponseClass</span> <span class="o">=</span> <span class="n">responseClass</span><span class="o">;</span>
</span><span class='line'>        <span class="c1">// Do some generic stuff in here - for example, set your retry policy to</span>
</span><span class='line'>        <span class="c1">// longer if you know all your requests are going to take &gt; 2.5 seconds</span>
</span><span class='line'>        <span class="c1">// etc etc...</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="nd">@Override</span>
</span><span class='line'>    <span class="kd">protected</span> <span class="n">Response</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="nf">parseNetworkResponse</span><span class="o">(</span><span class="n">NetworkResponse</span> <span class="n">networkResponse</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">try</span> <span class="o">{</span>
</span><span class='line'>            <span class="n">String</span> <span class="n">jsonString</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">String</span><span class="o">(</span><span class="n">networkResponse</span><span class="o">.</span><span class="na">data</span><span class="o">,</span> <span class="n">HttpHeaderParser</span><span class="o">.</span><span class="na">parseCharset</span><span class="o">(</span><span class="n">networkResponse</span><span class="o">.</span><span class="na">headers</span><span class="o">));</span>
</span><span class='line'>            <span class="n">T</span> <span class="n">response</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">GsonBuilder</span><span class="o">().</span><span class="na">create</span><span class="o">().</span><span class="na">fromJson</span><span class="o">(</span><span class="n">jsonString</span><span class="o">,</span> <span class="n">mResponseClass</span><span class="o">);</span>
</span><span class='line'>            <span class="n">com</span><span class="o">.</span><span class="na">android</span><span class="o">.</span><span class="na">volley</span><span class="o">.</span><span class="na">Response</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;</span> <span class="n">result</span> <span class="o">=</span> <span class="n">com</span><span class="o">.</span><span class="na">android</span><span class="o">.</span><span class="na">volley</span><span class="o">.</span><span class="na">Response</span><span class="o">.</span><span class="na">success</span><span class="o">(</span><span class="n">response</span><span class="o">,</span>
</span><span class='line'>                    <span class="n">HttpHeaderParser</span><span class="o">.</span><span class="na">parseCacheHeaders</span><span class="o">(</span><span class="n">networkResponse</span><span class="o">));</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">result</span><span class="o">;</span>
</span><span class='line'>        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">UnsupportedEncodingException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">com</span><span class="o">.</span><span class="na">android</span><span class="o">.</span><span class="na">volley</span><span class="o">.</span><span class="na">Response</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="k">new</span> <span class="nf">ParseError</span><span class="o">(</span><span class="n">e</span><span class="o">));</span>
</span><span class='line'>        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="n">JsonSyntaxException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="k">return</span> <span class="n">com</span><span class="o">.</span><span class="na">android</span><span class="o">.</span><span class="na">volley</span><span class="o">.</span><span class="na">Response</span><span class="o">.</span><span class="na">error</span><span class="o">(</span><span class="k">new</span> <span class="nf">ParseError</span><span class="o">(</span><span class="n">e</span><span class="o">));</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And usage:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">Request</span> <span class="n">request</span> <span class="o">=</span> <span class="k">new</span> <span class="n">GsonRequest</span><span class="o">&lt;</span><span class="n">T</span><span class="o">&gt;(</span><span class="n">Method</span><span class="o">.</span><span class="na">POST</span><span class="o">,</span> <span class="n">url</span><span class="o">,</span> <span class="n">body</span><span class="o">,</span> <span class="n">Person</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="k">new</span> <span class="n">Listener</span><span class="o">&lt;</span><span class="n">Person</span><span class="o">&gt;()</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onResponse</span><span class="o">(</span><span class="n">Person</span> <span class="n">response</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// Do something with our person object </span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">},</span> <span class="k">new</span> <span class="n">Response</span><span class="o">.</span><span class="na">ErrorListener</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>  <span class="nd">@Override</span>
</span><span class='line'>  <span class="kd">public</span> <span class="kt">void</span> <span class="nf">onErrorResponse</span><span class="o">(</span><span class="n">VolleyError</span> <span class="n">error</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>      <span class="c1">// Handle the error </span>
</span><span class='line'>      <span class="c1">// error.networkResponse.statusCode</span>
</span><span class='line'>      <span class="c1">// error.networkResponse.data</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">});</span>
</span></code></pre></td></tr></table></div></figure>


<h2>What about that easy image loading?</h2>

<p>Loading images with Volley is one of my favourite features of the library. Once it&#8217;s setup, it&#8217;s really easy to use. It handles loading images off the UI thread, can show a default image and an error one, and handles caching all for you. You need to set up an <code>ImageLoader</code>, similar to how you set up the <code>RequestQueue</code> as a singleton:</p>

<figure class='code'><figcaption><span>ImageLoaderProvider.java</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">ImageLoaderProvider</span> <span class="o">{</span>
</span><span class='line'>    <span class="kd">private</span> <span class="kd">static</span> <span class="n">ImageLoader</span> <span class="n">imageLoader</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="nf">ImageLoaderProvider</span><span class="o">()</span> <span class="o">{</span> <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="kd">static</span> <span class="kd">synchronized</span> <span class="n">ImageLoader</span> <span class="nf">getImageLoader</span><span class="o">(</span><span class="n">Context</span> <span class="n">ctx</span><span class="o">,</span> <span class="n">RequestQueue</span> <span class="n">queue</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">imageLoader</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="n">imageLoader</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">ImageLoader</span><span class="o">(</span><span class="n">queue</span><span class="o">,</span> <span class="k">new</span> <span class="nf">LruBitmapCache</span><span class="o">(</span><span class="n">getCacheSize</span><span class="o">(</span><span class="n">ctx</span><span class="o">)));</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>        <span class="k">return</span> <span class="n">imageLoader</span><span class="o">;</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>  
</span><span class='line'>  <span class="cm">/**</span>
</span><span class='line'><span class="cm">  * Returns a cache size equal to approximately three screens worth of images.</span>
</span><span class='line'><span class="cm">  */</span>
</span><span class='line'>  <span class="kd">private</span> <span class="kt">int</span> <span class="nf">getCacheSize</span><span class="o">(</span><span class="n">Context</span> <span class="n">ctx</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="kd">final</span> <span class="n">DisplayMetrics</span> <span class="n">displayMetrics</span> <span class="o">=</span> <span class="n">ctx</span><span class="o">.</span><span class="na">getResources</span><span class="o">().</span><span class="na">getDisplayMetrics</span><span class="o">();</span>
</span><span class='line'>        <span class="kd">final</span> <span class="kt">int</span> <span class="n">screenWidth</span> <span class="o">=</span> <span class="n">displayMetrics</span><span class="o">.</span><span class="na">widthPixels</span><span class="o">;</span>
</span><span class='line'>        <span class="kd">final</span> <span class="kt">int</span> <span class="n">screenHeight</span> <span class="o">=</span> <span class="n">displayMetrics</span><span class="o">.</span><span class="na">heightPixels</span><span class="o">;</span>
</span><span class='line'>        <span class="kd">final</span> <span class="kt">int</span> <span class="n">screenBytes</span> <span class="o">=</span> <span class="n">screenWidth</span> <span class="o">*</span> <span class="n">screenHeight</span> <span class="o">*</span> <span class="mi">4</span><span class="o">;</span> <span class="c1">// 4 bytes per pixel</span>
</span><span class='line'>
</span><span class='line'>        <span class="k">return</span> <span class="n">screenBytes</span> <span class="o">*</span> <span class="mi">3</span><span class="o">;</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now, replace your <code>ImageView</code> objects with <code>NetworkImageView</code> ones:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;com.android.volley.toolbox.NetworkImageView</span>
</span><span class='line'>    <span class="na">android:id=</span><span class="s">&quot;@+id/some_image&quot;</span>
</span><span class='line'>    <span class="err">...</span> <span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>And finally, all you need to do is pass your <code>NetworkImageView</code> the URL of the image you&#8217;d like loaded, and the <code>ImageLoader</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">ImageLoader</span> <span class="n">imageLoader</span> <span class="o">=</span> <span class="n">ImageLoaderProvider</span><span class="o">.</span><span class="na">getImageLoader</span><span class="o">(</span><span class="n">mContext</span><span class="o">,</span> <span class="n">VolleyProvider</span><span class="o">.</span><span class="na">getQueue</span><span class="o">(</span><span class="n">mContext</span><span class="o">));</span>
</span><span class='line'><span class="o">((</span><span class="n">NetworkImageView</span><span class="o">)</span><span class="n">findViewById</span><span class="o">(</span><span class="n">R</span><span class="o">.</span><span class="na">id</span><span class="o">.</span><span class="na">some_image</span><span class="o">)).</span><span class="na">setImageUrl</span><span class="o">(</span><span class="n">imgUrl</span><span class="o">,</span> <span class="n">imageLoader</span><span class="o">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are also methods available such as <code>setDefaultImageResId</code> and <code>setErrorImageResId</code>, for supplying default and error resources.</p>

<h2>Anything else?</h2>

<p>Volley has a default TTL on requests of 2.5 seconds - after this, it&#8217;ll retry the request. This can result in some unexpected behaviour - for example where your error listener gets called (immediately after the retry), then your success listener gets called a little while later (when the original request returns). You can fix this by specifying a timeout in your request:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">REQUEST_TIMEOUT_MS</span> <span class="o">=</span> <span class="mi">10000</span><span class="o">;</span>
</span><span class='line'><span class="o">...</span>
</span><span class='line'><span class="n">request</span><span class="o">.</span><span class="na">setRetryPolicy</span><span class="o">(</span><span class="k">new</span> <span class="nf">DefaultRetryPolicy</span><span class="o">(</span><span class="n">REQUEST_TIMEOUT_MS</span><span class="o">,</span> <span class="n">DefaultRetryPolicy</span><span class="o">.</span><span class="na">DEFAULT_MAX_RETRIES</span><span class="o">,</span> <span class="n">DefaultRetryPolicy</span><span class="o">.</span><span class="na">DEFAULT_BACKOFF_MULT</span><span class="o">));</span>
</span></code></pre></td></tr></table></div></figure>


<p>Another thing to be aware of is that the image loading will cache images in the full size they come down as. This means if you’re downloading images at full resolution but only displaying them at a much smaller one, you’re going to be caching them at full res. If this is in a list view, you’re going to be pushing stuff out of the cache (and then re-downloading them) a lot more often than desirable.</p>

<p>You can get around this by changing some code in <a href="https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/NetworkImageView.java"><code>NetworkImageView</code></a>. The important bit is near the end of the <code>loadImageIfNecessary(final boolean isInLayoutPass)</code> method. The code makes a call to the following method in the <code>ImageLoader</code> class:</p>

<figure class='code'><figcaption><span>ImageLoader.java </span><a href='https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/ImageLoader.java'>link</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="n">ImageContainer</span> <span class="nf">get</span><span class="o">(</span><span class="n">String</span> <span class="n">requestUrl</span><span class="o">,</span> <span class="kd">final</span> <span class="n">ImageListener</span> <span class="n">listener</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="nf">get</span><span class="o">(</span><span class="n">requestUrl</span><span class="o">,</span> <span class="n">listener</span><span class="o">,</span> <span class="mi">0</span><span class="o">,</span> <span class="mi">0</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Notice how that calls an overload that takes some <code>int</code> values?</p>

<figure class='code'><figcaption><span>ImageLoader.java </span><a href='https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/ImageLoader.java'>link</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="n">ImageContainer</span> <span class="nf">get</span><span class="o">(</span><span class="n">String</span> <span class="n">requestUrl</span><span class="o">,</span> <span class="n">ImageListener</span> <span class="n">imageListener</span><span class="o">,</span>
</span><span class='line'>            <span class="kt">int</span> <span class="n">maxWidth</span><span class="o">,</span> <span class="kt">int</span> <span class="n">maxHeight</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="o">...</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Well, if we ‘fix’ the code back in <code>NetworkImageView</code> to pass in the width &amp; height of the view, then the image gets scaled down and cached at the smaller size (this takes is utilised in the <code>doParse</code> method of <a href="https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/ImageRequest.java"><code>ImageRequest</code></a>:</p>

<figure class='code'><figcaption><span>NetworkImageLoader.java</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="n">ImageContainer</span> <span class="n">newContainer</span> <span class="o">=</span> <span class="n">mImageLoader</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">mUrl</span><span class="o">,</span>
</span><span class='line'>    <span class="k">new</span> <span class="nf">ImageListener</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>        <span class="o">...</span>
</span><span class='line'>    <span class="o">},</span>
</span><span class='line'>    <span class="n">getMeasuredWidth</span><span class="o">(),</span>
</span><span class='line'>    <span class="n">getMeasuredHeight</span><span class="o">());</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note that if you pass the image URL in for use in a different place, <strong>it’ll use the (scaled down) image from the cache</strong> - so if you need the full resolution image, this solution will need some modification.</p>

<h2>Wow, Volley can do lots of stuff!</h2>

<p>And I certainly haven&#8217;t covered all of it here. There&#8217;s loads more that it can do. I&#8217;d recommend looking through some of the classes in <code>com.android.volley.toolbox</code> to see what else is already written for you, and for some ideas of how to use some of the other cool features it has to offer.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Handling OutOfMemoryError with large bitmaps on older Android devices]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/11/10/handling-outofmemoryerror-with-large-bitmaps-on-older-android-devices/"/>
    <updated>2013-11-10T12:42:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/11/10/handling-outofmemoryerror-with-large-bitmaps-on-older-android-devices</id>
    <content type="html"><![CDATA[<p>If you&#8217;ve ever worked with bitmaps on an Android device before, you&#8217;ve <a href="http://stackoverflow.com/questions/477572/strange-out-of-memory-issue-while-loading-an-image-to-a-bitmap-object">likely</a> <a href="http://stackoverflow.com/questions/14235287/suggestions-to-avoid-bitmap-out-of-memory-error?lq=1">encountered</a> the <a href="https://code.google.com/p/android/issues/detail?id=8488">dreaded</a> <code>OutOfMemoryError</code> &#8216;bitmap size exceeds VM budget&#8217;. This issue can present itself immediately when testing, however on older devices it may not manifest except in certain cases. The reason for this is as follows:</p>

<blockquote><p>In addition, prior to Android 3.0 (API Level 11), the backing data of a bitmap was stored in native memory which is not released in a predictable manner, potentially causing an application to briefly exceed its memory limits and crash.</p><footer><strong>Android Developer Documentation</strong> <cite><a href='http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html'>developer.android.com/training/&hellip;</a></cite></footer></blockquote>


<p>Depending on what you&#8217;re doing, there is a way to get around this.</p>

<!-- more -->


<p>The situation where I encountered this was at work when working on a control for displaying a seat map for a movie theatre as part of a ticket purchasing wizard. It shows the screen, the seats, some seat numbers, etc. From there the app user is able to pick seats to sit in for watching the movie. Previously this had been built by drawing many <code>Button</code> controls with a custom drawable. This was terribly inefficient, as all those controls had to be totally redrawn whenever the user tried to zoom, and was practically unusable for large theatres (with hundreds of seats) even on top end devices.</p>

<p>Clearly this was due for a rewrite. The method I worked out for doing this was to create a &#8216;base&#8217; bitmap from the theatre data showing all empty and already-sold seats. I&#8217;d use this as a static base image, and then paint &#8216;selected&#8217; seats on top of that as the user taps to select/deselect seats they&#8217;d like to sit in.</p>

<p>This method had a few benefits we didn&#8217;t enjoy with the old method:</p>

<ul>
<li>we only had to create the whole theatre model (calculating seat positions etc) once, when creating the base image (previously it was re-calculating seat sizes and locations at every zoom level, ugh)</li>
<li>since it was an image, we could now just drop it inside a <a href="https://github.com/MikeOrtiz/TouchImageView">TouchImageView</a> and that would handle zooming and panning (and <a href="https://github.com/MikeOrtiz/TouchImageView/pull/33">this pull request</a> maps touch inputs back to our original image co-ordinates after zoom)</li>
<li>the static base image meant we only had to perform N+1 passes across the canvas when drawing seat selections, where N was the number of selected seats (typically low, so this is very fast)</li>
</ul>


<p>So off I went and coded this brilliant design. The code for the <code>SeatingImageView</code> control ended up looking <em>something</em> like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SeatingImageView</span> <span class="kd">extends</span> <span class="n">TouchImageView</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="n">Bitmap</span> <span class="n">mImmutableBase</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setBaseImage</span><span class="o">(</span><span class="n">Bitmap</span> <span class="n">baseImage</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">baseImage</span><span class="o">.</span><span class="na">isMutable</span><span class="o">())</span>
</span><span class='line'>            <span class="n">baseImage</span> <span class="o">=</span> <span class="n">Bitmap</span><span class="o">.</span><span class="na">createBitmap</span><span class="o">(</span><span class="n">baseImage</span><span class="o">);</span> <span class="c1">// Immutable copy</span>
</span><span class='line'>        <span class="n">mImmutableBase</span> <span class="o">=</span> <span class="n">baseImage</span><span class="o">;</span>
</span><span class='line'>        <span class="n">setImageBitmap</span><span class="o">(</span><span class="n">mImmutableBaseBitmap</span><span class="o">.</span><span class="na">copy</span><span class="o">(</span><span class="n">Bitmap</span><span class="o">.</span><span class="na">Config</span><span class="o">.</span><span class="na">ARGB_8888</span><span class="o">,</span> <span class="kc">true</span><span class="o">));</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">drawSeats</span><span class="o">(</span><span class="n">List</span><span class="o">&lt;</span><span class="n">Drawable</span><span class="o">&gt;</span> <span class="n">seats</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">mImmutableBase</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="k">return</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">Bitmap</span> <span class="n">mutable</span> <span class="o">=</span> <span class="n">immutablebase</span><span class="o">.</span><span class="na">copy</span><span class="o">(</span><span class="n">Bitmap</span><span class="o">.</span><span class="na">Config</span><span class="o">.</span><span class="na">ARGB_8888</span><span class="o">,</span> <span class="kc">true</span><span class="o">);</span>
</span><span class='line'>        <span class="n">Canvas</span> <span class="n">canvas</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">Canvas</span><span class="o">(</span><span class="n">mutable</span><span class="o">);</span>
</span><span class='line'>        <span class="k">for</span><span class="o">(</span><span class="n">Drawable</span> <span class="n">seat</span> <span class="o">:</span> <span class="n">seats</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="n">seat</span><span class="o">.</span><span class="na">draw</span><span class="o">(</span><span class="n">canvas</span><span class="o">);</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">setImageBitmap</span><span class="o">(</span><span class="n">mutable</span><span class="o">);</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>So you&#8217;d set your base image, then overlay some selected seat images on top of that as necessary. I tested this on my phone (Galaxy SII i9100, Android 4.1) and my Nexus 7 (2012 model, Android 4.3) and sent it off to QA to be approved.</p>

<p>But our tester sent it back. She said it was crashing whenever she selected a seat - but only on certain cinemas. This was odd, as I couldn&#8217;t replicate it at all. I went and had a chat to her, and sure enough, it was definitely crashing on her device (an old HTC running Android 2.3). I borrowed the phone and went about figuring this out.</p>

<p>Of course, it was the dreaded <code>OutOfMemoryError</code>. But how to fix this? I was already capping the size of the bitmap when building the base image and scaling seats down to fit. If I forced the max size to be lower, then large cinemas started to look awfully pixelated when zoomed in. I did some logging of the memory, and it appeared that the OOM was occurring at the time we created the new image with the seats - <code>Bitmap mutable = immutablebase.copy(Bitmap.Config.ARGB_8888, true);</code>.</p>

<p>We had in memory at this point 3 copies of the bitmap:</p>

<ol>
<li>the immutable base image that wasn&#8217;t being displayed (<code>mImmutableBase</code>)</li>
<li>the <em>copy</em> of the immutable base we&#8217;d created that was currently being displayed to the user (<code>setImageBitmap(mImmutableBaseBitmap.copy(Bitmap.Config.RGB_8888, true));</code>)</li>
<li>the copy we&#8217;d <em>just created</em> to draw the newly selected seats onto (<code>Bitmap mutable = immutablebase.copy(Bitmap.Config.RGB_8888, true);</code>)</li>
</ol>


<p>That seemed easy enough to handle - we&#8217;d just get rid of the one being displayed before we created a copy of the immutable base, then we&#8217;d only ever have 2 in memory at once. I updated my <code>drawSeats</code> method to look like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kt">void</span> <span class="nf">drawSeats</span><span class="o">(</span><span class="n">List</span><span class="o">&lt;</span><span class="n">Drawable</span><span class="o">&gt;</span> <span class="n">seats</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">if</span> <span class="o">(</span><span class="n">mImmutableBase</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="k">return</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">setImageBitmap</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span> <span class="c1">// Clear all references to the existing bitmap</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">Bitmap</span> <span class="n">mutable</span> <span class="o">=</span> <span class="n">immutablebase</span><span class="o">.</span><span class="na">copy</span><span class="o">(</span><span class="n">Bitmap</span><span class="o">.</span><span class="na">Config</span><span class="o">.</span><span class="na">ARGB_8888</span><span class="o">,</span> <span class="kc">true</span><span class="o">);</span>
</span><span class='line'>    <span class="n">Canvas</span> <span class="n">canvas</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">Canvas</span><span class="o">(</span><span class="n">mutable</span><span class="o">);</span>
</span><span class='line'>    <span class="k">for</span><span class="o">(</span><span class="n">Drawable</span> <span class="n">seat</span> <span class="o">:</span> <span class="n">seats</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">seat</span><span class="o">.</span><span class="na">draw</span><span class="o">(</span><span class="n">canvas</span><span class="o">);</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">setImageBitmap</span><span class="o">(</span><span class="n">mutable</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>But this didn&#8217;t work either!</p>

<p>Reading through <a href="https://code.google.com/p/android/issues/detail?id=8488#c80">this thread</a> (post #80 down is especially useful) helps to shed some light on what&#8217;s causing us to run out of memory here. The bitmap has memory in both the native and Dalvik heap, and it&#8217;s not getting recycled from native quickly enough. Luckily, there is a way to force this to occur.</p>

<p>The fix was to:</p>

<ol>
<li>acquire a reference to the bitmap that is currently being shown - <code>getDrawable()</code></li>
<li>tell the <code>ImageView</code> to show nothing - <code>setImageBitmap(null)</code> - while still holding a reference to the old bitmap</li>
<li>manually call <code>recycle()</code> on the old bitmap - this clears the native heap allocation</li>
<li>although we <em>shouldn&#8217;t have to</em> call <code>System.gc()</code>, I found that this was still required to consistently remove the bitmap from memory</li>
</ol>


<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SeatingImageView</span> <span class="kd">extends</span> <span class="n">TouchImageView</span> <span class="o">{</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="n">Bitmap</span> <span class="n">mImmutableBase</span><span class="o">;</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">setBaseImage</span><span class="o">(</span><span class="n">Bitmap</span> <span class="n">baseImage</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">baseImage</span><span class="o">.</span><span class="na">isMutable</span><span class="o">())</span>
</span><span class='line'>            <span class="n">baseImage</span> <span class="o">=</span> <span class="n">Bitmap</span><span class="o">.</span><span class="na">createBitmap</span><span class="o">(</span><span class="n">baseImage</span><span class="o">);</span> <span class="c1">// Immutable copy</span>
</span><span class='line'>        <span class="n">mImmutableBase</span> <span class="o">=</span> <span class="n">baseImage</span><span class="o">;</span>
</span><span class='line'>        <span class="n">setImageBitmap</span><span class="o">(</span><span class="n">mImmutableBaseBitmap</span><span class="o">.</span><span class="na">copy</span><span class="o">(</span><span class="n">Bitmap</span><span class="o">.</span><span class="na">Config</span><span class="o">.</span><span class="na">ARGB_8888</span><span class="o">,</span> <span class="kc">true</span><span class="o">));</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">drawSeats</span><span class="o">(</span><span class="n">List</span><span class="o">&lt;</span><span class="n">Drawable</span><span class="o">&gt;</span> <span class="n">seats</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">mImmutableBase</span> <span class="o">==</span> <span class="kc">null</span><span class="o">)</span> <span class="k">return</span><span class="o">;</span>
</span><span class='line'>        <span class="n">recycleOldImage</span><span class="o">();</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">Bitmap</span> <span class="n">mutable</span> <span class="o">=</span> <span class="n">immutablebase</span><span class="o">.</span><span class="na">copy</span><span class="o">(</span><span class="n">Bitmap</span><span class="o">.</span><span class="na">Config</span><span class="o">.</span><span class="na">ARGB_8888</span><span class="o">,</span> <span class="kc">true</span><span class="o">);</span>
</span><span class='line'>        <span class="n">Canvas</span> <span class="n">canvas</span> <span class="o">=</span> <span class="k">new</span> <span class="nf">Canvas</span><span class="o">(</span><span class="n">mutable</span><span class="o">);</span>
</span><span class='line'>        <span class="k">for</span><span class="o">(</span><span class="n">Drawable</span> <span class="n">seat</span> <span class="o">:</span> <span class="n">seats</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="n">seat</span><span class="o">.</span><span class="na">draw</span><span class="o">(</span><span class="n">canvas</span><span class="o">);</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>        <span class="n">setImageBitmap</span><span class="o">(</span><span class="n">mutable</span><span class="o">);</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="kd">private</span> <span class="kt">void</span> <span class="nf">recycleOldImage</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>        <span class="n">Drawable</span> <span class="n">oldImage</span> <span class="o">=</span> <span class="n">getDrawable</span><span class="o">();</span>
</span><span class='line'>        <span class="k">if</span> <span class="o">(</span><span class="n">oldImage</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>            <span class="n">setImageBitmap</span><span class="o">(</span><span class="kc">null</span><span class="o">);</span>
</span><span class='line'>            <span class="n">BitmapDrawable</span> <span class="n">oldBitmap</span> <span class="o">=</span> <span class="o">(</span><span class="n">BitmapDrawable</span><span class="o">)</span><span class="n">oldImage</span><span class="o">;</span>
</span><span class='line'>            <span class="n">oldBitmap</span><span class="o">.</span><span class="na">getBitmap</span><span class="o">().</span><span class="na">recycle</span><span class="o">();</span>
</span><span class='line'>            <span class="n">System</span><span class="o">.</span><span class="na">gc</span><span class="o">();</span>
</span><span class='line'>        <span class="o">}</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>This fixed the bug! The memory logging I’d put in showed that were were only keeping at max two copies of the base image in memory at a time, and more importantly we weren’t seeing any crashes.</p>

<p>However, the logs were also showing that we were still precariously close to the memory limit for the device. I was concerned about other devices with <a href="http://stackoverflow.com/questions/4351678/two-questions-about-max-heap-sizes-and-available-memory-in-android">even lower memory limits</a> - or other edge case theatre layouts we didn’t have examples for. This required something of a minor design change to resolve.</p>

<p>I&#8217;d been depending on using ARGB_8888 config for the alpha channel, providing a transparent background behind the seat images to match the background for the rest of the screen. After some experimentation I discovered that there was no noticable change in the colour of my seat images when switching to RGB_565, but the memory usage dropped by a large amount - enough that I was happy I wasn&#8217;t going to hit the cap again. It was simple enough to modify the control to take a &#8216;background&#8217; colour at creation, which reproduced the effects of transparency. Of course if you&#8217;re faced with the same situation but are using a background with a gradient, or a colour not accurately reproducable in RGB_565, this will not work for you as easily.</p>

<p>Other tips:</p>

<ul>
<li>use RGB_565 if you can - it uses a lot less memory than ARGB_8888 (2 bytes per pixel instead of 4)</li>
<li>if you&#8217;re debugging memory issues with bitmaps, <strong>use an Android 3.0 or higher device</strong> to debug, since bitmap memory allocations are reflected correctly in the Dalvik heap on these devices (see the <a href="http://developer.android.com/training/articles/memory.html#Bitmaps">memory docs</a>)</li>
<li>always test on the lowest spec device you have available to you, even if you&#8217;re not doing all your development on that</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Android Currency Localisation Hell]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/10/21/android-currency-localisation-hell/"/>
    <updated>2013-10-21T17:45:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/10/21/android-currency-localisation-hell</id>
    <content type="html"><![CDATA[<p>We had a customer at work recently who had a special requirement around multiple currency support in our Android app. They have cinema sites in multiple countries, and they want customers to see the correct currency symbol when viewing sessions for a site. Up until now, the app has only ever had to deal with single currencies on a per-customer (and hence per-build) basis.</p>

<p>While implementing this multiple currency support, I came across something of a problem - the Android Currency code doesn&#8217;t behave quite as you&#8217;d hope, and is inconsistent across versions. Sometimes you get a currency symbol where you&#8217;re supposed to, sometimes you don&#8217;t - and sometimes the symbol is a slightly different symbol in one locale to that which is in another (￥, I&#8217;m looking at you). I&#8217;ve now got a set of <a href="https://github.com/adamsp/CurrencyFormattingDemo">test cases</a> which do a fair job of explaining the issue, as well as the solution we came up with which <em>mostly</em> works.</p>

<!-- more -->


<h3>The status quo</h3>

<p>Our app is designed to use a JSON configuration file to set customer-specific settings during build, including a single default currency symbol which we were prepending to the currency value. The items being purchased in the app all come down from a web service, and the values are specified in cents - every value gets divided by 100 to get the &#8216;true&#8217; value for the currency. This is legacy behaviour in the service backend that has been in place for over a decade and cannot be changed.</p>

<p>Luckily however, we can <em>add</em> to it. The design that came through initially was simply to allow the customer to specify a currency symbol on a per-site basis, and then expose this via the web service. Being developers, we didn&#8217;t feel this was good enough. What about the case where the &#8216;special case&#8217; sites (that is, the ones which don&#8217;t match the default currency symbol) are in a different currency with the same symbol? (NZ$/AU$, or CA$/US$) Eventually we settled on specifying an <a href="http://en.wikipedia.org/wiki/ISO_4217">ISO 4217 currency code</a> <strong>per location that is a special case</strong> - 3 characters, and they&#8217;re associated with a symbol. This is populated in a drop-down list in the existing configuration application for the site.</p>

<p>So, now we&#8217;ve got this currency code coming through for these special case sites. We should be able to format currency values using this, right? According to the <a href="http://developer.android.com/reference/java/util/Currency.html">Currency documentation</a>, we can. Our intent was to format the currency <strong>value</strong> (whether numbers appear as 15,00 € like in France, or as $15.00 like in the US) using the device locale, while customising the currency <strong>symbol</strong> - this would provide optimum readability for the user (the value appears in the format they&#8217;re most used to) while also providing an accurate representation of what currency the figure is in.</p>

<p>So, after a bit of research I figured I should be able to write code like this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="n">String</span> <span class="nf">getFormattedCurrencyString</span><span class="o">(</span><span class="n">String</span> <span class="n">isoCurrencyCode</span><span class="o">,</span> <span class="kt">double</span> <span class="n">amount</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="c1">// This formats currency values as the user expects to read them (default locale).</span>
</span><span class='line'>  <span class="n">NumberFormat</span> <span class="n">currencyFormat</span> <span class="o">=</span> <span class="n">NumberFormat</span><span class="o">.</span><span class="na">getCurrencyInstance</span><span class="o">();</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// This specifies the actual currency that the value is in, and provides the currency symbol.</span>
</span><span class='line'>  <span class="n">Currency</span> <span class="n">currency</span> <span class="o">=</span> <span class="n">Currency</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="n">isoCurrencyCode</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// Note we don&#39;t supply a locale to this method - uses default locale to format the currency symbol.</span>
</span><span class='line'>  <span class="n">String</span> <span class="n">symbol</span> <span class="o">=</span> <span class="n">currency</span><span class="o">.</span><span class="na">getSymbol</span><span class="o">();</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// We then tell our formatter to use this symbol.</span>
</span><span class='line'>  <span class="n">DecimalFormatSymbols</span> <span class="n">decimalFormatSymbols</span> <span class="o">=</span> <span class="o">((</span><span class="n">java</span><span class="o">.</span><span class="na">text</span><span class="o">.</span><span class="na">DecimalFormat</span><span class="o">)</span> <span class="n">currencyFormat</span><span class="o">).</span><span class="na">getDecimalFormatSymbols</span><span class="o">();</span>
</span><span class='line'>  <span class="n">decimalFormatSymbols</span><span class="o">.</span><span class="na">setCurrencySymbol</span><span class="o">(</span><span class="n">symbol</span><span class="o">);</span>
</span><span class='line'>  <span class="o">((</span><span class="n">java</span><span class="o">.</span><span class="na">text</span><span class="o">.</span><span class="na">DecimalFormat</span><span class="o">)</span> <span class="n">currencyFormat</span><span class="o">).</span><span class="na">setDecimalFormatSymbols</span><span class="o">(</span><span class="n">decimalFormatSymbols</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="k">return</span> <span class="n">currencyFormat</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="n">amount</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Unfortunately, while I initially tested this with one or two samples and figured it would work as advertised, I was wrong.</p>

<h3>Certain locales cannot localise currencies</h3>

<p>As I was writing unit tests for this, I discovered that I wasn&#8217;t getting expected results. I was running these tests on a device (a Galaxy S II) set to New Zealand locale - and my tests were failing. When I ran them on an emulator (which defaults to US locale), I got <em>different</em> results - some of the failing tests passed, but I got a new set of failures.</p>

<p>The failures on my device were cases where I was getting the ISO currency code back instead of the symbol. &#8220;AUD&#8221; instead of &#8220;AU$&#8221;, etc. The case where I supplied &#8220;NZD&#8221; I was expecting &#8220;NZ$&#8221; - yet I was getting &#8220;$&#8221;, and not &#8220;NZD&#8221; like the others. And even more confusing, these tests were passing on the emulator - I was getting the expected symbols!</p>

<p>So I tried supplying a <code>Locale</code> object and using that, rather than the device default, so I could see what behaviour I got on a variety of locales:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="n">String</span> <span class="nf">getFormattedCurrencyStringForLocale</span><span class="o">(</span><span class="n">Locale</span> <span class="n">locale</span><span class="o">,</span> <span class="n">String</span> <span class="n">isoCurrencyCode</span><span class="o">,</span> <span class="kt">double</span> <span class="n">amount</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="c1">// This formats currency values as the user expects to read them (default locale).</span>
</span><span class='line'>  <span class="n">NumberFormat</span> <span class="n">currencyFormat</span> <span class="o">=</span> <span class="n">NumberFormat</span><span class="o">.</span><span class="na">getCurrencyInstance</span><span class="o">(</span><span class="n">locale</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// This specifies the actual currency that the value is in, and provides the currency symbol.</span>
</span><span class='line'>  <span class="n">Currency</span> <span class="n">currency</span> <span class="o">=</span> <span class="n">Currency</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="n">isoCurrencyCode</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// Note we don&#39;t supply a locale to this method - uses default locale to format the currency symbol.</span>
</span><span class='line'>  <span class="n">String</span> <span class="n">symbol</span> <span class="o">=</span> <span class="n">currency</span><span class="o">.</span><span class="na">getSymbol</span><span class="o">(</span><span class="n">locale</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// We then tell our formatter to use this symbol.</span>
</span><span class='line'>  <span class="n">DecimalFormatSymbols</span> <span class="n">decimalFormatSymbols</span> <span class="o">=</span> <span class="o">((</span><span class="n">java</span><span class="o">.</span><span class="na">text</span><span class="o">.</span><span class="na">DecimalFormat</span><span class="o">)</span> <span class="n">currencyFormat</span><span class="o">).</span><span class="na">getDecimalFormatSymbols</span><span class="o">();</span>
</span><span class='line'>  <span class="n">decimalFormatSymbols</span><span class="o">.</span><span class="na">setCurrencySymbol</span><span class="o">(</span><span class="n">symbol</span><span class="o">);</span>
</span><span class='line'>  <span class="o">((</span><span class="n">java</span><span class="o">.</span><span class="na">text</span><span class="o">.</span><span class="na">DecimalFormat</span><span class="o">)</span> <span class="n">currencyFormat</span><span class="o">).</span><span class="na">setDecimalFormatSymbols</span><span class="o">(</span><span class="n">decimalFormatSymbols</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="k">return</span> <span class="n">currencyFormat</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="n">amount</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Looking at the code above, the line <code>String symbol = currency.getSymbol()</code> is the one that fetches the symbol. The <code>getSymbol()</code> method has an overload <code>getSymbol(Locale locale)</code>. If I took the step of passing this method the <code>locale</code> parameter, I got different results. Interesting!</p>

<p>The <a href="http://developer.android.com/reference/java/util/Currency.html">documentation</a> for <code>public String getSymbol (Locale locale)</code> in the <code>Currency</code> class says:</p>

<blockquote><p>Added in API level 1<br/>Returns the localized currency symbol for this currency in locale. That is, given &#8220;USD&#8221; and Locale.US, you&#8217;d get &#8220;$&#8221;, but given &#8220;USD&#8221; and a non-US locale, you&#8217;d get &#8220;US$&#8221;.</p><p>If the locale only specifies a language rather than a language and a country (such as Locale.JAPANESE or {new Locale(&#8220;en&#8221;, &#8220;&#8221;)} rather than Locale.JAPAN or {new Locale(&#8220;en&#8221;, &#8220;US&#8221;)}), the ISO 4217 currency code is returned.</p><p>If there is no locale-specific currency symbol, the ISO 4217 currency code is returned.</p></blockquote>


<p>The important part there is the last bit. <strong>If there is no locale-specific currency symbol, the ISO 4217 currency code is returned.</strong> That&#8217;s what I was seeing - if the locale didn&#8217;t &#8216;know&#8217; how to format a currency symbol for the supplied currency, it would just return the currency code.</p>

<p>Huh, okay. How do we fix that, then?</p>

<p>As it turns out, the US locale has formatting for <em>most</em> currency codes. It doesn&#8217;t quite match in some cases (it might provide UK£ instead of £UK, for example) and in certain scenarios it doesn&#8217;t have a symbol, but for the most part, it&#8217;s better than anything else. There&#8217;s one case where we don&#8217;t want this to use the US locale though - USD ISO code, with a non-US device locale. We can fix that with a hard coded symbol of &#8216;US$&#8217;.</p>

<p>There is also the issue that when the currency code matches the users locale (for example, NZD and en_NZ locale), the users see NZ$ rather than $. We handle this internally by utilising our existing behaviour of having a default currency symbol specified in the app build. If we receive a response that contains a currency code, we utilise the code for getting a currency symbol for that code. If we don&#8217;t receive a currency code (which is the case most of the time, to maintain backwards compatibility, and the majority of cinemas don&#8217;t actually support multiple countries), we just use the symbol from the build config. That code isn&#8217;t shown here, but it&#8217;s a simple check to see if the <code>isoCurrencyCode</code> value is null or empty, and if it is then we use the default symbol.</p>

<p>So, the final version of the method is as follows. Note that we still use the device locale for formatting the numbers, and where the symbol goes within the string - we only use US locale for the symbol itself.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="kd">static</span> <span class="n">String</span> <span class="nf">getFormattedCurrencyString</span><span class="o">(</span><span class="n">String</span> <span class="n">isoCurrencyCode</span><span class="o">,</span> <span class="kt">double</span> <span class="n">amount</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="c1">// This formats currency values as the user expects to read them (default locale).</span>
</span><span class='line'>  <span class="n">NumberFormat</span> <span class="n">currencyFormat</span> <span class="o">=</span> <span class="n">NumberFormat</span><span class="o">.</span><span class="na">getCurrencyInstance</span><span class="o">();</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// This specifies the actual currency that the value is in, and provides the currency symbol.</span>
</span><span class='line'>  <span class="n">Currency</span> <span class="n">currency</span> <span class="o">=</span> <span class="n">Currency</span><span class="o">.</span><span class="na">getInstance</span><span class="o">(</span><span class="n">isoCurrencyCode</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// Our fix is to use the US locale as default for the symbol, unless the currency is USD</span>
</span><span class='line'>  <span class="c1">// and the locale is NOT the US, in which case we know it should be US$.</span>
</span><span class='line'>  <span class="n">String</span> <span class="n">symbol</span><span class="o">;</span>
</span><span class='line'>  <span class="k">if</span> <span class="o">(</span><span class="n">isoCurrencyCode</span><span class="o">.</span><span class="na">equalsIgnoreCase</span><span class="o">(</span><span class="s">&quot;usd&quot;</span><span class="o">)</span> <span class="o">&amp;&amp;</span> <span class="o">!</span><span class="n">Locale</span><span class="o">.</span><span class="na">getDefault</span><span class="o">().</span><span class="na">equals</span><span class="o">(</span><span class="n">Locale</span><span class="o">.</span><span class="na">US</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">symbol</span> <span class="o">=</span> <span class="s">&quot;US$&quot;</span><span class="o">;</span>
</span><span class='line'>  <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>      <span class="n">symbol</span> <span class="o">=</span> <span class="n">currency</span><span class="o">.</span><span class="na">getSymbol</span><span class="o">(</span><span class="n">Locale</span><span class="o">.</span><span class="na">US</span><span class="o">);</span> <span class="c1">// US locale has the best symbol formatting table.</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'>  
</span><span class='line'>  <span class="c1">// We then tell our formatter to use this symbol.</span>
</span><span class='line'>  <span class="n">DecimalFormatSymbols</span> <span class="n">decimalFormatSymbols</span> <span class="o">=</span> <span class="o">((</span><span class="n">java</span><span class="o">.</span><span class="na">text</span><span class="o">.</span><span class="na">DecimalFormat</span><span class="o">)</span> <span class="n">currencyFormat</span><span class="o">).</span><span class="na">getDecimalFormatSymbols</span><span class="o">();</span>
</span><span class='line'>  <span class="n">decimalFormatSymbols</span><span class="o">.</span><span class="na">setCurrencySymbol</span><span class="o">(</span><span class="n">symbol</span><span class="o">);</span>
</span><span class='line'>  <span class="o">((</span><span class="n">java</span><span class="o">.</span><span class="na">text</span><span class="o">.</span><span class="na">DecimalFormat</span><span class="o">)</span> <span class="n">currencyFormat</span><span class="o">).</span><span class="na">setDecimalFormatSymbols</span><span class="o">(</span><span class="n">decimalFormatSymbols</span><span class="o">);</span>
</span><span class='line'>  
</span><span class='line'>  <span class="k">return</span> <span class="n">currencyFormat</span><span class="o">.</span><span class="na">format</span><span class="o">(</span><span class="n">amount</span><span class="o">);</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<h3>But wait, there&#8217;s more</h3>

<p>Now, that seems pretty good, right? Not quite - there&#8217;s a few scenarios you need to be aware of. Formatting numbers for France, one expects something like &#8220;15,00 $NZ&#8221; - that&#8217;s a comma instead of a period, a space after the numbers, followed by the symbol and then the country code. That&#8217;s how the French locale (fr_FR) localises currency values. Unfortunately, since we&#8217;re using the US locale (en_US) to format the symbol, we get &#8220;15,00 NZ$&#8221;. This is still completely readable, however it&#8217;s not <strong>quite</strong> right. It&#8217;s probably good enough, but still unfortunate.</p>

<p>Additionally, I was also getting differences in my JPY tests. First, my phone (running Android 4.1) was getting ￥15 - that was what I expected, the yen does not have more than one unit. However the emulator was getting ￥15.00 - two decimal places, where there should be 0! So, I fired up a few more emulators and did some more testing.</p>

<p>It turns out that for versions of Android 4.0.3 and down, the currency format (the <code>NumberFormat.getCurrencyInstance(locale);</code> formatter) does not work correctly for locales that have only single units in their currency. If you check out the <a href="https://github.com/adamsp/CurrencyFormattingDemo">sample project</a> you can see that for the Japanese Yen and the Chilean Peso, both of which have only single units, earlier versions of Android will format these with decimal places, where as 4.1 and up does not.</p>

<p>But wait, there&#8217;s still more. Different locales also return <em>different versions of the same symbol</em>. The US locale (en_US) returns a <a href="http://www.fileformat.info/info/unicode/char/ffe5/index.htm">full-width ￥</a> symbol, where as the Japan locale (ja_JP) returns a <a href="http://www.fileformat.info/info/unicode/char/a5/index.htm">regular ￥</a> symbol. Similarly, the French locale (fr_FR) will return a <a href="http://www.fileformat.info/info/unicode/char/a0/index.htm">non-breaking space</a> between the digits and the symbol, where as the French Canadian locale (fr_CA) which formats numbers the same way (&#8220;15,00 $NZ&#8221;, like above) uses a <a href="http://www.fileformat.info/info/unicode/char/0020/index.htm">regular space</a>. This makes writing tests a pain in the ass, but it shouldn&#8217;t have much impact on actually displaying these things to the user - of course, you do have to be careful if you&#8217;re doing string comparisons.</p>

<h3>Currency localisation sucks</h3>

<p>So, all up, what should&#8217;ve taken me an hour or so took over 2 days, working out why things weren&#8217;t behaving themselves. Even after all that time, I&#8217;m still not sure I&#8217;ve got it all figured out - I&#8217;ve rewritten this blog post about 5 times, and I can&#8217;t reproduce some things I had noted down from when I was doing this at work. Hopefully, reading through this saves someone else some pain and gives them an explanation as to why their tests are failing - or worse, users are reporting strange behaviour around currencies.</p>

<p>Of course, if you&#8217;re only targetting one market, this may not be a problem for you at all. But be prepared for the day you expand - this could definitely come back and bite you.</p>

<p>(As a side note, I realise that the test cases I&#8217;ve supplied are far from comprehensive - I especially lost my incentive to continue when I discovered they were behaving differently on different devices, at least until I&#8217;d discovered why that was the case.)</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Android Open Source licenses page]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/09/24/android-open-source-licenses-page/"/>
    <updated>2013-09-24T20:49:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/09/24/android-open-source-licenses-page</id>
    <content type="html"><![CDATA[<p>Ever used an open source library in your Android app? If you have, then you <a href="http://www.tldrlegal.com/browse">probably</a> should have included a page with the license details for that library. If you did, great! You probably had the same question I did recently; how should you do that?</p>

<!-- more -->


<p>My first attempt looked like this - in fact, this is currently what my &#8217;<a href="https://github.com/adamsp/wookmark">Wookmark Viewer</a>&#8217; licenses page looks like:</p>

<p><a href="http://adamsp.github.com/speakman-website/images/android-licenses-page/wookmark_licenses.png"><img src="http://adamsp.github.com/speakman-website/images/android-licenses-page/wookmark_licenses.png" width="240" height="400" title="Wookmark Licenses" ></a></p>

<p>However, while this page details the libraries used and their licenses, and provides links to those things, it isn&#8217;t good enough. It says in the <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License, Version 2.0</a>:</p>

<blockquote><p>You must give any other recipients of the Work or Derivative Works a copy of this License.</p></blockquote>


<p>So how should I do that? Do I have to include the same license multiple times for different libraries that use the same license? How do I include that in a regular old TextView?</p>

<p>I revisited these issues at work recently when I was tasked with adding the licenses page to our app. After some time looking around online, I couldn&#8217;t really find any suggestions as to how this page should behave, how it should look, or how to display licenses for multiple libraries. The only thing I found was <a href="http://stackoverflow.com/questions/11300552/license-screen-about-phone-legal-information-open-licenses-screen">this Stack Overflow question</a>, but that was enough of a lead to set me on the right path. I checked out some of the other Google apps - see the Play Music and Gmail apps licenses pages below. This is simply an HTML page displayed in a DialogFragment. This is more like it!</p>

<p><a href="http://adamsp.github.com/speakman-website/images/android-licenses-page/play_music_licenses.png"><img src="http://adamsp.github.com/speakman-website/images/android-licenses-page/play_music_licenses.png" width="240" height="400" title="Play Music Licenses" ></a>
<a href="http://adamsp.github.com/speakman-website/images/android-licenses-page/gmail_licenses.png"><img src="http://adamsp.github.com/speakman-website/images/android-licenses-page/gmail_licenses.png" width="240" height="400" title="Gmail Licenses" ></a></p>

<p>This answers the questions of how to display things nicely (including the full license text), how to handle multiple libraries with the same license, how to display any copyright notice, and how to link to any modified source code, as required in the <a href="http://opensource.org/licenses/gpl-2.0.php">GPL-2.0</a> license, for example. It should also be simple enough to set up to automatically construct this page (or a similar one) in your build scripts - including any custom text you may want to add, as I&#8217;ve done above for my original attempt on the Wookmark app.</p>

<p>I&#8217;ve created a DialogFragment that reproduces the Google apps licenses page experience - <a href="https://github.com/adamsp/AndroidLicensesPage">AndroidLicensesPage on Github</a>.</p>

<p>If you want to use this fragment in your application, you need to include <code>LicensesFragment.java</code> in your projects source, as well as including the <code>licenses_fragment.xml</code> layout file in <code>/res/layout</code> and the <code>licenses.html</code> file in <code>/res/raw</code>. You should update the namespace to suit.</p>

<p>To display licenses for your app, you need to update the <code>licenses.html</code> file to suit (including any libraries you&#8217;ve used, their licenses, copyrights, and any links to source you may have modified, if required), then you can display it as you would any other <a href="http://developer.android.com/reference/android/app/DialogFragment.html">DialogFragment</a>:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>// Create & show a licenses fragment just as you would any other DialogFragment.
</span><span class='line'>FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
</span><span class='line'>Fragment prev = getSupportFragmentManager().findFragmentByTag("licensesDialogFragment");
</span><span class='line'>if (prev != null) {
</span><span class='line'>  ft.remove(prev);
</span><span class='line'>}
</span><span class='line'>ft.addToBackStack(null);
</span><span class='line'>
</span><span class='line'>// Create and show the dialog.
</span><span class='line'>DialogFragment newFragment = LicensesFragment.newInstance();
</span><span class='line'>newFragment.show(ft, "licensesDialogFragment");</span></code></pre></td></tr></table></div></figure>


<p>There are some TODOs in the LicensesFragment file - you should modify these things to suit your environment, though things will work fine without you needing to touch anything.</p>

<p>If you want to see an example of this in action, clone the repository and you should be able to open the included AndroidLicensesPageExampleProject in Android Studio. It should run directly on any device or emulator running Android 2.1 or higher.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Adding Google Play Services to an Android Studio project]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/06/23/adding-google-play-services-to-an-android-studio-project/"/>
    <updated>2013-06-23T10:55:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/06/23/adding-google-play-services-to-an-android-studio-project</id>
    <content type="html"><![CDATA[<p>Adding a support library to Android Studio is a bit different to how it&#8217;s done in Eclipse. Where you&#8217;d add a &#8216;project&#8217; in Eclipse, in Studio you add a &#8216;Module&#8217; (which is a sub-project of your overall application - similar to Projects in a Solution, if you&#8217;ve done any .NET development). In this post I detail how to add the Google Play Services project, but you should be able to follow the instructions to add any support library.</p>

<!-- more -->


<p><strong>Edit July 10 2013:</strong> Note that this post only applies to projects <strong>not</strong> using Gradle.</p>

<p>Most of this information can be found on the <a href="https://developer.android.com/google/play-services/setup.html">Android Developer site</a>.</p>

<p>This guide assumes you already have an application project set up, and you&#8217;re looking to add this support library in to enable new features. For setting up the main project, check out the <a href="http://developer.android.com/sdk/installing/studio.html">Android Studio documentation</a>.</p>

<ol>
<li>Update Google Play Game Services via the SDK Manager - you can launch this from <em>Tools -> Android -> SDK Manager</em>. This will download all the required files to your Android SDK install directory.</li>
<li>Copy the <code>google-play-services_lib/</code> folder (<strong>the whole folder</strong>, not just the .jar) from  <code>&lt;android-sdk&gt;/extras/google/google_play_services/libproject/google-play-services_lib/</code> to your <code>lib/</code> folder in your project.</li>
<li>In Android Studio, select <em>File -> Import Module</em>, then select the <code>google-play-services_lib</code> folder (the one you just copied into your project directory, not the one from your SDK directory).</li>
<li>Make sure &#8216;Create module from existing sources&#8217; is selected, then Next, Next, until you reach the end of the wizard.</li>
<li>Now you have to add a reference to your new module from your existing application. Right click your existing game module (should be the top line in the Project explorer) and select <em>Open Module Settings</em>. Along the left side select <em>Modules</em> and you should see both your existing application module and your newly added library module listed. Make sure your app is selected, then choose the <em>Dependencies</em> tab. There should be a <strong>+</strong> sign at the bottom (on a Mac), or on the right side (on Windows). Click this then select <em>Module dependency</em> and add the <em>google-play-services_lib</em> module.</li>
<li>Ok, now you have everything set up correctly in your existing app module, but you need to finish setting up the one you just imported. Still in the settings window from the previous step, select the <em>google-play-services_lib</em> module under the <em>Modules</em> section. Again, click the <strong>+</strong> on the Dependencies tab but this time we&#8217;re going to choose &#8216;Jars or directories&#8217;. Navigate to the <code>google-play-services_lib/libs/</code> folder (again, the one in your application directory and not the SDK directory) and pick <em>google-play-services.jar</em>.</li>
<li>Finally, we have to make sure that other modules have access to the google-play-services.jar. In the <em>Dependencies</em> tab for the <em>google-play-services_lib</em> module, check the &#8216;Export&#8217; checkbox for the <em>google-play-services.jar</em> entry. This makes the JAR accessible to any other module that references this one.</li>
</ol>


<p>The important part is that you import the whole project, not just the JAR file. If you only import the JAR, you don&#8217;t get the associated resources. Check out this <a href="http://www.youtube.com/watch?v=nkJS_W-VC9I">Google Developers</a> video for more detail - it&#8217;s the first mistake they list.</p>

<p>If you use proguard, add this to your proguard-project.txt:</p>

<pre><code>-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}
</code></pre>

<p>You can confirm that it&#8217;s worked by building the project (you may need to do a <em>Build -> Rebuild Project</em>) and making sure there&#8217;s no errors. To see the imported module in the Project explorer, switch the drop down at the top of the Project explorer to &#8216;Packages&#8217; instead of &#8216;Project&#8217;.</p>

<p>If you&#8217;re adding a project other than Google Play Services, such as <a href="http://actionbarsherlock.com/">ActionBarSherlock</a>, that project may use the Android support library. If you&#8217;re using this too (as is likely) you need to ensure you only have one support library JAR referenced. You should export the JAR from the library (as in step 7 above) and then delete the one in your own module.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reflections on finishing an Android app]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2013/02/28/reflections-on-finishing-an-android-app/"/>
    <updated>2013-02-28T22:31:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2013/02/28/reflections-on-finishing-an-android-app</id>
    <content type="html"><![CDATA[<p>A few days ago I finally finished the application I&#8217;ve been working on in my spare moments over the last month or two. It&#8217;s called <a href="https://github.com/adamsp/wookmark">Wookmark Viewer</a> and it&#8217;s a simple little app that lets you browse the latest images saved on <a href="http://www.wookmark.com">Wookmark.com</a> (Wookmark is an &#8216;image bookmarking&#8217; site, so there&#8217;s all sorts of images from all over the web that get saved there). This was an interesting project for me, as I got to use a few different open source libraries (including one I ended up almost totally rewriting), switched IDE from Eclipse to IntelliJ, and had to figure out some new Android features I hadn&#8217;t used before.</p>

<p>This post-mortem picks apart what I enjoyed building, what caused me troubles, and what needs changing - the app is far from perfect.</p>

<!-- more -->


<h3>User Experience</h3>

<p>The app should be fairly easy to pick up and use for anyone who&#8217;s used an app with a sliding menu before. These include Facebook, NHL Game Center, YouTube and Falcon Pro, among others - so the sliding menu system is not an uncommon one. While I&#8217;ve tried to keep the user experience consistent, the final result is actually (in my opinion) quite bad, and completely inconsistent.</p>

<p>Swipe open the side-menu, and choose &#8216;New&#8217; (assuming you&#8217;re currently looking at &#8216;Popular&#8217; images). Now, press the Back button on the device - and exit the app. The idea of swapping the fragments in/out via the menu, instead of navigating to a new page, may be lost on the user. Certainly I&#8217;ve exited the app by accident a few times when I just wanted to go to the previous page.</p>

<p>However, even this poor behaviour isn&#8217;t consistent. If you go to the &#8216;Color Search&#8217; page and search of a colour, you can hit the Back button and return to the search page from the results. I consider this to be good behaviour on its own, but it&#8217;s still very confusing since it&#8217;s so different to every other page.</p>

<p>Finally, the &#8216;Settings&#8217; page is different again. Clicking on Settings brings forward an entirely new activity - with no access to the sliding menu, no branding (on 2.2/2.3), and no subheadings on the settings. On newer versions of Android you&#8217;re provided with a <code>PreferenceFragment</code> which you can use like a regular <code>PreferenceActivity</code>, but as a fragment. Unfortunately this has not been implemented in the support library, and I couldn&#8217;t find a quick/easy way of doing it, so (since I was keen to just get the damn thing finished) I went the easy way of just using a <code>PreferenceActivity</code> - resulting in this inconsistent behaviour.</p>

<h3>Open source libraries</h3>

<p>Wookmark Viewer utilises a total of 5 open source libraries: <a href="https://github.com/adamsp/SlidingMenu">SlidingMenu</a> for the menu system; <a href="https://github.com/JakeWharton/ActionBarSherlock">ActionBarSherlock</a> for the action bar view styling; <a href="https://github.com/adamsp/LazyList">LazyList</a> to lazy-load the images automatically in the background, off the UI thread; <a href="https://github.com/attenzione/android-ColorPickerPreference">ColorPickerPreference</a> for the colour picker; and finally <a href="https://github.com/adamsp/AntipodalWall">AntipodalWall</a> for the Pinterest-style view - more on this below.</p>

<p>Sliding Menu and ActionBar Sherlock worked well together - all I had to do was fork Sliding Menu and let the classes extend <code>SherlockFragment</code> and <code>SherlockActivity</code> instead. Easy. Open source is good for this - I was able to modify the code as necessary, on top of being able to step through the code when I wanted to know what was going on behind the scenes.</p>

<p>I made some modifications to the LazyList library as well. Originally it scaled all images it loaded; scaling is now optional for each image loaded, with the ability to set the scale factor when the <code>ImageLoader</code> class is instantiated. I also added the ability to supply a listener when you call <code>DisplayImage</code>, so that when the image is finished loading the calling class can update the UI - for example by removing a progress bar. I need to provide overloads for the <code>DisplayImage</code> method so that existing code can continue to use the class exactly as before, and then I&#8217;ll send a pull request back to the original author.</p>

<p>I chose the &#8216;AntipodalWall&#8217; library as my base Pinterest-style view to work with as it allowed a varying number of columns, worked on Android 2.2 and up, and was easy to set up - none of the other options met all those criteria. Unfortunately, the app quickly ran out of memory - there was no view recycling. This is fine for a static, finite number of resources, but the nature of the app means that there are an infinite number of images to load. I spent some time working on rewriting this to implement view recycling - it&#8217;s now an <code>AdapterView</code>, recycling views as they scroll off screen and supplying them back to the <code>getView</code> method of the <code>Adapter</code>. In addition I&#8217;ve overridden the <code>onSaveInstanceState</code> and <code>onRestoreInstanceState</code> methods so the scroll position and visible views are kept when the device is rotated or the app is paused.</p>

<p>There are a few problems with my implementation of this, however. It could be simplified a little, as I&#8217;m not sure my class and variable names will make too much sense to others, though I did work on refactoring that a little recently. It doesn&#8217;t handle views resizing (for example if content like an image loads in the background and a view needs resizing) - in fact, it requires views to come pre-measured from the <code>Adapter</code> and then scales them to fit, which only really works for my use case of knowing the size beforehand, and probably doesn&#8217;t work for views that contain more than just a single image. And it doesn&#8217;t behave as expected with respect to some methods; the <code>setNumberOfColumns</code> methods for example cannot be called at any time, it has to be called <em>before</em> you call <code>setAdapter</code>, which has the potential for confusion.</p>

<p>Once I&#8217;ve fixed these issues, I&#8217;m a little confused as to what I should be doing about sending a pull request or not. A diff between the original and my code reveals that while a lot of the original code remains, the file is mostly new content. Certainly, anyone who was using the old library would not be able to use my version without a significant refactor - they&#8217;d have to implement <code>Adapter</code>, for a start. So I don&#8217;t know if I should leave my fork as it is - a fork - or send a pull request, or create a new repository with a new name as a new project altogether. When I&#8217;m happy with it, I&#8217;ll probably send an email to the creator of the original project and get his opinion; I&#8217;m more than happy to send the PR if he wants it!</p>

<h3>What&#8217;s the point?</h3>

<p>Well, for an actual use-case for the app, as the API stands right now there isn&#8217;t much of one, really. The mobile site works well, looks a lot better, and offers much greater functionality. But it does have some limitations - it only offers a single-column view for images, for example.</p>

<p>Mostly, writing this app was simply good experience. I got some experience with some new libraries, and a new API - which is great, as reading other peoples code is an excellent way to grow as a developer. I learned a lot about the Android application life cycle (which I&#8217;d effectively managed to ignore with my other Android app), and figured out how to recycle views efficiently.</p>

<h3>Why isn&#8217;t it on the Play Store?</h3>

<p>Currently, there&#8217;s no way to filter adult/NSFW content. While these are tagged on the website, that information is unfortunately not available in the data returned from the API. I&#8217;ve been in contact with the creator of the Wookmark website recently, and asked if it&#8217;s possible to add this information - if so, I can filter all NSFW content, and obey the &#8216;No nudity&#8217; rule of the Play Store <a href="https://play.google.com/about/developer-content-policy.html">developer content policy</a>.</p>

<p>Until then, if you want to load the app onto your device manually, you can either build it from source or I can send you an APK file - just send me a message on <a href="https://twitter.com/adamsnz">Twitter</a>.</p>

<h3>Other thoughts</h3>

<p>Unfortunately, Color Search doesn&#8217;t work that well. Indexing images by colour is, I understand, fairly difficult. It works for values such as 0xFF0000 (red), or 0x000000 (black) - but not for 0xFA0000 (slightly less saturated red). A little experimentation shows the search works for colour values 0xXXYYZZ - that is, where the R/G/B values are chosen from the set of numbers 00, 11, 22, …, DD, EE, FF, rather than the full range 00-FF. I can probably hack this fairly easily to find a &#8220;closest&#8221; colour to the one that comes out of the colour picker - this is a better solution than the current case of not finding any results at all, in most cases.</p>

<p>Partway through development of this app I switched from Eclipse to IntelliJ - I wish I&#8217;d done it sooner. IntelliJ worked immediately with my already installed Android SDK, and after figuring out a few nuances I&#8217;ve found it to be a significantly easier IDE to use, and much more stable. One problem I&#8217;ve recently noticed though is that Eclipse used tab indentation, and IntelliJ uses 4 spaces, so my indentation on any class I&#8217;ve edited in IntelliJ is now a mixture of both. Oops.</p>

<p>That&#8217;s all the thoughts I have for now. It&#8217;s unfortunate I can&#8217;t keep this app up on the Play Store, as I did spend some time on it, but that&#8217;s the way of things, I guess. If I can get a little extra info out of the API then it&#8217;ll only take a few minutes to update and publish. In the meantime, I&#8217;ve sure learned a lot!</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Converting WP7 Maps to WP8]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2012/12/08/converting-wp7-maps-to-wp8/"/>
    <updated>2012-12-08T11:07:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2012/12/08/converting-wp7-maps-to-wp8</id>
    <content type="html"><![CDATA[<p>After <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207030.aspx">converting</a> a Windows Phone 7 application (<a href="http://www.whatsshaking.co.nz">What&#8217;s Shaking, NZ?</a>) to Windows Phone 8, I noticed a few deprecation warnings around the Maps SDK. Converting the code to use the WP8 Maps SDK instead was fairly straightforward, but there were a few gotchas which I&#8217;ve covered in this post.</p>

<!--more-->


<p><em>Note: This post assumes you&#8217;ve already converted your Windows Phone 7 app to Windows Phone 8 and are wondering how to get rid of the deprecation messages.</em></p>

<p><em>It covers converting your code to use the new Pushpins (assuming you were using the default ones previously - though a glance over the Windows Phone 7 custom Pushpin image docs indicates to me that it should be fairly straightforward to port those over as well, after a read through this), as well as the changes required in XAML.</em></p>

<p><em>This post does not delve into displaying routes or providing directions, etc.</em></p>

<p><img class="bottom" src="http://adamsp.github.com/speakman-website/images/wp7-maps-to-wp8-maps/maps_deprecated.PNG" title="Deprecation Warnings" ></p>

<h3>Deleting old references</h3>

<p>First, delete both the old <a href="http://phone.codeplex.com/">Windows Phone Toolkit</a> if you were using it (I was using it for the <code>ToggleSwitch</code> control), and the <code>Microsoft.Controls.Phone.Maps</code> library from your project references. If some of your other code breaks (ie, the ToggleSwitch), don&#8217;t worry, we&#8217;re going to fix that later.</p>

<p>There will of course be references to these namespaces throughout your code. Feel free to delete these now, or as we go.</p>

<p>While you&#8217;re changing things in the Solution Explorer, you may as well update the WMAppManifest file - you need to include the new <code>IP_CAP_MAP</code> capability.</p>

<p><img class="bottom" src="http://adamsp.github.com/speakman-website/images/wp7-maps-to-wp8-maps/maps_app_manifest.PNG" title="WMAppManifest" ></p>

<h3>Changes to XAML</h3>

<p>Next, edit your XAML to reference the new xmlns declaration:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"</span></code></pre></td></tr></table></div></figure>


<p>Now your <code>&lt;maps /&gt;</code> tag will probably show up with some blue squiggly underlines, previously I had this on one of my Map pages:</p>

<figure class='code'><figcaption><span>Old XAML</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;maps:Map</span> <span class="na">Grid.Row=</span><span class="s">&quot;1&quot;</span> <span class="na">Name=</span><span class="s">&quot;QuakeMap&quot;</span>
</span><span class='line'>    <span class="na">CredentialsProvider=</span><span class="s">&quot;your_maps_api_key_here&quot;</span>
</span><span class='line'>    <span class="na">ZoomLevel=</span><span class="s">&quot;5.3&quot;</span>
</span><span class='line'>    <span class="na">ZoomBarVisibility=</span><span class="s">&quot;Collapsed&quot;</span>
</span><span class='line'>    <span class="na">CopyrightVisibility=</span><span class="s">&quot;Collapsed&quot;</span>
</span><span class='line'>    <span class="na">LogoVisibility=</span><span class="s">&quot;Collapsed&quot;</span>
</span><span class='line'>    <span class="na">ScaleVisibility=</span><span class="s">&quot;Visible&quot;</span><span class="nt">&gt;</span>
</span><span class='line'>    <span class="nt">&lt;maps:Map.Center&gt;</span>
</span><span class='line'>        <span class="nt">&lt;my:GeoCoordinate</span> <span class="na">Altitude=</span><span class="s">&quot;NaN&quot;</span>
</span><span class='line'>            <span class="na">Course=</span><span class="s">&quot;NaN&quot;</span>
</span><span class='line'>            <span class="na">HorizontalAccuracy=</span><span class="s">&quot;NaN&quot;</span>
</span><span class='line'>            <span class="na">Latitude=</span><span class="s">&quot;-41&quot;</span>
</span><span class='line'>            <span class="na">Longitude=</span><span class="s">&quot;173&quot;</span>
</span><span class='line'>            <span class="na">Speed=</span><span class="s">&quot;NaN&quot;</span>
</span><span class='line'>            <span class="na">VerticalAccuracy=</span><span class="s">&quot;NaN&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>    <span class="nt">&lt;/maps:Map.Center&gt;</span>
</span><span class='line'><span class="nt">&lt;/maps:Map&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>However, my new XAML looks like this:</p>

<figure class='code'><figcaption><span>New XAML</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;maps:Map</span> <span class="na">Grid.Row=</span><span class="s">&quot;1&quot;</span> <span class="na">Name=</span><span class="s">&quot;QuakeMap&quot;</span>
</span><span class='line'>          <span class="na">ZoomLevel=</span><span class="s">&quot;5.3&quot;</span>
</span><span class='line'>          <span class="na">Center=</span><span class="s">&quot;-41, 173&quot;</span>
</span><span class='line'>          <span class="na">Loaded=</span><span class="s">&quot;QuakeMap_Loaded&quot;</span><span class="nt">&gt;</span>
</span><span class='line'><span class="nt">&lt;/maps:Map&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Much simpler, and all the previous properties I had marked as <code>Collapsed</code> are now collapsed by default (and no longer accessible).</p>

<h3>Pushpins</h3>

<p>Unfortunately the other part of the Maps that we&#8217;re talking about today (the Pushpins) has become <em>more</em> complicated, not less. Where previously you would simply create a <code>Pushpin</code> object, assign it a location and some content (and perhaps an event listener), and then add it via a <code>Map.Children.Add(pin)</code> call, now it&#8217;s not that simple.</p>

<p>To add the Pushpins, we now need to download and reference the <em>new</em> WPToolkit via NuGet. Go on, I&#8217;ll wait (the new one I used was published Oct 30 2012, was top result after searching for WPtoolkit). We need this for the Pushpins, as they are no longer included in the built-in Maps library (which is now located in the <code>Microsoft.Phone.Maps</code> assembly, as seen above). This should also fix any other issues you had where things from the previous Toolkit were no longer available (once you update your <code>using</code> statements).</p>

<p>Once that&#8217;s done, you can start fixing your existing Pushpin code. First, add a reference to the package you just downloaded:</p>

<figure class='code'><figcaption><span>New XAML</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'>using Microsoft.Phone.Maps.Toolkit;
</span></code></pre></td></tr></table></div></figure>


<p>The next thing you&#8217;ll notice is that the <code>Location</code> property of the Pushpin no longer exists. It&#8217;s now called <code>GeoCoordinate</code>, that&#8217;s all. That should be all you need to change there:</p>

<figure class='code'><figcaption><span>Pushpin code</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="n">Pushpin</span> <span class="n">pin</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Pushpin</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">GeoCoordinate</span> <span class="p">=</span> <span class="n">quake</span><span class="p">.</span><span class="n">Location</span><span class="p">,</span>
</span><span class='line'>    <span class="n">Content</span> <span class="p">=</span> <span class="n">quake</span><span class="p">.</span><span class="n">FormattedMagnitude</span>
</span><span class='line'><span class="p">};</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now to add the pin, we need to:</p>

<ol>
<li>Create a <code>MapOverlay</code> object and add the pin to the overlay</li>
<li>Create a <code>MapLayer</code> object and add the overlay to the layer</li>
<li>Add the <code>MapLayer</code> to the <code>Layers</code> property of the map</li>
</ol>


<p>So let&#8217;s do that:</p>

<figure class='code'><figcaption><span>Pushpin code</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="n">MapOverlay</span> <span class="n">overlay</span> <span class="p">=</span> <span class="k">new</span> <span class="n">MapOverlay</span><span class="p">();</span>
</span><span class='line'><span class="n">overlay</span><span class="p">.</span><span class="n">Content</span> <span class="p">=</span> <span class="n">pin</span><span class="p">;</span>
</span><span class='line'><span class="n">overlay</span><span class="p">.</span><span class="n">GeoCoordinate</span> <span class="p">=</span> <span class="n">quake</span><span class="p">.</span><span class="n">Location</span><span class="p">;</span>
</span><span class='line'><span class="n">overlay</span><span class="p">.</span><span class="n">PositionOrigin</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Point</span><span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="m">1</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="n">MapLayer</span> <span class="n">layer</span> <span class="p">=</span> <span class="k">new</span> <span class="n">MapLayer</span><span class="p">();</span>
</span><span class='line'><span class="n">layer</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">overlay</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="n">QuakeMap</span><span class="p">.</span><span class="n">Layers</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">layer</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>A few things to note here:</p>

<ul>
<li>Setting the <code>MapOverlay.PositionOrigin</code> is the point in your overlays content you would like centered on the <code>GeoCoordinate</code>. The overlay has (0,0) as top left, and (1,1) as bottom right of your content. Since we&#8217;re using the old Pushpin image, we want (0,1) for bottom left. If (for example) you had an arrow pointing from left-to-right and you wanted the tip of the arrow to be pointing at the location, you would specify <code>overlay.PositionOrigin = new Point(1, 0.5);</code> for the center of the right-hand side.</li>
<li>A Map can have multiple <code>MapLayer</code>s</li>
<li>A <code>MapLayer</code> can have multiple <code>MapOverlay</code>s</li>
<li>We have to specify the <code>GeoCoordinate</code> property twice - once for the <code>Pushpin</code> itself, and once for the <code>MapOverlay</code> it&#8217;s going into.</li>
</ul>


<p>If you&#8217;re adding multiple pins simultaneously, you may want to add them in separate layers or on the same layer. I&#8217;ve opted for inserting all pins on the same layer, as I&#8217;ve found this exhibits the same behaviour I was experiencing previously - pins added later appear on top - so I&#8217;ve found no reason to experiment.</p>

<p>For further reading, check out the <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207045(v=vs.105).aspx">Windows Phone Dev Center</a>.</p>

<h3>Maps API Key</h3>

<p>You may have noticed earlier that you no longer specify the <code>CredentialsProvider</code> in the XAML. Instead we have an event handler for the <code>Loaded</code> event on the map. As <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207033(v=vs.105).aspx#BKMK_appidandtoken">detailed on MSDN</a> we now specify an ApplicationID and AuthenticationToken in code. This looks to be very simple, though I haven&#8217;t tried it yet (as you get the ApplicationID and AuthenticationToken during the app submission process).</p>

<figure class='code'><figcaption><span>Map.Loaded Event Handler</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="k">private</span> <span class="k">void</span> <span class="nf">QuakeMap_Loaded</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">RoutedEventArgs</span> <span class="n">e</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">Microsoft</span><span class="p">.</span><span class="n">Phone</span><span class="p">.</span><span class="n">Maps</span><span class="p">.</span><span class="n">MapsSettings</span><span class="p">.</span><span class="n">ApplicationContext</span><span class="p">.</span><span class="n">ApplicationId</span> <span class="p">=</span> <span class="s">&quot;ApplicationID&quot;</span><span class="p">;</span>
</span><span class='line'>    <span class="n">Microsoft</span><span class="p">.</span><span class="n">Phone</span><span class="p">.</span><span class="n">Maps</span><span class="p">.</span><span class="n">MapsSettings</span><span class="p">.</span><span class="n">ApplicationContext</span><span class="p">.</span><span class="n">AuthenticationToken</span> <span class="p">=</span> <span class="s">&quot;AuthenticationToken&quot;</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Localizing a Windows Phone (7) application]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2012/11/20/localizing-a-windows-phone-application/"/>
    <updated>2012-11-20T08:49:00-08:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2012/11/20/localizing-a-windows-phone-application</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been trying to clean up the What&#8217;s Shaking, NZ? for Windows Phone 7 <a href="https://github.com/adamsp/wsnz-windowsphone">codebase</a> recently, as there was quite a bit of duplicated code and plenty of room for problems (read: shitty code). I&#8217;ll be migrating it to Windows Phone 8 soon, and want it as clean as possible before I start.</p>

<!-- more -->


<p>One part of the clean up was localization. Localization of your resources is important, as it allows you to easily distribute your application in multiple languages without having to modify your code. Too few developers do this, and having an application display its content in the language of the device is a great way to make your users feel appreciated. I&#8217;ve done localization in Java previously, but never in .NET. I did some Googling and found a few guides, it was pretty simple:</p>

<ul>
<li>Add an <code>AppResources.resx</code> file (for your default language, as specified in Assembly Info for the project)</li>
<li>Add some strings with keys</li>
<li>Reference the keys in code wherever the strings are needed</li>
<li>Additional languages are just <code>AppResources.xx-YY.resx</code>, where <code>xx</code> is the region and <code>YY</code> is the language. For example, <code>AppResources.de-DE.resx</code>. You can see the full list <a href="http://msdn.microsoft.com/en-us/library/hh202918(v=vs.92).aspx">here</a>.</li>
<li>Finally edit the <code>*.csproj</code> file to include your newly supported languages.</li>
</ul>


<p>Pretty simple. However, the <a href="http://msdn.microsoft.com/en-us/library/ff637520(v=vs.92).aspx">guide</a> I was following didn&#8217;t detail how to handle the case where you had multiple projects. Oh dear. I couldn&#8217;t find anything online about supporting multiple projects - other than just having a new <code>AppResources.resx</code> file per project, which I didn&#8217;t want.</p>

<p>As it turns out, it&#8217;s still very simple to do. Instead of adding the <code>AppResources.resx</code> file to the current project, just add a new project as a Windows Phone class library and then add the <code>AppResources.resx</code> file to that. Now, you can reference it from anywhere, provided you include a reference and a <code>using</code> statement from the other project back into the resources project:</p>

<figure class='code'><figcaption><span>MainPage.xaml.cs </span><a href='https://github.com/adamsp/wsnz-windowsphone/blob/dev/WhatsShakingNZ/MainPage.xaml.cs#L43'>Source</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="k">using</span> <span class="nn">WhatsShakingNZ.Localization</span><span class="p">;</span>
</span><span class='line'><span class="p">...</span>
</span><span class='line'><span class="k">private</span> <span class="k">void</span> <span class="nf">InitializeApplicationBar</span><span class="p">()</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="n">ApplicationBarIconButton</span> <span class="n">refreshButton</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ApplicationBarIconButton</span><span class="p">();</span>
</span><span class='line'>    <span class="n">refreshButton</span><span class="p">.</span><span class="n">Text</span> <span class="p">=</span> <span class="n">AppResources</span><span class="p">.</span><span class="n">AppBarRefreshButtonText</span><span class="p">;</span>
</span><span class='line'>    <span class="p">...</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>To access the resources from XAML, you need to add the following class to your resources library:</p>

<figure class='code'><figcaption><span>LocalizedStrings.cs </span><a href='https://github.com/adamsp/wsnz-windowsphone/blob/dev/Localization/LocalizedStrings.cs'>Source</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='c#'><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">LocalizedStrings</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">public</span> <span class="nf">LocalizedStrings</span><span class="p">()</span>
</span><span class='line'>    <span class="p">{</span>
</span><span class='line'>    <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">private</span> <span class="k">static</span> <span class="n">AppResources</span> <span class="n">localizedResources</span> <span class="p">=</span> <span class="k">new</span> <span class="n">AppResources</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="n">AppResources</span> <span class="n">LocalizedResources</span> <span class="p">{</span> <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">localizedResources</span><span class="p">;</span> <span class="p">}</span> <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>You will also need to add the following to the <code>App.xaml</code> file (the guide I linked to above doesn&#8217;t detail all of this):</p>

<figure class='code'><figcaption><span>App.xaml</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;Application</span>
</span><span class='line'><span class="err">...</span>
</span><span class='line'><span class="na">xmlns:local=</span><span class="s">&quot;clr-namespace:WhatsShakingNZ.Localization;assembly=WhatsShakingNZ.Localization&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>
</span><span class='line'>    <span class="nt">&lt;Application.Resources&gt;</span>
</span><span class='line'>        <span class="nt">&lt;local:LocalizedStrings</span> <span class="na">x:Key=</span><span class="s">&quot;LocalizedStrings&quot;</span> <span class="nt">/&gt;</span>
</span><span class='line'>        ...
</span><span class='line'>    <span class="nt">&lt;Application.Resources&gt;</span>
</span><span class='line'>...
</span><span class='line'><span class="nt">&lt;/Application&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>And then to reference the resources in the XAML for each page, change anything that was using hardcoded text to use a binding as follows:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='xml'><span class='line'><span class="nt">&lt;TextBlock</span> <span class="na">x:Name=</span><span class="s">&quot;PageTitle&quot;</span>
</span><span class='line'>    <span class="na">Text=</span><span class="s">&quot;{Binding Path=LocalizedResources.PageTitleLatestQuakes, Source={StaticResource LocalizedStrings}}&quot;</span>
</span><span class='line'>    <span class="na">Margin=</span><span class="s">&quot;9,-7,0,0&quot;</span>
</span><span class='line'>    <span class="na">Style=</span><span class="s">&quot;{StaticResource PhoneTextTitle1Style}&quot;</span><span class="nt">/&gt;</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can see all of these changes in <a href="https://github.com/adamsp/wsnz-windowsphone/commit/49c511f9be2181955b3a5e7b06bf88068ec32ec4">this commit</a>.</p>

<p>There are a few important gotchas with this:</p>

<ul>
<li>The DLL filename <strong>cannot end in &#8220;Resources&#8221;</strong>. I had some trouble with this, but I eventually found <a href="http://isolatedstorage.wordpress.com/2010/10/25/reserved-xap-file-names-resource-dll/">this blog post</a> detailing the fact there are some reserved file names in XAP files. Specifically, you can&#8217;t have DLLs ending in &#8216;Resources&#8217;. If you have named your project as &#8220;Resources&#8221;, everything will compile fine but your app will crash when it runs. It&#8217;s easy enough to fix - I renamed my project (and the properties that named the DLL) from <code>WhatsShakingNZ.Resources</code> to <code>WhatsShakingNZ.Localization</code>. After doing this, everything worked perfectly.</li>
<li>You must specify the <code>AppResources.resx</code> Access Modifier as <code>public</code> or you won&#8217;t be able to access the resource properties:
<img class="bottom" src="http://adamsp.github.com/speakman-website/images/wp7-localization/access_modifier.PNG"></li>
<li>The default language as specified in the Assembly Information under the project Properties window is the one that your default <code>AppResources.resx</code> file is considered to be. If the device your application is running on is running any language other than your default, it will search for the resource string in the corresponding language resource file. If that resource file does not exist (or, if the specific key it is looking for does not exist in that region-specific file), then it will fall back to your default. This means you can have some strings localised and some not, even within the same page.</li>
<li>To support additional languages, you have to add the <code>AppResources.xx-YY.resx</code> file, and also declare in the <code>.csproj</code> file for the <strong>main project</strong> that it supports the language (not the project containing your resource files). You have to edit this file manually in a text editor, as detailed in step 4 of <a href="http://msdn.microsoft.com/en-us/library/ff637520(v=vs.92).aspx">the guide linked above</a>. You can check out <a href="http://blogs.msdn.com/b/webdev/archive/2008/06/10/localizing-a-silverlight-application.aspx">this MSDN blog</a>, <a href="http://msdn.microsoft.com/en-us/library/dd941932(VS.95).aspx">this guide</a> or <a href="http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/7e3267e4-ab1f-4fd0-90f4-d9292831bb2b/">this forum post</a> for a bit more information on how and why.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Google Maps zoom levels on Android]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2012/10/28/google-maps-zoom-levels-on-android/"/>
    <updated>2012-10-28T12:40:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2012/10/28/google-maps-zoom-levels-on-android</id>
    <content type="html"><![CDATA[<p>I had an interesting problem today where I needed to scale the default zoom for the map view for my <a href="https://play.google.com/store/apps/details?id=speakman.whatsshakingnz">Android app</a>, depending on the screen size. I&#8217;d previously hardcoded it to a zoom level of 6. This worked nicely on my testing device (a Nexus One) and looked OK (but not great) on a Galaxy S3 - but I saw it last night on a Nexus 7 and it looked ridiculous. My desire was to have the map view show the whole of New Zealand, filling up as much of the screen as possible. On the Nexus 7, the country was tiny.</p>

<!-- more -->


<p>I&#8217;d previously considered the fact that I would likely need to adjust the zoom level on a per-device level, and had added a method stub with the intent of adding some logic in there. Up til now I hadn&#8217;t bothered with it, as, well, &#8220;It works on my device!&#8221; However looking at it on this Nexus 7, I figured it was time to do something about it.</p>

<p>A bit of Googling around showed that the problem of zooming relative to screen size was common - but the <a href="http://stackoverflow.com/questions/2666922/auto-size-zoom-on-google-maps-in-java-depending-android-screen-resolution">common problem/solution</a> was to ensure the map zoomed to span a set of markers in an <code>ItemizedOverlay</code>. I specifically <strong>did not</strong> want to do this - I want to show the whole country, not just the areas where the earthquakes are!</p>

<p>The <code>MapController.zoomToSpan(int latSpanE6, int lonSpanE6)</code> method looked like it would do what I wanted, but honestly, it&#8217;s fucked. It gave me either zoom level 5 or zoom level 7, and I could never get it to give me zoom 6 (which is what I wanted, for the screen size on the emulator I was trying it on). Incrementally decreasing the size of the area I was requesting it to zoom to was no help. Admittedly the <a href="https://developers.google.com/maps/documentation/android/reference/com/google/android/maps/MapController#zoomToSpan(int, int)">documentation</a> gives no guarantees, and says that after the zoom &#8220;at least one of the new latitude or the new longitude will be within a factor of 2 from the corresponding parameter.&#8221; This wasn&#8217;t good enough.</p>

<p>I ended up doing it the hard way and experimenting with different screen resolution emulators until I found the right zooms. I figured 5, 6 and 7 would probably do it, depending on screen size. My code now looks like this:</p>

<figure class='code'><figcaption><span>getDefaultZoomForDevice() </span><a href='https://github.com/adamsp/wsnz-android/blob/master/Whats%20Shaking%20NZ/src/speakman/whatsshakingnz/fragments/MapFragment.java#L117'>Source</a></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='Java'><span class='line'><span class="kd">private</span> <span class="kt">int</span> <span class="nf">getDefaultZoomForDevice</span><span class="o">()</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">WindowManager</span> <span class="n">wm</span> <span class="o">=</span> <span class="o">(</span><span class="n">WindowManager</span><span class="o">)</span> <span class="n">getActivity</span><span class="o">().</span><span class="na">getApplicationContext</span><span class="o">().</span><span class="na">getSystemService</span><span class="o">(</span><span class="n">Context</span><span class="o">.</span><span class="na">WINDOW_SERVICE</span><span class="o">);</span>
</span><span class='line'>  <span class="n">Display</span> <span class="n">display</span> <span class="o">=</span> <span class="n">wm</span><span class="o">.</span><span class="na">getDefaultDisplay</span><span class="o">();</span>
</span><span class='line'>  <span class="kt">int</span> <span class="n">width</span> <span class="o">=</span> <span class="n">display</span><span class="o">.</span><span class="na">getWidth</span><span class="o">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">if</span><span class="o">(</span><span class="n">width</span> <span class="o">&lt;</span> <span class="mi">480</span><span class="o">)</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">5</span><span class="o">;</span>
</span><span class='line'>  <span class="k">else</span> <span class="nf">if</span> <span class="o">(</span><span class="n">width</span> <span class="o">&lt;</span> <span class="mi">720</span><span class="o">)</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">6</span><span class="o">;</span>
</span><span class='line'>  <span class="k">else</span>
</span><span class='line'>      <span class="k">return</span> <span class="mi">7</span><span class="o">;</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>I went with these resolutions because they represent some of the most common sizes among popular phones. Below 480px wide we have 320x480 devices such as the LG P500 (Optimus One) or the Galaxy Ace. Below 720px wide we have the common 480x800 devices such as my Nexus One, or the Galaxy S and Galaxy S II. And finally we have even larger devices with higher resolutions, such as the 720x1280 Galaxy S III (this is the most common device for all downloads of What&#8217;s Shaking, NZ? for Android) and HTC One X, and the 800x1280 Nexus 7 tablet.</p>

<p>There are some obvious problems with this solution. It&#8217;s not generic at all, and works only for New Zealand. The <code>Display.getWidth()</code> call is actually deprecated since API Level 13, however I want to support older devices as well - currently nearly 45% of all my downloads for this app are Android 2.3 and below. Also, note that this solution doesn&#8217;t work very well for people with strange resolution phones - anything that doesn&#8217;t fall into the broad categories I&#8217;ve defined above is likely to meet with a strange/unfortunate default zoom. However if your screen size is that weird, there&#8217;s probably not a whole lot more I can do about it - the Android Maps API doesn&#8217;t allow anything more granular than these discrete levels, and these zoom levels fit New Zealand to the screen the best for the given sizes. Lastly, it won&#8217;t scale properly when even larger devices are released.</p>

<p>However, despite these problems, I still found it to be the simplest, and most effective way of handling zoom at a per-device level. I would love to see a more granular zoom level (in Windows Phone you supply a double for zoom level), as it would presumably fix the problems with the <code>zoomToSpan</code> failures (this is a far more generic solution and would almost certainly be preferable). However, even if that does come about it won&#8217;t make much difference. With all these older devices still in use that won&#8217;t support it, it&#8217;ll take a long time to make enough of a dent in the user base that it&#8217;s worth thinking about again.</p>

<p><a href="http://adamsp.github.com/speakman-website/images/android-maps/android_maps_large.PNG"><img class="bottom" src="http://adamsp.github.com/speakman-website/images/android-maps/android_maps_large.PNG" width="160" height="240" title="Large screen, 720x1280px, zoom level 7" ></a>
<a href="http://adamsp.github.com/speakman-website/images/android-maps/android_maps_medium.PNG"><img class="bottom" src="http://adamsp.github.com/speakman-website/images/android-maps/android_maps_medium.PNG" width="160" height="240" title="Medium screen, 480x800px, zoom level 6" ></a>
<a href="http://adamsp.github.com/speakman-website/images/android-maps/android_maps_small.PNG"><img class="bottom" src="http://adamsp.github.com/speakman-website/images/android-maps/android_maps_small.PNG" width="160" height="240" title="Small screen, 320x480px, zoom level 5" ></a></p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Setting up Octopress on Github Pages]]></title>
    <link href="http://adamsp.github.com/speakman-website/blog/2012/09/11/setting-up-octopress-on-github-pages/"/>
    <updated>2012-09-11T20:22:00-07:00</updated>
    <id>http://adamsp.github.com/speakman-website/blog/2012/09/11/setting-up-octopress-on-github-pages</id>
    <content type="html"><![CDATA[<p>There&#8217;s a lot of good information out there already on setting up Octopress on Github. The <a href="http://octopress.org/docs/deploying/github/">Octopress documentation</a> covers the subject in depth, as do assorted blog posts. However, perhaps it&#8217;s because I was drinking while doing it, or perhaps it was because I missed something while reading the guides, or my poor mental model of how things were supposed to work, or even that it was late at night, but I had a lot of trouble setting up <a href="http://www.whatsshaking.co.nz">What&#8217;s Shaking, NZ?</a> on Github Pages.</p>

<!-- more -->


<p>A few things to note:</p>

<ol>
<li>A lot of what I&#8217;ve done with setting up this website is completely new to me. I&#8217;ve never edited CSS before, for example &#8211; or ever owned a domain name. So if something is obvious to most, apologies if an explanation may seem unnecessary. I especially apologise if an explanation is wrong! Please let me know.</li>
<li>If you want a guide to setting things up, this isn&#8217;t it. A lot of things I did here are <em>wrong</em>. This post is simply to point out some of the things I struggled with, in the hope that pointing out the right way to do things may be of help to someone else some day.</li>
</ol>


<p>Now, on to the post!</p>

<h3>Intent</h3>

<p>My intent was to host the website as a project page on a Github repo, using a custom domain. This repository would consist of a <code>master</code> branch with the source on it, and a <code>gh-pages</code> branch with the website on it. From there, I could have the www.whatsshaking.co.nz domain point at the right place and everything would all work splendidly. I spent a fair bit of time playing around with colours and layout and resizing locally (resizing the header was only possible thanks to <a href="http://blog.bigdinosaur.org/changing-octopresss-header/">Lee at Big Dinosaur</a>). When it was at a this-sucks-less-than-everything-else-I&#8217;ve-tried stage, I decided it was time to put it up online.</p>

<p>I spent a bit of time poring over the <a href="http://octopress.org/docs/deploying/github/">Octopress documentation</a> as well as <a href="http://robdodson.me/blog/2012/04/30/custom-domain-with-octopress-and-github-pages/">this post by Rob Dodson</a>. I figured I was armed with enough knowledge to get this to work first time.</p>

<p>My test setup on my local machine looked something like this:</p>

<ul>
<li>Octopress cloned into <code>~/Sites/wsnz</code> using the command on the site</li>
<li><a href="http://pow.cx/">POW</a> running so I could access http://wsnz.dev locally and see the changes to my site as I made them, after running <code>rake watch</code></li>
</ul>


<p>What I wanted, was this:
- Octopress WSNZ site in <code>~/Code/wsnz-website</code> with source on <code>master</code> branch and easy deployment to <code>gh-pages</code> branch
- POW running the same as above, for easy local development</p>

<p>So, with beer in hand and the internet at the ready I embarked on this adventure.</p>

<h3>Following instructions</h3>

<p>First of all, I wanted my code in a different place locally. So I created the repository on the Github site (<a href="https://github.com/adamsp/wsnz-website">adamsp/wsnz-website</a>) and cloned to <code>~/Code/wsnz-website</code> using the &#8216;Clone in Mac&#8217; button and the Github application. Then through the OS X Finder I copied the contents of <code>~/Sites/wsnz</code> into <code>~/Code/wsnz-website</code>. Importantly, this means I no longer have the original .git folder, so that explains why the <a href="https://github.com/adamsp/wsnz-website">wsnz-website repository</a> has no commit history (<s>where as the <a href="https://github.com/adamsp/adamsp.github.com">repo for this site</a> is a &#8216;proper&#8217; fork and does have the commit history</s> <strong>Edit 18 Sep 2012:</strong> <a href="https://github.com/adamsp/speakman-website">This site</a> ended up copy/pasted from that linked repo).</p>

<p>Now my code was in the right place, I went ahead and did some other modifications. I changed my <code>_config.yml</code> file so that the URL property pointed at the domain, <code>url: www.whatsshaking.co.nz</code>, I added a <a href="https://github.com/dstufft/octopress/blob/9f40242b1e7eb0098f0ef3c508c7bed7e647b982/.gitignore">.gitignore</a>, added a Google Analytics ID, etc. I also did <code>echo 'www.whatsshaking.co.nz' &gt;&gt; source/CNAME</code>, as instructed in the guides, so I had a CNAME file with my site URL in it.</p>

<p>I now ran <code>rake setup_github_pages</code> (with the git endpoint as <code>git@github.com:adamsp/wsnz-website</code>) &#8211; this changed my <code>_config.yml</code> and <code>Rakefile</code>. This is wrong!</p>

<p>When I ran <code>rake deploy</code> I ended up with a broken website. I figured I should be able to see it at http://adamsp.github.com/wsnz-website &#8211; but that didn&#8217;t work. This was confusing, as everything appeared to be right on the <code>gh-pages</code> branch.</p>

<h3>Fixing problems</h3>

<p>I was looking through HTML in the <code>gh-pages</code> branch when I realised that the files weren&#8217;t at root. Checking back in my source again, it looked like everything in the config files was prefixed with <code>wsnz-website/</code>!</p>

<p>The <code>setup_github_pages</code> command changed all the URLs to be prefixed with <code>wsnz-website/</code>. I had to go through and edit these out. So you should still have the following settings in these files:</p>

<figure class='code'><figcaption><span>_config.yml</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nt">subscribe_rss</span><span class="o">:</span> <span class="o">/</span><span class="nt">atom</span><span class="nc">.xml</span>
</span><span class='line'><span class="nt">root</span><span class="o">:</span> <span class="o">/</span>
</span><span class='line'><span class="nt">destination</span><span class="o">:</span> <span class="nt">public</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>Rakefile</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='css'><span class='line'><span class="nt">public_dir</span> <span class="o">=</span> <span class="s2">&quot;public&quot;</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>config.rb</span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='ruby'><span class='line'><span class="n">http_path</span> <span class="o">=</span> <span class="s2">&quot;/&quot;</span>
</span><span class='line'><span class="n">http_images_path</span> <span class="o">=</span> <span class="s2">&quot;/images&quot;</span>
</span><span class='line'><span class="n">http_fonts_path</span> <span class="o">=</span> <span class="s2">&quot;/fonts&quot;</span>
</span><span class='line'><span class="n">css_dir</span> <span class="o">=</span> <span class="s2">&quot;public/stylesheets&quot;</span>
</span></code></pre></td></tr></table></div></figure>


<p>But oddly enough, things still weren&#8217;t working. Turns out, I had to leave the URL property in <code>_config.yml</code> as <code>url: http://adamsp.github.com/wsnz-website</code>.</p>

<p>Once I did this and redeployed, everything worked as expected. I updated my link in <code>~/.pow</code> to point to <code>~/Code/wsnz-website</code> and I could access my site for local development again. Pushing blog posts and changes is now as simple as <code>rake generate</code> then <code>rake deploy</code>. Easy.</p>

<h3>Specific issues</h3>

<p>Anyway, after all of that, these are the issues I had, and their fixes/correct settings:</p>

<ul>
<li>The settings in <code>_config.yml</code> <em>require a space after the colon</em> or else the generate command fails.</li>
<li>If you&#8217;re updating files in the sass folder and things don&#8217;t appear to be changing, you may need to delete <code>.sass_cache</code>.</li>
<li>The <code>url</code> setting in <code>_config.yml</code> is the Github pages URL &#8211; eg <code>url: http://adamsp.github.com/wsnz-website</code>. This is true even if using a custom domain. See <a href="https://github.com/adamsp/wsnz-website/commit/44e66db6a834624089e06bbd9b60779881045aba">this commit</a> for what I mean.</li>
<li>The paths in <code>_config.yml</code>, <code>config.rb</code> and <code>Rakefile</code> should <em>not</em> contain your sites repository name. eg <code>destination: public</code> and not <code>destination: wsnz-website/public</code>. The <code>rake setup_github_pages</code> command may put these settings there.</li>
<li>The <code>CNAME</code> file should exist under the source folder, and then when deployed it will exist in the root of your <code>gh-pages</code> directory. This is required.</li>
<li><a href="http://octopress.org/docs/deploying/github/#custom_domains">Setting up the DNS entries</a> is also required. With the <code>CNAME</code> file present you cannot access the site at the Github address. Note that you should just point it to <code>http://username.github.com</code> rather than <code>http://username.github.com/project-page</code>.</li>
</ul>


<p>Again, I must emphasise that most of this is fairly new to me. I&#8217;m sure most of these things are common knowledge, but not to me - and that means probably not to someone else.</p>
]]></content>
  </entry>
  
</feed>
