<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Blog</title>
	<atom:link href="http://blog.andresteingress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.andresteingress.com</link>
	<description>Android, Grails, Groovy. Mostly.</description>
	<lastBuildDate>Tue, 24 Jan 2012 07:07:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>CacheManager&#8217;s diskStorePath</title>
		<link>http://blog.andresteingress.com/2012/01/24/cachemanagers-diskstorepath/</link>
		<comments>http://blog.andresteingress.com/2012/01/24/cachemanagers-diskstorepath/#comments</comments>
		<pubDate>Tue, 24 Jan 2012 07:00:34 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1728</guid>
		<description><![CDATA[Lately I had to configure the Ehcache [0] CacheManager&#8217;s diskStorePath property. That alone wouldn&#8217;t be a problem, but I had to come up with a mechanism that allowed to set the diskStorePath based on customer-specific configuration settings. As I couldn&#8217;t &#8230; <a href="http://blog.andresteingress.com/2012/01/24/cachemanagers-diskstorepath/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Lately I had to configure the Ehcache [<a href="http://ehcache.org/">0</a>] CacheManager&#8217;s <tt>diskStorePath</tt> property. That alone wouldn&#8217;t be a problem, but I had to come up with a mechanism that allowed to set the diskStorePath based on customer-specific configuration settings. As I couldn&#8217;t find proper instructions on the web or on stackoverflow, I thought it would be worth sharing the outcome.</p>
<h3>The problem</h3>
<p>The Grails plugin collective (GPC) offers the so-called &#8220;Spring-Cache Plugin&#8221; [<a href="http://grails.org/plugin/springcache">1</a>], a great plugin by Robert Fletcher. The plugin comes with a <tt>@Cacheable</tt> annotation. Whenever a type, method or field is annotated as &#8220;cacheable&#8221; the result is put into a Ehcache instance and further calls might return a cached result (depending on the cache settings).</p>
<p>Let&#8217;s start with the default settings. The default Ehcache cache setting look like this (extracted from <tt>ehcache-failsafe.xml</tt>):</p>
<pre class="brush: xml; title: ; notranslate">
&lt;defaultCache
            maxElementsInMemory=&quot;10000&quot;
            eternal=&quot;false&quot;
            timeToIdleSeconds=&quot;120&quot;
            timeToLiveSeconds=&quot;120&quot;
            overflowToDisk=&quot;true&quot;
            maxElementsOnDisk=&quot;10000000&quot;
            diskPersistent=&quot;false&quot;
            diskExpiryThreadIntervalSeconds=&quot;120&quot;
            memoryStoreEvictionPolicy=&quot;LRU&quot;
            /&gt;
</pre>
<p>The attribute <tt>overflowToDisk</tt> is true, meaning that whenever the maximum number of in-memory objects is reached, objects are swapped to disk. However, <tt>diskPersistent</tt> is false, meaning that between subsequent server/application restarts, the in-memory cache is lost and all swapped objects will be cleaned on startup.</p>
<p>Our requirement was to activate disk persistency and configure a <tt>diskStorePath</tt>, based on a given customer configuration. The customer configuration diskStore directory path would be based on the build settings, ie. a custom Config.groovy file.</p>
<p>Specifying a custom <tt>diskStorePath</tt> would be done in a custom <tt>ehcache.xml</tt> file like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;diskStore path=&quot;here comes the customer-specific directory&quot;/&gt;
</pre>
<h3>Setting the diskStorePath</h3>
<p>The Springcache plugin works with Spring&#8217;s <tt>EhCacheManagerFactoryBean</tt> and <tt>EhCacheFactoryBean</tt>. Given the following configuration in <tt>Config.groovy</tt> &#8230;</p>
<pre class="brush: groovy; title: ; notranslate">
springcache.enabled = true

springcache {
    defaults {
        // set default cache properties that will apply to all caches that do not override them
        eternal = false
        diskPersistent = true
        maxElementsInMemory = 1000
        maxElementsOnDisk = 10000

//        24 hours
        timeToIdle = 86400
        timeToLive = 86400

        overflowToDisk = true
        memoryStoreEvictionPolicy = &quot;LRU&quot;
    }

    caches {
        myCache {
            // set any properties unique to this cache
        }
        // more caches follow ...
}
</pre>
<p>&#8230; the plugin will create one or multiple <tt>EhCacheFactoryBean</tt> instances, by iterating over <tt>springcache.defaults</tt>.</p>
<pre class="brush: groovy; title: ; notranslate">
    springcacheDefaultCache(EhCacheFactoryBean) { bean -&gt;
        bean.&quot;abstract&quot; = true
        cacheManager = ref(&quot;springcacheCacheManager&quot;)
        application.config.springcache.defaults.each {
            bean.setPropertyValue it.key, it.value
        }
    }

    application.config.springcache.caches.each {String name, ConfigObject cacheConfig -&gt;
        &quot;$name&quot;(EhCacheFactoryBean) {bean -&gt;
            bean.parent = springcacheDefaultCache
            cacheName = name
            cacheConfig.each {
                bean.setPropertyValue it.key, it.value
            }
        }
    }
</pre>
<p>The <tt>diskStorePath</tt> is actually held by Ehcache&#8217;s <tt>CacheManager</tt>. It is a singleton managing the default cache and all the other cache instances. Bad news is that <tt>EhcacheManagerFactoryBean</tt> does not provide a way to define a <tt>diskStorePath</tt> [<a href="https://jira.springsource.org/browse/SPR-5076">2</a>]. The only way to configure a custom path is to reference a custom <tt>ehcache.xml</tt> configuration:</p>
<pre class="brush: java; title: ; notranslate">
public class EhCacheManagerFactoryBean {
    // ...
    public void setConfigLocation(org.springframework.core.io.Resource configLocation)
}
</pre>
<p>As we have multiple customers and therefore potentially multiple diskStore paths and wanted to control the path through the customer-specific <tt>Config.groovy</tt>, we had to find a way to dynamically generate a temporary <tt>ehcache.xml</tt>.</p>
<p>As it turns out, with Groovy&#8217;s XML support this is a pretty straight-forward process in <tt>resources.groovy</tt>:</p>
<pre class="brush: groovy; title: ; notranslate">
springcacheCacheManager(EhCacheManagerFactoryBean) {
         // ... set other props

        def writer = new StringWriter()
        def xml = new MarkupBuilder(writer)

        xml.ehcache() {
          diskStore(path: config.app.cache.diskStorePath ?: 'java.io.tmpdir/springcache')
          defaultCache(config.springcache.defaults)
        }

        def ehCacheXmlTempFile   = File.createTempFile(&quot;ehcache-springcache&quot;, &quot;.xml&quot;)
        ehCacheXmlTempFile.setText(writer.toString())

        // set the spring bean property
        configLocation = new FileSystemResource(ehCacheXmlTempFile)
}
</pre>
<p>As you can see from the code snippet above, <tt>XmlSlurper</tt> is used to slurp a ehcache.xml configuration template, without any predefined settings. As the Springcache plugin has already been configured in <tt>Config.groovy</tt>, it &#8216;synchronizes&#8217; those settings and injects all properties into the slurped DOM. The best thing is that <tt>diskStorePath</tt> can be set accordingly to the current configuration setting in <tt>config.app.cache.diskStorePath</tt>, defaulting to the default temporary directory. Last, <tt>StreamingMarkupBuilder</tt> is used to write the resulting XML to a newly created temporary file.</p>
<h3>Conclusion</h3>
<p>This article shows how using a dynamic programming language for bean definitions is just awesome and how Groovy&#8217;s excellent XML support can be used in places XML gurus only can dream of.</p>
<p>[0] <a href="http://ehcache.org/">Ehcache &#8211; http://ehcache.org/</a><br />
[1] <a href="http://grails.org/plugin/springcache">Grails Springcache Plugin</a><br />
[2] <a href="https://jira.springsource.org/browse/SPR-5076">Spring JIRA &#8211; [EhCacheFactoryBean] diskStorePath property has no effect</a></p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.andresteingress.com/2012/01/24/cachemanagers-diskstorepath"></a><br />
<noscript><a href="http://flattr.com/thing/469975/CacheManagers-DiskStorePath" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2012/01/24/cachemanagers-diskstorepath/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>@NullSafe Reloaded</title>
		<link>http://blog.andresteingress.com/2012/01/17/nullsafe-reloaded/</link>
		<comments>http://blog.andresteingress.com/2012/01/17/nullsafe-reloaded/#comments</comments>
		<pubDate>Tue, 17 Jan 2012 18:00:47 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1701</guid>
		<description><![CDATA[In almost all projects of mine I got used to a utility class called Default. Default would provide static methods, whereas each method comes with a single parameter. The purpose of Default was nothing more than to provide default values &#8230; <a href="http://blog.andresteingress.com/2012/01/17/nullsafe-reloaded/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In almost all projects of mine I got used to a utility class called <tt>Default</tt>. <tt>Default</tt> would provide static methods, whereas each method comes with a single parameter. The purpose of <tt>Default</tt> was nothing more than to provide default values if the argument is <tt>null</tt> at runtime.</p>
<pre class="brush: java; title: ; notranslate">

public class Default {

    // ...
    public static Float floatObject(Float n) {
        return n != null ? n : 0.0f;
    }

    public static Integer integerObject(Integer i) {
        return i != null ? i : 0;
    }

    // ...
}
</pre>
<h3>Doin it the Groovy way</h3>
<p>With the upcoming popularity of Groovy AST transformations, I thought it would be time to write a small <tt>NullSafeASTTransformation</tt> with the attached <tt>@NullSafe</tt> annotation. </p>
<p>As Groovy is dynamically typed, <tt>@NullSafe</tt> is restricted to work on statically declared local variables.</p>
<pre class="brush: groovy; title: ; notranslate">

@NullSafe String name = data.name
@NullSafe Integer count = data.count
@NullSafe BigDecimal amount = data.amount

assert name == ''
assert count == 0
assert amount == 0.0
</pre>
<p>As you can see in the code sample above, <tt>@NullSafe</tt> ensures that the according variable value is at least of the variables type&#8217;s default value, after the initial expression has been executed at runtime.</p>
<p>In addition, the <tt>NullSafeASTTransformation</tt> checks all variable assignments with a custom class code visitor, to ensure that a variable assignment will result in the default value and not <tt>null</tt>.</p>
<pre class="brush: groovy; title: ; notranslate">

def doSomeStuff()  {

    @NullSafe BigDecimal bd = 12.0
    bd = compute()
    assert bd == 0.0
}

def compute() { return null }
</pre>
<p>The <tt>NullSafeASTTransformation</tt> is a local AST transformation [<a href="http://groovy.codehaus.org/Local+AST+Transformations">0</a>], injecting static method calls to a hidden <tt>NullSafeUtil</tt> class:</p>
<pre class="brush: groovy; title: ; notranslate">

@GroovyASTTransformation(phase=CompilePhase.SEMANTIC_ANALYSIS)
class NullSafeASTTransformation implements ASTTransformation {

    SourceUnit sourceUnit
    ClassNode NULL_SAFE_UTIL_CLASS = ClassHelper.make(NullSafeUtil.class)

    void visit(org.codehaus.groovy.ast.ASTNode[] nodes, org.codehaus.groovy.control.SourceUnit source) {
        this.sourceUnit = source

        if (sourceUnit.getAST().classes.size() != 1)  {
            addError('@NullSafe annotation can only be applied on local variables!', nodes[0])
            return
        }

        if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof DeclarationExpression)) {
            addError('@NullSafe annotation can only be applied on local variables!', nodes[0])
            return
        }

        DeclarationExpression declarationExpression = nodes[1]

        if (!(declarationExpression.leftExpression instanceof VariableExpression)) {
            addError('@NullSafe can only be applied on the left side of a variable declaration!', declarationExpression)
            return
        }

        injectDeclarationNullSafeCheck(declarationExpression)
        injectAssignmentNullSafeCheck(declarationExpression)
    }

    void injectDeclarationNullSafeCheck(DeclarationExpression declarationExpression)  {
        VariableExpression variableExpression = declarationExpression.leftExpression

        if (variableExpression.dynamicTyped || variableExpression.accessedVariable.type == ClassHelper.DYNAMIC_TYPE)  {
            addError('@NullSafe is not supported on dynamically typed variables!', variableExpression)
            return
        }

        def rightExpression = declarationExpression.getRightExpression()
        if (rightExpression == null)  {
            addError(&quot;@NullSafeNumber right expression is empty&quot;, declarationExpression)
            return
        }

        ClassNode variableType = variableExpression.accessedVariable.type
        declarationExpression.rightExpression = new StaticMethodCallExpression(NULL_SAFE_UTIL_CLASS, &quot;nullSafe&quot;, new ArgumentListExpression([new CastExpression(variableType, rightExpression)]))
    }

    void injectAssignmentNullSafeCheck(DeclarationExpression declarationExpression)  {
        VariableExpression variableExpression = declarationExpression.leftExpression

        if (variableExpression.dynamicTyped || variableExpression.accessedVariable.type == ClassHelper.DYNAMIC_TYPE)  {
            addError('@NullSafe is not supported on dynamically typed variables!', variableExpression)
            return
        }

        def rightExpression = declarationExpression.getRightExpression()
        if (rightExpression == null)  {
            addError(&quot;@NullSafeNumber right expression is empty&quot;, declarationExpression)
            return
        }

        NullSafeClassCodeVisitor visitor = new NullSafeClassCodeVisitor(sourceUnit, variableExpression.accessedVariable)
        visitor.visitClass(sourceUnit.getAST().classes[0])
    }

    protected void addError(String msg, ASTNode expr) {
        int line = expr.getLineNumber();
        int col = expr.getColumnNumber();
        sourceUnit.getErrorCollector().addErrorAndContinue(
                new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), sourceUnit)
        );
    }
}
</pre>
<p>The most important points besides checking if the annotation has been applied in a valid context, is the injection of the static method call to <tt>NullSafeUtil.nullSafe</tt>. As Groovy dynamically dispatches static method calls it is ensured that static method selection is based on the variables runtime type.</p>
<h3>Conclusion</h3>
<p>The <tt>@NullSafe</tt> annotation currently works on statically typed local variables. At time of writing, the types cover all <tt>Number</tt> descendants, <tt>String</tt> and <tt>Character</tt>. </p>
<p>You can have a look at the complete source at Github [<a href="https://github.com/andresteingress/groovy-null-safe-ast/">1</a>], please contribute or leave comments!</p>
<p>[0] <a href="http://groovy.codehaus.org/Local+AST+Transformations">Groovy Documentation on local AST transformations &#8211; http://groovy.codehaus.org/Local+AST+Transformations</a><br />
[1] <a href="https://github.com/andresteingress/groovy-null-safe-ast/">@NullSafe Github Project &#8211; https://github.com/andresteingress/groovy-null-safe-ast/</a></p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.andresteingress.com/2012/01/17/nullsafe-reloaded/"></a><br />
<noscript><a href="http://flattr.com/thing/467220/NullSafe-Reloaded" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2012/01/17/nullsafe-reloaded/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GContracts 1.2.5 Released!</title>
		<link>http://blog.andresteingress.com/2012/01/16/gcontracts-1-2-5-released/</link>
		<comments>http://blog.andresteingress.com/2012/01/16/gcontracts-1-2-5-released/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 10:29:23 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[gcontracts]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[releases]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1693</guid>
		<description><![CDATA[I am proud to announce that GContracts 1.2.5 has just been released and is available in the Central Maven repository [0] and at Github [1]. This release covers bug fixes, Groovy 1.8.4 and above compatibility and fixed a compilation error &#8230; <a href="http://blog.andresteingress.com/2012/01/16/gcontracts-1-2-5-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I am proud to announce that GContracts 1.2.5 has just been released and is available in the Central Maven repository [<a href="http://repo1.maven.org/maven2/org/gcontracts/gcontracts-core/1.2.5/">0</a>] and at Github [<a href="https://github.com/andresteingress/gcontracts/downloads">1</a>].</p>
<p>This release covers bug fixes, Groovy 1.8.4 and above compatibility and fixed a compilation error in Spock specifications.</p>
<h3>Release Notes</h3>
<ul>
<li>[<a href="http://gcontracts.lighthouseapp.com/projects/71511/tickets/33">33</a>] Unable to apply GContracts annotation on Spock methods</li>
<li>[<a href="http://gcontracts.lighthouseapp.com/projects/71511/tickets/34">34</a>] support for Groovy 1.8.x</li>
</ul>
<p>[0] <a href="http://repo1.maven.org/maven2/org/gcontracts/gcontracts-core/1.2.5/">GContracts 1.2.5 @ Central Maven Repository</a><br />
[1] <a href="https://github.com/andresteingress/gcontracts/downloads">Github Download Page</a></p>
<p>Special thanks to Evgeny Goldin for all of his contributions and testing!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2012/01/16/gcontracts-1-2-5-released/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>GSheets &#8211; A Groovy Builder based on Apache POI</title>
		<link>http://blog.andresteingress.com/2012/01/13/gsheets-a-groovy-builder-based-on-apache-poi/</link>
		<comments>http://blog.andresteingress.com/2012/01/13/gsheets-a-groovy-builder-based-on-apache-poi/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 07:59:31 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1681</guid>
		<description><![CDATA[I recently asked on Twitter whether there was an Apache POI [0] Groovy builder for generating Excel workbooks. I did find a few blog posts [1], [2], but none of the provided builders seemed to offer the ability to write &#8230; <a href="http://blog.andresteingress.com/2012/01/13/gsheets-a-groovy-builder-based-on-apache-poi/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I recently asked on Twitter whether there was an Apache POI [<a href="http://poi.apache.org/">0</a>] Groovy builder for generating Excel workbooks. I did find a few blog posts [<a href="http://skepticalhumorist.blogspot.com/2010/12/groovy-dslbuilders-poi-spreadsheets.html">1</a>], [<a href="http://www.technipelago.se/content/technipelago/blog/44">2</a>], but none of the provided builders seemed to offer the ability to write styled and formatted Excel workbooks with possibly multiple sheets.</p>
<p>So I decided to setup a new Github project (what else?) named <strong>GSheets</strong> [<a href="https://github.com/andresteingress/gsheets">3</a>]. At the current point of time it consists of a single class called <tt>ExcelFile</tt>, a Groovy builder for Excel workbooks based on HSSF [<a href="http://poi.apache.org/spreadsheet/">4</a>]. </p>
<pre class="brush: groovy; title: ; notranslate">
Workbook workbook = new ExcelFile().workbook {

            // section for workbook formatting styles
            styles {
                font(&quot;bold&quot;)  { Font font -&gt;
                    font.setBoldweight(Font.BOLDWEIGHT_BOLD)
                }

                cellStyle (&quot;header&quot;)  { CellStyle cellStyle -&gt;
                    cellStyle.setAlignment(CellStyle.ALIGN_CENTER)

                }
            }

	    // section for workbook data
            data {
                sheet (&quot;Export&quot;)  {
                    header([&quot;Column1&quot;, &quot;Column2&quot;, &quot;Column3&quot;])

                    row([&quot;a&quot;, &quot;b&quot;, &quot;c&quot;])
                }
            }

            // section for applying commands i.e. apply a cell style, merge cells etc.
            commands {
                applyCellStyle(cellStyle: &quot;header&quot;, font: &quot;bold&quot;, rows: 1, columns: 1..3)
            }
        }
</pre>
<p>As can be seen in the code sample above, <tt>ExcelFile</tt> gives a simple DSL for specifying styles, table data and commands. The <tt>styles</tt> section is used to define <tt>CellStyle</tt> objects. The <tt>data</tt> section specifies all the (header) rows and the <tt>commands</tt> section is used to apply styles, merge cells, and do various other operations on the current workbook sheet.</p>
<h3>What&#8217;s next?</h3>
<p>I plan to continuously extend <tt>ExcelFile</tt> with all the spreadsheet generating features HSSF provides. If you want to contribute, feel free to ping me on Twitter (@asteingr) or this blog. </p>
<p>[0] <a href="http://poi.apache.org/">Apache POI &#8211; http://poi.apache.org/</a><br />
[1] <a href="http://skepticalhumorist.blogspot.com/2010/12/groovy-dslbuilders-poi-spreadsheets.html">http://skepticalhumorist.blogspot.com/2010/12/groovy-dslbuilders-poi-spreadsheets.html</a><br />
[2] <a href="http://www.technipelago.se/content/technipelago/blog/44">http://www.technipelago.se/content/technipelago/blog/44</a><br />
[3] <a href="https://github.com/andresteingress/gsheets">GSheets Github &#8211; https://github.com/andresteingress/gsheets</a><br />
[4] <a href="http://poi.apache.org/spreadsheet/">Apache POI Spreadsheets &#8211; http://poi.apache.org/spreadsheet/</a></p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.andresteingress.com/2012/01/13/gsheets-a-groovy-builder-based-on-apache-poi/"></a><br />
<noscript><a href="http://flattr.com/thing/466150/GSheets-A-Groovy-Builder-based-on-Apache-POI" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2012/01/13/gsheets-a-groovy-builder-based-on-apache-poi/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[German] Android360 Ausgabe 4.2011</title>
		<link>http://blog.andresteingress.com/2011/11/21/german-android360-ausgabe-4-2011/</link>
		<comments>http://blog.andresteingress.com/2011/11/21/german-android360-ausgabe-4-2011/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 21:20:36 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[announcement]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1667</guid>
		<description><![CDATA[Die Ausgabe des Android360 Magazins [0] enthält einen Artikel von mir über Android Entwicklung mit Scala als alternative Dalvik VM Programmiersprache. Kaufen, lesen und endlich glücklich werden [0] Android360 Magazin &#8211; http://android360.de/]]></description>
			<content:encoded><![CDATA[<p><img src="http://blog.andresteingress.com/wp-content/uploads/2011/11/android360-cover.jpg" alt="" title="android360-cover" width="200" height="283" class="aligncenter size-full wp-image-1668" /></p>
<p>Die Ausgabe des Android360 Magazins [<a href="http://android360.de/">0</a>] enthält einen Artikel von mir über Android Entwicklung mit Scala als alternative Dalvik VM Programmiersprache.</p>
<p>Kaufen, lesen und endlich glücklich werden <img src='http://blog.andresteingress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>[0] <a href="http://android360.de/">Android360 Magazin &#8211; http://android360.de/</a></p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.andresteingress.com/2011/11/21/german-android360-ausgabe-4-2011/"></a><br />
<noscript><a href="http://flattr.com/thing/439641/Android360-Artikel-uber-Android-Entwicklung-mit-Scala" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2011/11/21/german-android360-ausgabe-4-2011/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anonymous Inner Classes in Android</title>
		<link>http://blog.andresteingress.com/2011/10/12/anonymous-inner-classes-in-android/</link>
		<comments>http://blog.andresteingress.com/2011/10/12/anonymous-inner-classes-in-android/#comments</comments>
		<pubDate>Wed, 12 Oct 2011 06:09:10 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[basic]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1580</guid>
		<description><![CDATA[This one is about anonymous classes and there implications for Android applications. Let&#8217;s have a look at the following code: As InnerClass is a so-called &#8220;anonymous private inner class&#8221;, it might reference instance variables from the enclosing class. What does &#8230; <a href="http://blog.andresteingress.com/2011/10/12/anonymous-inner-classes-in-android/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This one is about anonymous classes and there implications for Android applications.</p>
<p>Let&#8217;s have a look at the following code:</p>
<pre class="brush: java; title: ; notranslate">
public class OuterClass {

    private String someInstanceVariable = &quot;&quot;;

    private InnerClass anonymous = new InnerClass() {

        @Override public void someMethod() {
            someInstanceVariable = &quot;Test&quot;;
        }
    };
}
</pre>
<p>As <tt>InnerClass</tt> is a so-called &#8220;anonymous private inner class&#8221;, it might reference instance variables from the enclosing class. What does this mean at runtime?</p>
<p>In Java, whenever an <tt>OuterClass</tt> instance is created, the <tt>InnerClass</tt> instance will automatically have a reference to its client, the object of type <tt>OuterClass</tt>, implying that there is no inner class instance without an outer class instance. Let&#8217;s take a look at the compilation result of the above example.</p>
<p>The compilation results in two class files: <tt>OuterClass.class</tt> and <tt>OuterClass$1.class</tt>, whereas the latter holds the implementation of the anonymous inner class. After throwing both classes into a Java disassembler, we end up with the following source code:</p>
<pre class="brush: java; title: ; notranslate">
package org.example;

public class OuterClass
{

    public OuterClass()
    {
    	super();
    	someInstanceVariable = &quot;&quot;;
    	anonymous = new OuterClass$1(this);
    }

    static String access$002(OuterClass x0, String x1)
    {
    	this.someInstanceVariable = x1;
    	return this.someInstanceVariable;
    }

    private String someInstanceVariable;
    private InnerClass anonymous;

    class OuterClass$1 extends InnerClass
    {

        OuterClass$1(OuterClass outerClass)
        {
        	this$0 = outerClass;
        	super();
        }

        public void someMethod()
        {
        	OuterClass.access$002(this$0, &quot;Test&quot;);
        }

        final OuterClass this$0;
    }
}
</pre>
<p>The most important part in the Java disassembled code is the <tt>OuterClass$1</tt> class holding a reference to the actual <tt>OuterClass</tt> instance. This is an important issue to understand when working with the Android framework, as it makes heavy use of anonymous classes and non-static inner classes.</p>
<h3>Anonymous Inner Classes &amp; Android</h3>
<p>Let us now consider the following <tt>Activity</tt> implementation:</p>
<pre class="brush: java; title: ; notranslate">
public class SomeActivity extends Activity
{

    private View.OnClickListener onClickListener = new View.OnClickListener() {

        public void onClick(View view) {
            new SomeLongRunningTask().execute();
        }
    };

    private Button someButton;

    private class SomeLongRunningTask extends AsyncTask&lt;Void, Void, Boolean&gt; {

        @Override
        protected Boolean doInBackground(Void... voids) {

            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {}

            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            someButton.setText(aBoolean ? &quot;Successful&quot; : &quot;Fail&quot;);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        someButton = (Button) findViewById(R.id.someButton);
        someButton.setOnClickListener(onClickListener);
    }
}
</pre>
<p>As you can see the reference to the current <tt>Activity</tt> is implicitly embedded two times: </p>
<ul>
<li>it is embedded in the anonymous <tt>OnClickListener</tt> implementation class and
<li>it is embedded in the  <tt>SomeLongRunningTask</tt> class
</ul>
<p>In effect, this means these are <i>two potential places</i> in this very simple activity where e.g. an orientation change might indirectly cause the listener or asynchronous task to leak the current <tt>Activity</tt> instance. </p>
<p>Let us consider the classic case of device rotation. The <tt>OnClickListener</tt> is not the problem in this case as the activity object is completely destroyed and a new activity object instance is created by the framework (although it could be a problem depending on the code that is executed by the listener).</p>
<p>But it gets interesting with the <tt>SomeLongRunningTask</tt> class. As long as a task instance is running in the background, it keeps a reference to the activity object that created it, no matter if Android already re-created a new <tt>Activity</tt> instance or not.</p>
<h3>How to remove implicit references?</h3>
<p>One way to solve this problem would be to use a <i>static inner class</i>. One property of these classes is their missing reference to the outer class. As we will still need the reference to the <tt>Button</tt> to update its text message, we have to introduce a <tt>Handler</tt>. The <tt>Handler</tt> is the one that should be responsible for ui updates, as it has a reference to the current UI thread.</p>
<pre class="brush: java; title: ; notranslate">
public class SomeActivity extends Activity
{
    private static final int UPDATE_BUTTON_TEXT = 1;
    private static final SomeActivity me = null;

    private static Handler handler = new Handler() {
        public void handleMessage(Message msg)  {
          if (me == null) return;

          switch (msg.what)  {
            case UPDATE_BUTTON_TEXT:
              Button btn = (Button) me.findViewById(R.id.someButton);
              btn.setText((String) msg.obj);
          }
        }
    };

    private View.OnClickListener onClickListener = new View.OnClickListener() {
       public void onClick(View view) {
            new SomeLongRunningTask().execute();
        }
    };

    private static class SomeLongRunningTask extends AsyncTask&lt;Void, Void, Boolean&gt; {

        private Handler handler;

        public SomeLongRunningTask(Handler handler)  {
            this.handler = handler;
        }

        @Override
        protected Boolean doInBackground(Void... voids) {

            try {
                Thread.sleep(30000); // replace with some background logic
            } catch (InterruptedException e) {}

            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            Message msg = handler.obtainMessage(UPDATE_BUTTON_TEXT);
            msg.obj = &quot;success&quot;
            handler.sendMessage(msg);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button someButton = (Button) findViewById(R.id.someButton);
        someButton.setOnClickListener(onClickListener);
    }

    @Override
    protected void onStart() {
        super.onStart();

        me = this;
    }

    @Override
    protected void onStop() {
        me = null;

        super.onStop();
    }
}
</pre>
<h3>Conclusion</h3>
<p>After all, this is a very stripped down example. But when thinking of elaborate applications, programmers should know about anonymous classes and their (invisible) side-effects.</p>
<p>[0] <a href="http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html">Romain Guy &#8211; Avoiding Memory Leaks &#8211; http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html</a><br />
[1] <a href="http://ttlnews.blogspot.com/2010/01/attacking-memory-problems-on-android.html">Attacking Memory Problems on Android &#8211; http://ttlnews.blogspot.com/2010/01/attacking-memory-problems-on-android.html</a></p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.andresteingress.com/2011/10/12/anonymous-inner-classes-in-android/"></a><br />
<noscript><a href="http://flattr.com/thing/416612/Anonymous-Inner-Classes-in-Android" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2011/10/12/anonymous-inner-classes-in-android/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android Quick Tip: Using SQLite FTS Tables</title>
		<link>http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-sqlite-fts-tables/</link>
		<comments>http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-sqlite-fts-tables/#comments</comments>
		<pubDate>Fri, 30 Sep 2011 07:15:48 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[android]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1611</guid>
		<description><![CDATA[Some time ago I had to implement an Android dictionary application for one of my customers. Of course that dictionary application&#8217;s main feature was supposed to be its search capability. Using SQL &#8220;LIKE&#8221; queries was not an option as the &#8230; <a href="http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-sqlite-fts-tables/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Some time ago I had to implement an Android dictionary application for one of my customers. Of course that dictionary application&#8217;s main feature was supposed to be its search capability. Using SQL &#8220;LIKE&#8221; queries was not an option as the dictionary data set was pretty big and had to provide full-text searches not even for words but also for their textual descriptions.</p>
<p>As a consequence, I had to do some research on full-text search capabilities in Android. While reading through the dev guide on search dialogs, a sentence triggered my attention [<a href="http://developer.android.com/guide/topics/search/search-dialog.html">0</a>]:</p>
<blockquote><p>If your data is stored in a SQLite database on the device, performing a full-text search (using FTS3, rather than a LIKE query) can provide a more robust search across text data and can produce results significantly faster.</p></blockquote>
<p>FTS3? That sounded interesting and I did some research into that direction.</p>
<h3>The FTS3 SQLite Extension</h3>
<p>FTS is the acronym for &#8220;full-text search&#8221;. FTS3 itself is an SQLite extension that is now part of SQLite that provides support for creating virtual tables which in fact maintain an inverted index for full-text searches. That means you can use FTS tables to enable full-text search in Android applications.</p>
<p>Let us see how this was done in the dictionary application. The <tt>DatabaseOpenHelper</tt> class extended <tt>SQLiteOpenHelper</tt> and created (among others) a virtual table.</p>
<pre class="brush: java; title: ; notranslate">
public class DatabaseOpenHelper extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;

	public static final String TABLE_WORDS = &quot;WORDS&quot;;
	public static final String TABLE_WORDS_FTS = &quot;WORDS_FTS&quot;;
        // ...

	public static final String COL_ID = BaseColumns._ID;

	public static final String COL_KEY_LABEL = &quot;LABEL&quot;;
	public static final String COL_KEY_DESCRIPTION = &quot;DESCRIPTION&quot;;
	public static final String COL_KEY_LANGUAGE = &quot;LANGUAGE&quot;;

	public static final String COL_KEY_CODE = &quot;CODE&quot;;
	public static final String COL_KEY_NAME = &quot;NAME&quot;;

	public static final String COL_KEY_TERM = &quot;TERM&quot;;
	public static final String COL_KEY_LINKED_TERM = &quot;LINKED_TERM&quot;;

	public static final String COL_ACC_TIME = &quot;ACC_TIME&quot;;
	public static final String COL_ACC_DATE = &quot;ACC_DATE&quot;;
	public static final String COL_TERM_ID = &quot;WORD_ID&quot;;
	public static final String COL_ICON_ID = &quot;ICON_ID&quot;;

	public DatabaseOpenHelper(final Context context) {
		super(context, ApplicationConstants.DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(final SQLiteDatabase db) {
		executeDDL(db);
	}

	@Override
	public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
		dropIfExists(db);
		onCreate(db);
	}

	private void dropIfExists(final SQLiteDatabase db) {
		db.execSQL(&quot;DROP TABLE IF EXISTS &quot; + TABLE_WORDS);
		db.execSQL(&quot;DROP TABLE IF EXISTS &quot; + TABLE_WORDS_FTS);
		// ...
	}

	private void executeDDL(final SQLiteDatabase db) {
		Log.d(&quot;Database&quot;, &quot;Updating dictionary db ...&quot;);
		db.execSQL(&quot;CREATE TABLE &quot; + TABLE_WORDS + &quot;(&quot; + COL_ID + &quot; INTEGER PRIMARY KEY AUTOINCREMENT, &quot;
				+ COL_KEY_LABEL + &quot; VARCHAR(128), &quot; + COL_KEY_DESCRIPTION + &quot; TEXT, &quot; + COL_KEY_LANGUAGE + &quot; INTEGER, &quot;
				+ COL_KEY_TERM + &quot; INTEGER &quot; + &quot;);&quot;);

		db.execSQL(&quot;CREATE INDEX IF NOT EXISTS IDX_WORDS_TERM ON &quot; + TABLE_WORDS + &quot; (&quot; + COL_KEY_TERM + &quot;)&quot;);
		db.execSQL(&quot;CREATE INDEX IF NOT EXISTS IDX_WORDS_LANGUAGE ON &quot; + TABLE_WORDS + &quot; (&quot; + COL_KEY_LANGUAGE + &quot;)&quot;);

		db.execSQL(&quot;CREATE VIRTUAL TABLE &quot; + TABLE_WORDS_FTS + &quot; USING fts3(&quot; + COL_ID + &quot;, &quot; + COL_KEY_LABEL + &quot;, &quot;
				+ COL_KEY_DESCRIPTION + &quot; , &quot; + COL_KEY_LANGUAGE + &quot;, &quot; + COL_KEY_TERM + &quot; &quot; + &quot;);&quot;);

	}
}
</pre>
<p>The statement </p>
<pre class="brush: java; title: ; notranslate">
db.execSQL(&quot;CREATE VIRTUAL TABLE &quot; + TABLE_WORDS_FTS + &quot; USING fts3(&quot; + COL_ID + &quot;, &quot; + COL_KEY_LABEL + &quot;, &quot; + COL_KEY_DESCRIPTION + &quot; , &quot; + COL_KEY_LANGUAGE + &quot;, &quot; + COL_KEY_TERM + &quot; &quot; + &quot;);&quot;);
</pre>
<p>creates a virtual table using the FTS3 extension. The table can be filled and updated with the usual SQL commands but uses an inverted index for fast full-text searches underneath.</p>
<p>The interesting part is the query syntax. FTS3 tables are queried using the <tt>MATCH</tt> keyword.</p>
<pre class="brush: java; title: ; notranslate">
public class DictionaryRepository {

   // ...
   public Cursor queryFulltextTermsForLanguage(String query, final Long languageId) {
        assert !TextUtils.isEmpty(query) : &quot;query must not be an empty string!&quot;;
        assert languageId &gt;= 0: &quot;LanguageId must be greater or equal than 0&quot;;

        return database.query(DatabaseOpenHelper.TABLE_WORDS_FTS,
                new String[] { DatabaseOpenHelper.COL_KEY_TERM, DatabaseOpenHelper.COL_KEY_LABEL, DatabaseOpenHelper.COL_KEY_LANGUAGE, DatabaseOpenHelper.COL_ID },
                DatabaseOpenHelper.TABLE_WORDS_FTS + &quot; MATCH ?&quot;,
                new String[] { appendWildcard(query) + &quot; &quot; + DatabaseOpenHelper.COL_KEY_LANGUAGE + &quot;: &quot; + languageId.toString() },
                null, null, null);
    }

    private String appendWildcard(String query) {
        if (TextUtils.isEmpty(query)) return query;

        final StringBuilder builder = new StringBuilder();
        final String[] splits = TextUtils.split(query, &quot; &quot;);

        for (String split : splits)
          builder.append(split).append(&quot;*&quot;).append(&quot; &quot;);

        return builder.toString().trim();
    }
    // ...
}
</pre>
<p>As can be seen from the example above, the FTS3 supports not even unqualified queries like</p>
<pre class="brush: sql; title: ; notranslate">
SELECT * FROM words_fts WHERE words_fts MATCH 'company';
</pre>
<p>but also qualified queries identifying the query columns by <tt>column: columnName</tt></p>
<pre class="brush: sql; title: ; notranslate">
SELECT * FROM words_fts WHERE words_fts MATCH 'description: company';
</pre>
<p>and the <tt>*</tt> operator</p>
<pre class="brush: sql; title: ; notranslate">
SELECT * FROM words_fts WHERE words_fts MATCH 'description: comp*';
</pre>
<p>A complete guide on FTS full-text queries can be found at [<a href="http://www.SQLite.org/fts3.html#section_3">2</a>].</p>
<p>[0] <a href="http://developer.android.com/guide/topics/search/search-dialog.html">Creating a Search Interface &#8211; Android Developer</a><br />
[1] <a href="http://www.SQLite.org/fts3.html#section_1">Introduction to FTS3 and FTS4</a><br />
[2] <a href="http://www.SQLite.org/fts3.html#section_3">FTS3 Full-Text Index Queries</a></p>
<p><a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-SQLite-fts-tables/"></a><br />
<noscript><a href="http://flattr.com/thing/407839/Android-Quick-Tip-Using-SQLite-FTS-Tables" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2011/09/30/android-quick-tip-using-sqlite-fts-tables/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Fighting Orientation Changes in Android</title>
		<link>http://blog.andresteingress.com/2011/09/27/fighting-orientation-changes-in-android/</link>
		<comments>http://blog.andresteingress.com/2011/09/27/fighting-orientation-changes-in-android/#comments</comments>
		<pubDate>Tue, 27 Sep 2011 08:30:36 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[android]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1543</guid>
		<description><![CDATA[One of the problems beginners often struggle with in Android is orientation changes. The problem with an orientation change is that it per se destroys the currently running activity, creates a new instance and starts that instance with the original &#8230; <a href="http://blog.andresteingress.com/2011/09/27/fighting-orientation-changes-in-android/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the problems beginners often struggle with in Android is <i>orientation changes</i>. The problem with an orientation change is that it per se destroys the currently running activity, creates a new instance and starts that instance with the original <tt>Intent</tt> again.</p>
<p>This behavior can be pretty disturbing in applications with multiple background threads/asynchronous tasks. This article shows how to handle background threads when the current activity instance is destroyed and created back and forth.</p>
<h3>Orientation Change Behavior</h3>
<p>For the matter of purpose let us assume we have an Activity that shows a large Image using an <tt>ImageView</tt> loaded from a web server. As the image is very large we decided to show a progress dialog during loading the image.</p>
<pre class="brush: java; title: ; notranslate">

public class RemoteImageViewActivity extends Activity {

  private ImageView imageView;
  private ProgressDialog dialog;

  private class DownloadImageTask extends AsyncTask&lt;URL, Integer, Bitmap&gt; {
     protected Bitmap doInBackground(URL... urls) {
         return Downloader.downloadFile(urls[0]); // or for testing purpose just Thread.sleep(30000);
     }

     protected void onPostExecute(Bitmap bitmap) {
         imageView.setImageBitmap(bitmap);
         dialog.dismiss();
     }
 }

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) findViewById(R.id.imageView);
        dialog = ProgressDialog.show(this, &quot;&quot;, &quot;Loading. Please wait...&quot;, true);

        try {
            new DownloadImageTask().execute(new URL(&quot;http://blog.andresteingress.com/&quot;));

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }
}
</pre>
<p>The example above shows a straight-forward implementation I&#8217;ve already seen in a handful of Android applications (mine included <img src='http://blog.andresteingress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).</p>
<p>Now let us see what happens when an orientation change happens during the image is downloaded. As can be seen from the stack trace below, when orientation is changed, our code somehow leaks an activity instance</p>
<pre class="brush: java; title: ; notranslate">
ERROR/WindowManager(1336): Activity com.example.RemoteImageViewActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051c210 that was originally added here
        android.view.WindowLeaked: Activity com.example.RemoteImageViewActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051c210 that was originally added here
        at android.view.ViewRoot.&lt;init&gt;(ViewRoot.java:258)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
        at android.view.Window$LocalWindowManager.addView(Window.java:424)
        at android.app.Dialog.show(Dialog.java:241)
        at android.app.ProgressDialog.show(ProgressDialog.java:107)
        at android.app.ProgressDialog.show(ProgressDialog.java:90)
        at com.example.RemoteImageViewActivity.onCreate(RemoteImageViewActivity.java:44)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
        at android.app.ActivityThread.access$1500(ActivityThread.java:117)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:130)
        at android.app.ActivityThread.main(ActivityThread.java:3683)
</pre>
<p>and after a while when the dialog needs to be dismissed another exception happens</p>
<pre class="brush: java; title: ; notranslate">

ERROR/AndroidRuntime(1336): FATAL EXCEPTION: main
        java.lang.IllegalArgumentException: View not attached to window manager
        at android.view.WindowManagerImpl.findViewLocked(WindowManagerImpl.java:355)
        at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:200)
        at android.view.Window$LocalWindowManager.removeView(Window.java:432)
        at android.app.Dialog.dismissDialog(Dialog.java:278)
        at android.app.Dialog.access$000(Dialog.java:71)
        at android.app.Dialog$1.run(Dialog.java:111)
        at android.app.Dialog.dismiss(Dialog.java:268)
</pre>
<p>The behavior seems odd at first glance, but when digging into the Android documentation, one finds the reason: per default Android recreates the currently running activity whenever the orientation is changed. That explains why <tt>onPostExecute</tt> can&#8217;t access the current application window and throws an exception (the first exception with the leaking activity instance is explained in a minute).</p>
<h3>Handling Orientation changes</h3>
<p>There are several ways how to handle an orientation change without leaking windows or accessing &#8220;dead&#8221; views. In our example above, one way would be to leave the dialog management over to the current <tt>Activity</tt>. This is done by overriding <tt>onCreateDialog</tt> and using its companion methods <tt>showDialog</tt> and <tt>dismissDialog</tt>.</p>
<pre class="brush: java; title: ; notranslate">
public class RemoteImageViewActivity extends Activity
{

    protected static final int PROGRESS_BAR_DIALOG = 1;

    private ImageView imageView;

    private class DownloadImageTask extends AsyncTask&lt;URL, Integer, Bitmap&gt; {
        protected Bitmap doInBackground(URL... urls) {

            try {
                Thread.sleep(30000);

                return Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);

            } catch (InterruptedException e) {
                return null;
            }
        }

        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);

            dismissDialog(PROGRESS_BAR_DIALOG);
        }
    }

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) findViewById(R.id.imageView);

        showDialog(PROGRESS_BAR_DIALOG);

        try {
            new DownloadImageTask().execute(new URL(&quot;http://blog.andresteingress.com/&quot;));

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override protected Dialog onCreateDialog(int id) {
        switch (id)  {
            case PROGRESS_BAR_DIALOG:
                return new ProgressDialog.Builder(this).setTitle(&quot;&quot;).setMessage(&quot;Loading. Please wait...&quot;).setCancelable(false).create();
        }

        return null;
    }
}
</pre>
<p>Overriding the <tt>onCreateDialog</tt> has the advantage that the <tt>Activity</tt> base class handles persisting the dialogs state and recreating the dialog on orientation changes.</p>
<p>The problem with the example above is that changing the orientation twice or more times, leads again to the view leaking exception from above as the <tt>onCreate</tt> method of the activity is called whenever the orientation is changed.</p>
<pre class="brush: java; title: ; notranslate">
ERROR/WindowManager(1336): Activity com.example.RemoteImageViewActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051c210 that was originally added here
        android.view.WindowLeaked: Activity com.example.RemoteImageViewActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051c210 that was originally added here
        at android.view.ViewRoot.&lt;init&gt;(ViewRoot.java:258)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
        at android.view.Window$LocalWindowManager.addView(Window.java:424)
        at android.app.Dialog.show(Dialog.java:241)
        at android.app.ProgressDialog.show(ProgressDialog.java:107)
        at android.app.ProgressDialog.show(ProgressDialog.java:90)
        at com.example.RemoteImageViewActivity.onCreate(RemoteImageViewActivity.java:44)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
        at android.app.ActivityThread.access$1500(ActivityThread.java:117)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:130)
        at android.app.ActivityThread.main(ActivityThread.java:3683)
</pre>
<p>This behavior is caused by <tt>DownloadImageTask</tt> being an inner class. After the orientation change, the asynchronous task refers to the old activity instance and, even worse, it additionally has a reference to the imageView to set the downloaded image accordingly.</p>
<p>But how could we solve that binding to the outer activity instance in our <tt>DownloadImageTask</tt> task class?</p>
<h3>Using a static Handler/Activity Combo</h3>
<p>In order to handle the problem with references to the old activity inside inner class object instances, we could use static variables in combination with Android&#8217;s <tt>Handler</tt> class. </p>
<pre class="brush: java; title: ; notranslate">
public class RemoteImageViewActivity extends Activity
{
    private static RemoteImageViewActivity ACTIVITY = null;

    private static final int SHOW_PROGRESS_BAR_DIALOG = 1;
    private static final int HIDE_PROGRESS_BAR_DIALOG = 2;
    private static final int SHOW_IMAGE = 3;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (ACTIVITY == null) return;

            switch (msg.what)  {
                case SHOW_PROGRESS_BAR_DIALOG:
                     ACTIVITY.showDialog(PROGRESS_BAR_DIALOG);
                    break;

                case HIDE_PROGRESS_BAR_DIALOG:
                    ACTIVITY.dismissDialog(PROGRESS_BAR_DIALOG);
                    break;

                case SHOW_IMAGE:
                    ImageView imageView = (ImageView) ACTIVITY.findViewById(R.id.imageView);
                    imageView.setImageBitmap((Bitmap) msg.obj);

            }
        }
    };

    protected static final int PROGRESS_BAR_DIALOG = 1;

    private static class DownloadImageTask extends AsyncTask&lt;URL, Integer, Bitmap&gt; {

        private Handler handler;

        public DownloadImageTask(Handler handler)  {
            this.handler = handler;
        }

        protected Bitmap doInBackground(URL... urls) {

            try {
                Thread.sleep(30000);

                return Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);

            } catch (InterruptedException e) {
                return null;
            }
        }

        protected void onPostExecute(Bitmap bitmap) {
            handler.sendEmptyMessage(HIDE_PROGRESS_BAR_DIALOG);
            handler.sendMessage(Message.obtain(handler, SHOW_IMAGE, bitmap));
        }
    }

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        handler.sendEmptyMessage(SHOW_PROGRESS_BAR_DIALOG);

        try {
            new DownloadImageTask(handler).execute(new URL(&quot;http://blog.andresteingress.com/&quot;));

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        ACTIVITY = this;
    }

    @Override
    protected void onStop() {
        ACTIVITY = null;

        super.onStop();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id)  {
            case PROGRESS_BAR_DIALOG:
                return new ProgressDialog.Builder(this).setTitle(&quot;&quot;).setMessage(&quot;Loading. Please wait...&quot;).setCancelable(false).create();
        }

        return null;
    }
}
</pre>
<p>The code above always keeps a reference to the current <tt>Activity</tt> in a static class variable. The asynchronous task implementation now keeps a reference to the <tt>Handler</tt> instance, avoiding to refer to the old <tt>Activity</tt> instance. With this little trick we can now safely switch orientations while the background task is running.</p>
<p>But wait, didn&#8217;t we see that <tt>onCreate</tt> is called multiple times during orientation changes? That means, whenever the orientation is changed we create a new instance of <tt>DownloadImageTask</tt> and start the task again!</p>
<h3>Overriding <tt>android:configChanges</tt></h3>
<p>One way to solve the problem is to introduce another static variable indicating whether the download is currently running in the background or not. But there is another way: we can provide the <tt>android:configChanges="orientation"</tt> XML attribute in our <tt>AndroidManifest.xml</tt>.</p>
<p>The <tt>configChanges</tt> attribute is documented [<a href="http://developer.android.com/guide/topics/manifest/activity-element.html#config">0</a>] as</p>
<blockquote><p>Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called.</p></blockquote>
<p>where as <tt>orientation</tt> is used to react on orientation changes.</p>
<p>Let&#8217;s add <tt>android:configChanges="orientation"</tt> to our activity XML declaration and modify the code to</p>
<pre class="brush: java; title: ; notranslate">
public class RemoteImageViewActivity extends Activity
{

    protected static final int PROGRESS_BAR_DIALOG = 1;

    private ImageView imageView;

    private class DownloadImageTask extends AsyncTask&lt;URL, Integer, Bitmap&gt; {
        protected Bitmap doInBackground(URL... urls) {

            try {
                Thread.sleep(30000);

                return Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);

            } catch (InterruptedException e) {
                return null;
            }
        }

        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);

            dismissDialog(PROGRESS_BAR_DIALOG);
        }
    }

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        imageView = (ImageView) findViewById(R.id.imageView);

        showDialog(PROGRESS_BAR_DIALOG);

        try {
            new DownloadImageTask().execute(new URL(&quot;http://blog.andresteingress.com/&quot;));

        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id)  {
            case PROGRESS_BAR_DIALOG:
                return new ProgressDialog.Builder(this).setTitle(&quot;&quot;).setMessage(&quot;Loading. Please wait...&quot;).setCancelable(false).create();
        }

        return null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // some work that needs to be done on orientation change
    }
}
</pre>
<p>By overriding the <tt>onConfigurationChanged</tt> method we have avoided activity recreation, which &#8211; in our case &#8211; does not seem to be necessary. As you can see in the code above, with this approach we do avoid the use of static class variables and the <tt>Handler</tt> object instance.</p>
<h3>Conclusion</h3>
<p>There are various ways to handle orientation changes and activity recreations in Android. If you have any other tips or preferred ways to do so, you are free to mention them in this article&#8217;s comments section.</p>
<p>[0] <a href="http://developer.android.com/guide/topics/manifest/activity-element.html#config">android:configChanges Documentation &#8211; http://developer.android.com/guide/topics/manifest/activity-element.html#config</a></p>
<p><a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://blog.andresteingress.com/2011/09/27/fighting-orientation-changes-in-android/"></a><br />
<noscript><a href="http://flattr.com/thing/404165/Fighting-Orientation-Changes-in-Android" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2011/09/27/fighting-orientation-changes-in-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>To Scale or not to Scale</title>
		<link>http://blog.andresteingress.com/2011/09/22/to-scale-or-not-to-scale/</link>
		<comments>http://blog.andresteingress.com/2011/09/22/to-scale-or-not-to-scale/#comments</comments>
		<pubDate>Thu, 22 Sep 2011 09:19:47 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[android]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1493</guid>
		<description><![CDATA[As this is yet another day I can&#8217;t remember the various differences and meanings of the android:scaleType attribute values, I decided to have a closer look at the scaling mechanisms provided by ImageView. The ImageView died that day Android&#8217;s ImageView &#8230; <a href="http://blog.andresteingress.com/2011/09/22/to-scale-or-not-to-scale/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As this is yet another day I can&#8217;t remember the various differences and meanings of the <tt>android:scaleType</tt> attribute values, I decided to have a closer look at the scaling mechanisms provided by <tt>ImageView</tt>.</p>
<h3>The <tt>ImageView</tt> died that day</h3>
<p>Android&#8217;s <tt>ImageView</tt> class is used to draw arbitrary <tt>Drawable</tt> objects [<a href="http://developer.android.com/reference/android/widget/ImageView.html">0</a>]. For the purpose of better understanding its internals, let us assume this class was not part of the Android framework and we would have to introduce a similar class for our project. How should the implementation look like?</p>
<h3>The <tt>DrawableView</tt></h3>
<p>Let&#8217;s name our class <tt>DrawableView</tt> as it is used solely to show object instances of type <tt>Drawable</tt> and extend it from <tt>View</tt> as this is the case with every other UI widget.</p>
<pre class="brush: java; title: ; notranslate">

public class DrawableView extends View {

    public DrawableView(Context context) {
        super(context);
    }

    public DrawableView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DrawableView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
}
</pre>
<p>Now we have to add a custom <tt>drawable</tt> attribute to be used in the XML layout definition. So let&#8217;s create a <tt>res/values/attrs.xml</tt></p>
<pre class="brush: xml; title: ; notranslate">
&lt;resources&gt;
    &lt;declare-styleable name=&quot;com.example.DrawableView&quot;&gt;
        &lt;attr name=&quot;src&quot; format=&quot;reference&quot;/&gt;
    &lt;/declare-styleable&gt;
&lt;/resources&gt;
</pre>
<p>And add code to our <tt>DrawableView</tt> to retrieve the <tt>Drawable</tt> instance that will later on be referenced via the newly created <tt>src</tt> XML attribute</p>
<pre class="brush: java; title: ; notranslate">

// ...

private Drawable drawable;

public DrawableView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.com_example_DrawableView, defStyle, 0);
        drawable = typedArray.getDrawable(R.styleable.com_example_DrawableView_src);

        typedArray.recycle();
}

// ...
</pre>
<p>Reading the <tt>src</tt> XML attribute in combination with the standard Android XML attributes already allows us to specify a header image in our layout view.</p>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout
    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:example=&quot;http://schemas.android.com/apk/res/com.example&quot;

    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;&gt;

    &lt;com.example.DrawableView
        android:id=&quot;@+id/header&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_width=&quot;fill_parent&quot;
        example:src=&quot;@drawable/header&quot;/&gt;

&lt;/LinearLayout&gt;
</pre>
<p>As you can see in the code snippet above, <tt>android:layout_width</tt> and <tt>android:layout_height</tt> are used to specify the <tt>View</tt>&#8216;s size. In my case the header image is 800 x 200 pixels, now the question raises what to do if a) the view is larger than the referenced image or b) the view is smaller than the referenced image.</p>
<p>Let&#8217;s start with the first case &#8211; the view is larger than the image.</p>
<h3>Case 1  &#8211; View &gt; Image</h3>
<p>If the available view space is larger than the image, we want a way to specify that the image should be centered horizontally and vertically within the available space &#8211; this is exactly the case with <tt>ImageView.ScaleType.CENTER</tt>. The image is centered without scaling.</p>
<p>To make our <tt>DrawableView</tt> work we will have to implement <tt>onMeasure</tt> first.</p>
<pre class="brush: java; title: ; notranslate">

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int width  = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();

        width  = Math.max(width, getSuggestedMinimumWidth());
        height = Math.max(height, getSuggestedMinimumHeight());

        setMeasuredDimension(resolveSize(width, widthMeasureSpec), resolveSize(height, heightMeasureSpec));
    }
</pre>
<p>First of all we&#8217;ll have to read the drawable&#8217;s width and height. If a minimum size is specified we&#8217;ll have to take that into account using the <tt>Math.max</tt> static method. The most important part is the final line: here we used the <tt>View.resolveSize</tt> method to set the measured width and height accordingly.</p>
<p><tt>resolveSize</tt> acts upon the parent views measure specification. In our case we are using a linear layout that fills its parent view and we have specified <tt>android:layout_width="fill_parent"</tt> and <tt>android:layout_height="wrap_content"</tt>. Given we use a very small header file for testing purposes (e.g. with 200 x 50 pixels), <tt>resolveSize</tt> would return the width of the actual screen (e.g. 320) but the height of the drawable we suggested. If we would have declared the height to fill the parent view, <tt>resolveSize</tt> would return the total height otherwise.</p>
<p>Now let us implement the drawing functionality.</p>
<pre class="brush: java; title: ; notranslate">

    private Drawable drawable;
    private Matrix matrix = new Matrix();

    private int drawableWidth, drawableHeight;
    private int viewWidth, viewHeight;

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        drawableWidth  = drawable.getIntrinsicWidth();
        drawableHeight = drawable.getIntrinsicHeight();

        int width  = Math.max(drawableWidth, getSuggestedMinimumWidth());
        int height = Math.max(drawableHeight, getSuggestedMinimumHeight());

        viewWidth  = resolveSize(width, widthMeasureSpec);
        viewHeight = resolveSize(height, heightMeasureSpec);

        setMeasuredDimension(viewWidth, viewHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int saveCount = canvas.save();

        // this will center the small header image
        matrix.setTranslate((int) ((viewWidth - drawableWidth) * 0.5f + 0.5f), (int) ((viewHeight - drawableHeight) * 0.5f + 0.5f));

        canvas.concat(matrix);

        drawable.setBounds(0, 0, drawableWidth, drawableHeight);
        drawable.draw(canvas);

        canvas.restoreToCount(saveCount);
    }
</pre>
<p>I had to refactor the previous code in <tt>onMeasure</tt>, to store the measured width and height in instance variables. Just drawing the given <tt>drawable</tt> on the canvas is easy and is done by a call to <tt>drawable.draw(canvas)</tt>. But we want our drawable to be centered in the middle of our <tt>DrawableView</tt> bounds. This is done by applying a matrix which translates every single pixel of the drawable by a given amount of pixels. </p>
<p>Translation is nothing but a simple calculation whereas each point in matrix M gets translated via <i>M&#8217; = M * T(dx, dy)</i>.</p>
<p><img src="http://blog.andresteingress.com/wp-content/uploads/2011/09/header_small_centered.png" alt="" title="header_small_centered" width="328" height="492" class="aligncenter size-full wp-image-1509" /></p>
<p>With the code above we have already implemented exactly the same functionality as if we applied <tt>android:scaleType="center"</tt> to an Android <tt>ImageView</tt>. Cool, isn&#8217;t it? Now let&#8217;s consider a case that includes image scaling.</p>
<h3>Case 2 &#8211; View &lt; Drawable </h3>
<p>Let us assume we replace the small header image with a large one, say 800 x 200 px. With a screen height of 480 px the height of the image would fit, but the width of the image is too large. What to do in that case? One approach would be to still keep the image ratio, but scale the image so that at least one axis fits for the view and center the result &#8211; which leads to cropping the left/right and/or upper/lower part of the image.</p>
<p>That means for our 800 x 200 px image, that the full height is drawn (assuming the screen height has 480 px), but the image width is cropped by 480 pixels, 240 left and 240 right.</p>
<pre class="brush: java; title: ; notranslate">

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int saveCount = canvas.save();

        float scale;
        float dx = 0, dy = 0;

        if (drawableWidth * viewHeight &gt; viewWidth * drawableHeight) {
            scale = (float) viewHeight / (float) drawableHeight;
            dx = (viewWidth - drawableWidth * scale) * 0.5f;
        } else {
            scale = (float) viewWidth / (float) drawableWidth;
            dy = (viewHeight - drawableHeight * scale) * 0.5f;
        }

        matrix.setScale(scale, scale);
        matrix.postTranslate((int) (dx + 0.5f), (int) (dy + 0.5f));

        canvas.concat(matrix);

        drawable.setBounds(0, 0, drawableWidth, drawableHeight);
        drawable.draw(canvas);

        canvas.restoreToCount(saveCount);
    }
</pre>
<p>The scaling mechanism seen in the <tt>onDraw</tt> method above is used to scale the image accordingly to the view&#8217;s bounds. In our case, we specified <tt>fill_parent</tt> and <tt>wrap_content</tt>, but that could have been also absolute measures or other layout measures. </p>
<p><img src="http://blog.andresteingress.com/wp-content/uploads/2011/09/header_centerCrop.png" alt="" title="header_centerCrop" width="323" height="484" class="aligncenter size-full wp-image-1510" /></p>
<p>Ah, and the code above is exactly what <tt>android:scaleType="centerCrop"</tt> causes.</p>
<p>But cropping isn&#8217;t that beautiful, is it? Let&#8217;s implement the <tt>onDraw</tt> method to scale the image so that it fits within the given view bounds, still keeping the image ratio.</p>
<pre class="brush: java; title: ; notranslate">
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int saveCount = canvas.save();

        float scale;
        float dx;
        float dy;

        if (drawableWidth &lt;= viewWidth &amp;&amp; drawableHeight &lt;= viewHeight) {
            scale = 1.0f;
        } else {
            scale = Math.min((float) viewWidth / (float) drawableWidth,
                    (float) viewHeight / (float) drawableHeight);
        }

        dx = (int) ((viewWidth - drawableWidth * scale) * 0.5f + 0.5f);
        dy = (int) ((viewHeight - drawableHeight * scale) * 0.5f + 0.5f);

        matrix.setScale(scale, scale);
        matrix.postTranslate(dx, dy);

        canvas.concat(matrix);

        drawable.setBounds(0, 0, drawableWidth, drawableHeight);
        drawable.draw(canvas);

        canvas.restoreToCount(saveCount);
    }
</pre>
<p>As you can see in the screenshot below, the actual <tt>View</tt> bounds are now larger than the drawable height what we returned in <tt>onMeasure</tt>. Android&#8217;s <tt>ImageView</tt> behaves exactly the same, but it provides an attribute to adjust the view bounds to the image bounds: <tt>android:adjustViewBounds</tt>.</p>
<p><img src="http://blog.andresteingress.com/wp-content/uploads/2011/09/header_centerInside.png" alt="" title="header_centerInside" width="322" height="485" class="aligncenter size-full wp-image-1511" /></p>
<p>To apply the view bounds to the scaled drawable dimensions, we would need to write</p>
<pre class="brush: xml; title: ; notranslate">
&lt;ImageView
        android:id=&quot;@+id/header&quot;

        android:layout_height=&quot;wrap_content&quot;
        android:layout_width=&quot;fill_parent&quot;
        android:scaleType=&quot;centerInside&quot;

        android:adjustViewBounds=&quot;true&quot;

        android:src=&quot;@drawable/header&quot;/&gt;
</pre>
<p>Which results in</p>
<p><img src="http://blog.andresteingress.com/wp-content/uploads/2011/09/header_adjustView.png" alt="" title="header_adjustView" width="324" height="482" class="aligncenter size-full wp-image-1533" /></p>
<h3>What about the other <tt>ScaleType</tt> configuration values?</h3>
<p>What we did not see so far is the implementation of <tt>ImageView.ScaleType.FIT_*</tt> attributes and <tt>ImageView.ScaleType.MATRIX</tt>.</p>
<p>The <tt>ImageView.ScaleType.MATRIX</tt> attribute can be set to use a custom matrix when drawing the image. With <tt>ImageView.setImageMatrix</tt> arbitrary operations can be executed during drawing the drawable.</p>
<p>All <tt>FIT_*</tt> scale types actually use the <tt>Matrix.setRectToRect</tt> method, which allows to translate between two given rectangular bounds.</p>
<pre class="brush: java; title: ; notranslate">

Rect src = new Rect(0, 0, drawableWidth, drawableHeight);
Rect dst = new Rect(0, 0, viewWidth, viewHeight);

matrix.setRectToRect(src, dst, scaleType);
</pre>
<p>The interesting part in the example above is the <tt>scaleType</tt>. This can be one of <tt>Matrix.ScaleToFit</tt> enumeration values: <tt>CENTER</tt>, <tt>START</tt>, <tt>END</tt> and <tt>FILL</tt> which exactly map to <tt>ImageView.ScaleType</tt>&#8216;s <tt>FIT_CENTER</tt>, <tt>FIT_START</tt>, <tt>FIT_END</tt> and <tt>FIT_XY</tt>. This means that all fit operations internally use a drawing matrix that scale from the drawl bounds to the actual view bounds.</p>
<h3>Conclusion</h3>
<p>This article tried to bring light into Android&#8217;s <tt>ImageView</tt> various scaling options. In fact, with some basic knowledge about the <tt>View</tt>, <tt>Canvas</tt> and <tt>Matrix</tt> classes and some Matrix operations we were able to implement our <tt>DrawableView</tt>clone.</p>
<p>The code for this blog post can be found at Github: <a href="https://github.com/andresteingress/android-drawable-view">https://github.com/andresteingress/android-drawable-view</a> [<a href="https://github.com/andresteingress/android-drawable-view">1</a>]</p>
<p>[0] <a href="http://developer.android.com/reference/android/widget/ImageView.html">The ImageView Documentation &#8211; http://developer.android.com/reference/android/widget/ImageView.html</a><br />
[1] <a href="https://github.com/andresteingress/android-drawable-view">android-drawable-view Example Project @ Github &#8211; https://github.com/andresteingress/android-drawable-view</a></p>
<p><a class="FlattrButton" style="display:none;" rev="flattr;button:compact;" href="http://blog.andresteingress.com/2011/09/22/to-scale-or-not-to-scale/"></a><br />
<noscript><a href="http://flattr.com/thing/404166/To-Scale-or-not-to-Scale" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2011/09/22/to-scale-or-not-to-scale/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Programming Android with Scala</title>
		<link>http://blog.andresteingress.com/2011/09/20/programming-android-with-scala/</link>
		<comments>http://blog.andresteingress.com/2011/09/20/programming-android-with-scala/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 19:37:06 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[android]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=1448</guid>
		<description><![CDATA[As I&#8217;ve mentioned in my previous blog post, I am working on several Android projects. Once you&#8217;ve done some larger projects and you have already worked with alternative JVM languages like Groovy [0] or Scala [1], one quickly feels the &#8230; <a href="http://blog.andresteingress.com/2011/09/20/programming-android-with-scala/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As I&#8217;ve mentioned in my previous blog post, I am working on several Android projects. Once you&#8217;ve done some larger projects and you have already worked with alternative JVM languages like Groovy [<a href="http://groovy.codehaus.org/">0</a>] or Scala [<a href="http://www.scala-lang.org/node/1305">1</a>], one quickly feels the need for reducing common code patterns found in every Android project. That was the main reason I chose to use Scala as main programming language for one of my free-time Android projects.</p>
<p>This article is about my experiences with Scala and the language features I found most useful when working with the Android framework.</p>
<h3>Environment and Prerequisites</h3>
<p>First of all: I am an IntelliJ user, working on a MBP. I did not test how writing an Android app with Scala works out in Eclipse. I usually develop all my Android projects in IntelliJ as Eclipse and the Android plugin just did not work out for me (it constantly slows down, hangs, of course your mileage may vary).</p>
<p>I installed the android-sdk, scala, sbt etc. with Homebrew
<pre>brew install scala sbt android-sdk</pre>
<p> and worked with the following package/software versions:</p>
<ul>
<li>Scala: 2.9.1
<li>Sbt: 0.10.1
<li>android-sdk: r12
<li>IntelliJ: 10.5.2
<li>Mac OSX: 10.7.1
</ul>
<h3>Setting up the project structure and environment</h3>
<p>First of all: I don&#8217;t want to scare you right away, but neither IntelliJ nor Eclipse (to my knowledge) offers support for developing Android projects with Scala in a continuous process from project creation to APK creation. There is no out-of-the-box configuration, you&#8217;ll need to have some manual or scripted steps when developing outside the standard Android environment.</p>
<p>On the other side, IntelliJ offers seperate module facets for Android and Scala projects. When combining the Scala and Android facet you&#8217;ll get syntax completion for Scala and Android-specific files, automatic <tt>R.java</tt> file compilation, sbt APK debug package generation (with a separate run configuration) and, well, the joy to use Scala instead of Java for your Android project <img src='http://blog.andresteingress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<p>I don&#8217;t want to go into details of IntelliJ module configuration, but in case you chose to work with sbt [<a href="https://github.com/harrah/xsbt/wiki">3</a>] you can use a giter8 template [<a href="https://github.com/n8han/giter8#readme">2</a>] to jump-start with an sbt supported project structure holding an empty Android application and test setup (for more information see [<a href="https://github.com/jberkel/android-plugin">4</a>]).</p>
<h3>Using Scala for your <tt>Activity</tt> classes</h3>
<p>Once you are done setting up the environment, you can start with your first activity, let&#8217;s call it <tt>HomeActivity</tt>. Let&#8217;s take a look at the Java implementation.</p>
<pre class="brush: java; title: ; notranslate">
public class HomeActivity extends Activity {

    public void onCreate(Bundle savedState)  {
        super.onCreate(savedState);
        setContentView(R.layout.home);
    }
}
</pre>
<p>Since we do need some UI widgets, we will add a login and password EditText field and a Button and add the according code to the <tt>Activity</tt> class:</p>
<pre class="brush: java; title: ; notranslate">
public class HomeActivity extends Activity {

private EditText usernameEditText;
private EditText passwordEditText;
private Button   loginButton;

public void onCreate(Bundle savedState)  {
  super.onCreate(savedState);
  setContentView(R.layout.home);

  usernameEditText = (EditText) findViewById(R.id.usernameEditText);
  passwordEditText = (EditText) findViewById(R.id.passwordEditText);
  loginButton = (Button) findViewById(R.id.loginButton);
}
}
</pre>
<p>Next we&#8217;ll register a <tt>View.OnClickListener</tt> to react on button clicks/touches:</p>
<pre class="brush: java; title: ; notranslate">

public class HomeActivity extends Activity {

private EditText usernameEditText;
private EditText passwordEditText;
private Button   loginButton;

public void onCreate(Bundle savedState)  {
  super.onCreate(savedState);
  setContentView(R.layout.home);

  usernameEditText = (EditText) findViewById(R.id.usernameEditText);
  passwordEditText = (EditText) findViewById(R.id.passwordEditText);
  loginButton = (Button) findViewById(R.id.loginButton);

  loginButton.setOnClickListener(new View.OnClickListener() {
    public void onClickListener(View view)  {
        // do some validation stuff
        startActivity(new Intent(HomeActivity.this, NextActivity.class));
    }
  });
}
}
</pre>
<p>That&#8217;s it for now with our sample Java-based activity. Now let&#8217;s see how the same Activity can be done using the Scala programming language.</p>
<p>As can bee seen from the source samples above, Java quickly produces very bloated code. When working with the Android framework that bloat is typically driven by type casts, anonymous class definitions, inner class definitions, common code to initialize menu items, etc.</p>
<p>Let&#8217;s translate the <code>HomeActivity</code> into a Scala class. First of all we&#8217;ll consider getting rid of the <tt>findViewById</tt> method calls and the type casts that have to be done for the return types. The sbt Android plugin generates a special singleton object for that purpose: the <tt>TR</tt> (typed resources) object. Within that class it creates typed references of type <tt>TypedResource</tt> for all the UI elements defined in the application&#8217;s XML layout files.</p>
<pre class="brush: scala; title: ; notranslate">
case class TypedResource[T](id: Int)

object TR {
  val usernameEditText = TypedResource[EditText](R.id.usernameEditText)
  val passwordEditText = TypedResource[EditText](R.id.passwordEditText)

  val loginButton = TypedResource[Button](R.id.loginButton)
}

trait TypedViewHolder {
  def view: View
  def findView[T](tr: TypedResource[T]) = view.findViewById(tr.id).asInstanceOf[T]
}

trait TypedView extends View with TypedViewHolder { def view = this }

trait TypedActivityHolder {
  def activity: Activity
  def findView[T](tr: TypedResource[T]) = activity.findViewById(tr.id).asInstanceOf[T]
}

trait TypedActivity extends Activity with TypedActivityHolder { def activity = this }

object TypedResource {
  implicit def view2typed(v: View) = new TypedViewHolder { def view = v }
  implicit def activity2typed(act: Activity) = new TypedActivityHolder { def activity = act }
}
</pre>
<p>The <tt>TR</tt> object defines typed source objects for all XML defined widgets and some traits to be reused in activity classes and views. Once the <tt>TR</tt> class is generated by sbt we can use the <tt>TypedActivity</tt> trait (more about traits in a short moment) to reference our UI widgets in a type-safe way:</p>
<pre class="brush: scala; title: ; notranslate">

class HomeActivity with TypedActivity {

   override def onCreate(savedState: Bundle) {
      super.onCreate(savedState)

      val usernameEditText = findView(TR.usernameEditText)
      val passwordEditText = findView(TR.passwordEditText)
      val loginButton = findView(TR.loginButton)

      // ...
   }
}
</pre>
<p>In case you are wondering where the <tt>findView</tt> method comes from, it is defined by <tt>TypedActivity</tt>. In comparison to the Java implementation we have saved the type casts. Now let us register the button click listener.</p>
<pre class="brush: scala; title: ; notranslate">

class HomeActivity with TypedActivity {

   override def onCreate(savedState: Bundle) {
      super.onCreate(savedState)
      setContentView(R.layout.home)

      val usernameEditText = findView(TR.usernameEditText)
      val passwordEditText = findView(TR.passwordEditText)

      val loginButton = findView(TR.loginButton)
      loginButton.setOnClickListener(new View.OnClickListener() {

       override def onClickListener(View view)  {
           startActivity(new Intent(HomeActivity.this, classOf[NextActivity]))
         }
       })
     }
}
</pre>
<p>OOOOkay &#8211; there is not much difference compared to the Java implementation, that&#8217;s true. But now comes the interesting part. Scala provides certain languages features which allow you to greatly reduce code. And here comes a list with my top-five favorite Scala language features.</p>
<p>Please note that I do not consider myself being a Scala expert &#8211; I would say I have average Scala knowledge. There might be better ways that lead to better results, please feel free to post them in the article&#8217;s comment section!</p>
<h3>Favorite 1: Lazy Vals</h3>
<p>As you can see in the code sample above, we have still the burden to use <tt>findView</tt> in the <tt>onCreate</tt> method. If we wanted other methods to access these references we would have to introduce instance variables, which again increases our LOCs. We can avoid that circumstance by using so-called lazy vals. In fact, Scala provides a keyword for specifying lazy attributes: not surprisingly, <tt>lazy</tt>.</p>
<pre class="brush: scala; title: ; notranslate">
class HomeActivity with TypedActivity {

   lazy val usernameEditText = findView(TR.usernameEditText)
   lazy val passwordEditText = findView(TR.passwordEditText)

   lazy val loginButton = findView(TR.loginButton)

   override def onCreate(savedState: Bundle) {
      super.onCreate(savedState)
      setContentView(R.layout.home)

      loginButton.setOnClickListener(new View.OnClickListener() {

       override def onClickListener(View view)  {
           startActivity(new Intent(HomeActivity.this, classOf[NextActivity]))
         }
       })
     }
}
</pre>
<p>This makes all UI element lookup operations lazy, meaning that the widget reference is looked up only once on first access during runtime. If the lazy instance variable is not accessed, the <tt>findView</tt> method will not be executed, therefore saving lookup operations.</p>
<p>In the example above, we could even further defer the registration of the <tt>OnClickListener</tt>:</p>
<pre class="brush: scala; title: ; notranslate">
class HomeActivity with TypedActivity {

   lazy val usernameEditText = findView(TR.usernameEditText)
   lazy val passwordEditText = findView(TR.passwordEditText)

   lazy val loginButton = {
      val b = findView(TR.loginButton)
      b.setOnClickListener(new View.OnClickListener() {

       override def onClickListener(View view)  {
           startActivity(new Intent(HomeActivity.this, classOf[NextActivity]))
         }
       })

       b
   }

   override def onCreate(savedState: Bundle) {
      super.onCreate(savedState)
      setContentView(R.layout.home)
    }
}
</pre>
<h3>Favorite 2: Implicit type conversions</h3>
<p>Wouldn&#8217;t it be nice to implement the <tt>View.OnClickListener</tt> interface with a Scala function, like that</p>
<pre class="brush: scala; title: ; notranslate">

     loginButton.setOnClickListener((v: View) =&gt; startActivity(new Intent(HomeActivity.this, classOf[NextActivity])))
</pre>
<p>To be honest, in a real world example you would have to enclose the functions body with curly braces (the example uses a single statement in the function body), but at least we got rid of the method interface declaration.</p>
<p>The code above can be left as it is, by introducing an <i>implicit type conversion</i>.</p>
<pre class="brush: scala; title: ; notranslate">

implicit def function2ViewOnClickListener(f: View =&gt; Unit) : View.OnClickListener = {

   new View.OnClickListener() {
     def onClick(view: View) {
       f(view)
     }
   }

}
</pre>
<p>As long as the implicit conversion is in the appropriate scope every function from source scope View to target scope Unit will be automatically converted to an instance of the anonymous class implementing the View.OnClickListener interface. Of course there are bunch of interfaces to write implicit conversions for, in my first Scala Android project I put them all in a trait to reuse them accross activities.</p>
<h3>Favorite 3: Traits</h3>
<p>A Java interface is very abstract. It is as abstract as an interface can be (even the interface contracts are omitted <img src='http://blog.andresteingress.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ). An abstract class is better in a way that it can provide method implementations, but than the problem swaps over to single inheritance as you can&#8217;t use multiple abstract classes as parent classes. </p>
<p>When your classes are defined in a framework context, this gets a real problem because the single inheritance line is most of the time already reserved for framework descending classes, meaning that custom classes extending from framework classes can&#8217;t extend custom classes anymore. That reuse restriction causes by single inheritance strikes me with its full power in my Java-based Android projects.</p>
<p>Let us assume that we need to extend both, class <tt>Activity</tt> and class <tt>ListActivity</tt>. Since the framework and Java&#8217;s single inheritance mechanism forces us to extend both activity classes, there is no way to extend from a common <tt>OptionsMenu</tt> base class that uniformly creates the application options menu. </p>
<p>With Scala we can create a so-called <i>trait</i>. A trait can be imagined as an abstract or concrete class that can be mixed into another class. A Scala class can mix-in several traits, but can only extend from a single descendant class. The Scala guys to to speak of &#8220;mix-in classes&#8221; instead of &#8220;multiple inheritance of classes&#8221; since traits differ in some ways from how multiple inheritance is implemented in other programming languages. </p>
<p>A trait for the <tt>OptionsMenu</tt> could be written as:</p>
<pre class="brush: scala; title: ; notranslate">
trait OptionsMenu extends Activity {

  override def onCreateOptionsMenu(menu: Menu) : Boolean = {
    menu.addSubMenu(&quot;Test&quot;)

    true
  }
}
</pre>
<p>The trait can now be used in all classes that directly or indirectly extend from <tt>Activity</tt> &#8211; and this includes <tt>ListActivity</tt>!</p>
<pre class="brush: scala; title: ; notranslate">
class NextActivity extends ListActivity with OptionsMenu {

  // ...
}
</pre>
<p>Another example would be further shortening the code for our <tt>HomeActivity</tt>by providing a base trait that extends from <tt>TypedActivity</tt> and the newly created <tt>OptionsMenu</tt> trait.</p>
<pre class="brush: scala; title: ; notranslate">
trait Activity with TypedActivity with OptionsMenu {

  lazy val usernameEditText = findView(TR.usernameEditText)
  lazy val passwordEditText = findView(TR.passwordEditText)
  lazy val loginButton = findView(TR.loginButton)

  val contentView: Int

  val init: Unit

  override def onCreate(savedInstanceState: Bundle) {
    setContentView(contentView)

    init
  }
}
</pre>
<p>Wit the base class shown above the <tt>HomeActivity</tt> can be minimized to the following code piece.</p>
<pre class="brush: scala; title: ; notranslate">
class HomeActivity extends Activity {

  val contentView: Int = R.layout.activity_home

  val init = {
    loginButton.setOnClickListener( (v: View) =&gt; startActivity(new Intent(HomeActivity.this, classOf[NextActivity] )))
  }
}
</pre>
<p>If we compare this class with our initial Java class in the first source code example, you&#8217;ll see that with the help of <i>lazy vals</i>, <i>implicit conversions</i> and <i>traits</i> we already reduced the source code to a great extent.</p>
<h3>Favorite 4: Pattern matching and Case Classes</h3>
<p>If you have ever taken a look at Erlang you&#8217;ll have with no doubt a clear picture of how integral pattern matching can be a  very characteristic programming language property. Scala provides various pattern matching mechanisms by providing the <tt>match</tt> and <tt>case</tt> keywords.</p>
<pre class="brush: scala; title: ; notranslate">

override def onCreateDialog(dialogId: Int) : Dialog = {
   dialogIg match {
     case SHOW_ALERT_DIALOG =&gt; // create the dialog instance
     case _ =&gt; throw new IllegalArgumentException(&quot;Dialog &quot; + dialogId + &quot; could not be created!&quot;)
   }
}
</pre>
<p>Pattern matching in Scala is mighty. It does not work for integer values only, it works for strings and various other types [<a href="http://www.scala-lang.org/node/120">5</a>]. A special case of pattern matching can be realized with so-called <i>case classes</i>. </p>
<p>A case class defines an immutable type with a pre-generated <tt>toString</tt>/<tt>hashCode</tt>/<tt>equals</tt> method implementations, a factory <tt>apply</tt> method, and automatic <tt>val</tt> prefixing.</p>
<p>Case classes can be used like good-old records in several corners of the Android framework, e.g. for implementing a view holder.</p>
<pre class="brush: scala; title: ; notranslate">
case class ViewHolder (checkBox: CheckBox, textView: TextView)
</pre>
<h3>Conclusion</h3>
<p>Scala does not aim to be an evolutionary successor of the Java programming language. It is a functional and object-oriented language with its own type system, features and &#8211; hard to grasp for hardcore Java hackers at first sight &#8211; its own language syntax. On the other hand, the Android SDK is a Java-based framework, naturally using Java concepts and patterns found in other Java frameworks. Scala provides neat features to greatly reduce framework clue code allowing to concentrate on application logic and domain classes. </p>
<p>You can find the article&#8217;s source code examples at Github [<a href="https://github.com/andresteingress/scala-android-examples">6</a>].</p>
<p>[0] <a href="http://groovy.codehaus.org/">The Groovy Programming Language &#8211; http://groovy.codehaus.org/</a><br />
[1] <a href="http://www.scala-lang.org/node/1305">Learning Scala &#8211; http://www.scala-lang.org/node/1305</a><br />
[2] <a href="https://github.com/n8han/giter8#readme">Giter8 Templates &#8211; https://github.com/n8han/giter8#readme</a><br />
[3] <a href="https://github.com/harrah/xsbt/wiki">SBT Scala Simple Build Tool &#8211; https://github.com/harrah/xsbt/wiki</a><br />
[4] <a href="https://github.com/jberkel/android-plugin">SBT Android Plugin</a><br />
[5] <a href="http://www.scala-lang.org/node/120">Scala Pattern Matching &#8211; http://www.scala-lang.org/node/120</a><br />
[6] <a href="https://github.com/andresteingress/scala-android-examples">Scala Android Examples &#8211; https://github.com/andresteingress/scala-android-examples</a></p>
<p><a class="FlattrButton" style="display:none;" href="http://blog.andresteingress.com/2011/09/20/programming-android-with-scala/"></a><br />
<noscript><a href="http://flattr.com/thing/404168/Programming-Android-with-Scala" target="_blank"><br />
<img src="http://api.flattr.com/button/flattr-badge-large.png" alt="Flattr this" title="Flattr this" border="0" /></a></noscript></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2011/09/20/programming-android-with-scala/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.689 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-01-29 12:29:36 -->
<!-- Compression = gzip -->
