mdevcon 2014

J’ai eu la chance de participer (en tant que speaker mais aussi en tant qu’auditeur) à la mdevcon 2014, les 7 et 8 mars derniers à Amsterdam. Mon compte rendu est disponible sur le blog octo.

Ainsi que les slides de ma présentation (en anglais) :

Share

Android Lint on SonarQube

SonarQube

For those who know SonarQube (formerly named Sonar), you can go to the next part.

For the others, SonarQube is an open source tool that manage code quality. This tool is well known by java/jee developers in Western Europe (mainly France and Swiss), but it seems completely unknown across the Atlantic. It is a pity because it is a very good tool.

As you can see in the following picture, this is a web-based dashboard describing the code quality of your application.

sonarqube

It is based on Findbugs, PMD, Checkstyle and Sonar self rules to analyze the code and display metrics (and details : you can see exactly where you got problems in your code). You also have tests indicators (number of tests, execution time, code coverage). It gives you general metrics about your code (number of lines, number of comments, duplicated code, complexity, …).

But the most interesting is that everything is recorded all along the project life, so you can see the evolution and make sure you get better :

Historical

Like I said before, this is a tool we used to since several years on java project. It works perfectly well with maven and gradle.
But what about Android and its quality analysis tool : Lint ?

Android Sonar Plugin

Android Sonar Plugin

A bit of history…

Eight months ago, I decided to provide a Sonar plugin to add the Android Lint violation checks in Sonar. With Stéphane Nicolas, we created the first version on github (deprecated). We had some help from Florian Roncari et Thomas Bores, and after a conf call with Freddy Mallet (from Sonarsource), the plugin has been integrated to the Sonar Community Plugins. More recently, Julien Henry (from SonarSource) made a really good job of refactoring on the plugin to match the Sonar standards. Thanks to him !

How-to

Pre-requisites : You need SonarQube, maven or gradle. I won’t give any details on installation of theses tools, they all have good documentations.

Installation : To install the plugin, go to your SonarQube update center (http://sonarhost:sonarport/updatecenter/available), find the « Android » plugin and install it OR git clone https://github.com/SonarCommunity/sonar-android.git, mvn clean install, retrieve the jar in the target folder and put it in /sonarpath/extensions/plugins. Restart sonar and that’s it ! Easy :) !

Thus, you’ll have all the Android Lint rules (158 exactly) available in your SonarQube instance :

sample report

Usage : In your maven or gradle build, you need to specify some information in order to communicate with the sonar server.

For maven, I suggest to put the following configuration in your settings.xml (generally in $MAVEN_HOME/conf/settings.xml or $HOME/.m2/settings.xml) :

<settings>
    <profiles>
        <profile>
            <id>sonar</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <!-- Example for MySQL-->
                <sonar.jdbc.url>jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8</sonar.jdbc.url>
                <sonar.jdbc.username>sonar</sonar.jdbc.username>
                <sonar.jdbc.password>sonar</sonar.jdbc.password>
 
                <!-- Optional URL to server. Default value is http://localhost:9000 -->
                <sonar.host.url>http://myserver:9000</sonar.host.url>
            </properties>
        </profile>
     </profiles>
</settings>

Then you can execute maven to analyse your application. Specify the profile Android Lint to use the Lint ruleset :

mvn sonar:sonar -Dsonar.profile="Android Lint"

For gradle, there is a plugin to execute sonar : sonar-runner. Like maven, it needs the same information. In your build.gradle, add the following :

apply plugin: 'sonar-runner'
 
sonarRunner {
    sonarProperties {
        property "sonar.host.url", "http://myserver:9000"
        property "sonar.jdbc.url", "jdbc:mysql://localhost:3306/sonar?useUnicode=true&amp;characterEncoding=utf8"
        property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver"
        property "sonar.jdbc.username", "sonar"
        property "sonar.jdbc.password", "sonar"
    }
}

You also need to specify some project information, either in a sonar-project.properties file or directly in the build.gradle :

# required metadata
sonar.projectKey=pjk
sonar.projectName=pjn
sonar.projectVersion=1.0
 
# path to source directories (required)
sonar.sources=src/main/java
 
# The value of the property must be the key of the language.
sonar.language=java
 
# Encoding of the source code
sonar.sourceEncoding=UTF-8
 
# Additional parameters
sonar.profile=Android Lint

Finally, run gradle to build the sonar dashboard :

gradle sonarRunner

Result : Here you can see a live report generated with a sample project on nemo (a sonar instance with many open sources projects) :
sample report

Conclusion

SonarQube is a really great tool that go with you all along the project. It ensures to keep a good level of quality in your code and thus to provide a more robust app. Before you could get java problems (probable bugs, coding conventions problems, …), now you also can get android problems ! At OCTO, on nearly all our projects, we add a nightly build on our continuous integration server (jenkins) that run the sonar check. And all the morning, during the standup meeting, we have a look at the report to check if our app is healthy. Give it a try !

Share

Droidcon Paris 2013

droidcon paris Hier et aujourd’hui avait lieu la première Droidcon Paris… et ce fut à mon avis une réussite, un bel événement, très bien organisé par l’équipe du PAUG. Le format était à peu près le même que les Droidcon Londres auxquelles j’avais assisté en 2010, 2011, à savoir une demi-journée de barcamp et une journée et demi de conférences « magistrales ». Pour ma part, j’ai présenté une session avec Stéphane Nicolas sur la qualité des développements Android, où comment exploiter les outils du monde Java (Tests, courverture, analyse du code) pour améliorer la robustesse des applis Android, conf que nous avions déjà jouée à Devox à Paris cette année (et que nous rejouerons probablement en anglais à la droidcon de Londres). Ci-dessous les slides de la conférence…

Share

Google I/O

Google-IO-2013 Les 15 et 16 mai dernier, j’ai eu la chance d’aller à la conférence Google I/O à San Fransisco. J’étais invité à présenter Android Holo Colors sur un stand des Sandbox, en parallèle des différentes sessions techniques animées par les Googlers.

Google I/O, c’est la grand-messe annuelle pour tous les développeurs qui souhaitent s’informer sur les produits et technologies Google (Android, Chrome, Google+, Cloud Platform, Maps, …). Cette année encore, c’est près de 6000 développeurs qui se sont retrouvés au Moscone Center de San Fransisco et j’y étais !

Je publierai prochainement un article sur le blog d’OCTO qui m’a permit de me rendre à cette incroyable conférence.

3ème conférence au compteur cette année et ce n’est pas fini puisque je présenterai une session à la DroidCon Paris le 18 juin prochain…


IMAG0369

IMAG0398

Share

Devoxx France

Demain Devoxx France, saison 2. J’aurai le plaisir d’y présenter une session (Tools in action) avec Stéphane Nicolas sur le sujet de la qualité des développements Android, où comment exploiter les outils disponible en java (tests, analyse de code, couverture, …) sur Android.

En avant-première les slides :

Share

Start an android project in less than 5 minutes

The Maven way

Akquinet (a deutsche consulting company) provides since 2 years some maven archetypes to create minimal Android project configuration.

To start with this solution, you need … Maven of course! Once it is installed, you simply need to type this command :

mvn archetype:generate \
  -DarchetypeArtifactId=android-release \
  -DarchetypeGroupId=de.akquinet.android.archetypes \
  -DarchetypeVersion=1.0.8 \
  -DgroupId=com.vdl.archetype \
  -DartifactId=testarchetype \
  -Dpackage=com.vdl.archetype

You should get the famous BUILD SUCCESS and a new projet tree containing the parent (pom), the project and the test project.

A mvn clean install in the project root folder should create the apk, deploy it to a running emulator or device and launch tests. It works for me without tuning anything in the pom, that’s a very good point!

Then, you want to code, so you import the maven project in your IDE, let’s say eclipse (you’ll need the m2eclipse plugin). And if you use the « m2e development support (optionnal)« , it will suggest you all connectors you need to install to manage your android maven project in eclipse:

Here again, projects are imported in eclipse without problems (I only had to remove src/test/java from the source build path). Then, I can launch the application, run the tests… Fine! I remember when i had to fight with eclipse and plugins to get everything working.

Let’s see more precisely what does the project contains: pom.xml are quite complete, with the release configuration, the signing configuration, the proguard configuration, … indeed, the basis of an android maven project.

But, there is a but, there are no dependencies provided (except the akquinet log library)! Actually, if you want to use roboguice or spring android, or robolectric… you’ll need to add dependencies by yourself.

We could imagine creating our own archetype with all dependencies we like, it is very easy. But let’s have a look at two very recent online services that create the project for you.

Android Bootstrap

As its name suggests, this service (http://www.androidbootstrap.com/) helps you to bootstrap your Android project. The website offers a generator, currently in beta, to personalize the project name and package. Or you can download the project on github. Bootstrap is very young (beginning of september, 2012).

The generated project is also a maven project with the application and the test project. Let’s run the eternal clean install :

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile) on project com-vdl-bootstrap: Compilation failure
[ERROR] /Users/jva/Developpement/blog/android-bootstrap/app/target/unpack/apklibs/com.github.kevinsawicki_wishlist_apklib_0.3/src/com/github/kevinsawicki/wishlist/TypeAdapter.java:[212,15] type parameters of <V>V cannot be determined; no unique maximal instance exists for type variable V with upper bounds V,android.view.View

So ugly! It seems that the wishlist dependency has a problem… If you have a look at the pom.xml, you actually see that there are many dependencies (roboguice, actionbar sherlock, gson, robotium, … and this famous wishlist). It’s nice to supply dependencies but KISS, keep it simply stupid! Try to limit to the main dependencies…

Actually, I won’t go further with this one, since i want to start in less than 5 minutes and don’t want to debug exotic dependencies used in the project…

Android KickstartR

kickstartr

Contrary to Bootstrap, KickstartR (http://androidkickstartr.com/) permits to choose dependencies you want to use. You can select Android annotations (and soon Roboguice), ActionBar Sherlock, Spring Android, ACRA, and others will be added. It also permits to create a maven project, or a non-maven project (if you don’t like maven maybe ?). KickstartR is even younger than Bootstrap (end of september, 2012).

Like before, i execute the clean install command and…

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Nice! I love it when a plan comes together! (Sorry for the younger of you who wont understand the reference)

If you look at the project, you will see that there is no test project, no parent project, only a single application project, with a very simple pom.xml. KISS is respected, perhaps too much. It would be great to have a complete project, with a test module… Whatever, the project build.

Now, let’s import it in eclipse. In order to get the project working with ActionBar Sherlock, you’ll need to import another project (« library »), available in the downloaded package. If like me, the style Theme.Sherlock.Light is not found, verify in android properties (right click / properties / android) that the « ../library » project is used as a library for your project.

Finally, after several clean, refresh, update maven config, … I could compile both projects but I could not run the application. I had some dex problems and even a java heap space in eclipse (maybe a problem with android annotations processor : please provide roboguice) !

Second chance, let’s try in IntelliJ… I import the two projects (library and KickstartR), and it simply works. Damn f*ck*ng eclipse!

Conclusion


Archetypes Bootstrap KickstartR
Integration with Maven + -
Build failed
+
Integration with Eclipse + -
KO
-
KO
Integration with IntelliJ + -
KO
+
Configurable (on website) - + ++
Choices (for libraries) -
No library
-
Imposed libraries
+
Tests + -
Build failed
-
No test

As for now, Bootstrap doesn’t work for me. And I’m not the only one (see this issue). But let’s imagine it works, my conclusion would be:

Actually, I’m not able to choose the best of three:

  • Archetypes provide a complete project with tests and it just works out of the box. But it doesn’t provide any additional library.
  • Bootstrap (when it will work), provides also complete project but with no choice in libraries, all are included. So now, instead of loosing time to add libraries, i will loose time to remove those I don’t use.
  • KickstartR provides the most clever solution: Ability to pick up libraries and only those I need. But, the project currently does not provide a test project.

Finally, I think i will create my archetype with the libraries I used to include: roboguice, spring-android, robospice, apache commons, robolectric, actionbar sherlock. Or maybe I’ll wait for Android KickstartR to be more mature (test project, more libraries) since it is a very good idea to be able to pick up in the libraries.

Or, why not create my own web site ?! ;)

Share

Android-Holo-Colors

Custom components look&feel

The need is born when i was coding an application for a client (the app is not yet available on store, so i won’t tell who is it). We needed to create custom edittext and spinner with different colors :

Edittext & Spinner colored

The same question appears thousand times on stackoverflow (custom checkbox, custom edittext, custom progressbar, custom radio, and so on…).

==> So, how to achieve that ?

Background drawable

The first, simple and naive solution is to replace background drawable of the component. For example, on an EditText:

<EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_edittext" />

Where res/drawable/selector_edittext.xml should be something like (inspired from Android source) :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/textfield_default_holo_light" />
    <item android:state_enabled="true" android:state_focused="true" android:drawable="@drawable/textfield_activated_holo_light" />
    <iten android:state_enabled="true" android:state_activated="true" android:drawable="@drawable/textfield_activated_holo_light" />
    <item android:state_enabled="true" android:drawable="@drawable/textfield_default_holo_light" />
</selector>

And drawables are png or ninepatch (.9.png) of your choice. In my case, we wanted something with Holo aspect but with different colors. For example :
Holo version (see Android source tree): textfield_activated_holo.9.png
Our versions :

Some graphical skills are needed (Gimp, Photoshop, whatever…). If you have the chance to have an ui designer in your team, you are a lucky guy. Otherwise, you’ll need to do it yourself. That’s not so complicated in my example (edittext) but have a look at checkboxes

All that done (« fiou ! »), you can set your background on all your edittext. Not a beautiful solution, isn’t it ?! Hopefully, Android provides styles and themes to simplify this job.

Styles and Themes

Android provides a very clean solution to avoid code duplication and to simplify theming of your application. It’s closed to CSS on the web world : styles and themes. I won’t explain all the stuff, the documentation is clear. Let’s theming our previous edittext component.

In order to specify the android:background on all edittexts in the application, we’ll define a style (values/styles.xml) :

  <style name="EditTextStyle" parent="android:Widget.EditText">
     <item name="android:background">@drawable/edit_text_holo_dark</item>
  </style>

We can also define the style for post-android4 (values-v11/styles.xml) and it’s important in our case since we wanted to extend Holo style:

  <style name="EditTextStyle" parent="android:Widget.Holo.EditText"> <!-- or Widget.Holo.Light.EditText -->
     <item name="android:background">@drawable/edit_text_holo_dark</item>
  </style>

This style inherit from a parent Android style (to get all others attributes) and override the famous background attribute. At this point, we could use the style in our layout with style="@style/EditTextStyle. But we should duplicate the code on all our edittext (that’s what we wanted to avoid!).

So we need to create a theme (values/themes.xml). A theme is a set of styles that can be used for the complete application or a single activity :

<style name="CustomTheme" parent="android:Theme">
    <item name="android:editTextStyle">@style/EditTextStyle</item>
    <!-- ... many others styles ... -->
</style>

Same remark as for style, we define a values-v11/themes.xml, to extend Holo Theme:

<style name="CustomTheme" parent="android:Theme.Holo"><!-- or Theme.Holo.Light -->
    <item name="android:editTextStyle">@style/EditTextStyle</item>
    <!-- ... many others styles ... -->
</style>

We override the editTextStyle attribute with the previously declared style. The attribute editTextStyle is defined in Android attributes file (attrs.xml, see also R.attr for the complete list of attributes you can extend). That’s the magic part of themes and styles, because Android will be able to apply the defined theme to all edittext.

To apply our theme to application or activity, we can use the following code :

<application android:theme="@style/CustomTheme">
<activity android:theme="@style/CustomTheme">

If you read french, i suggest a good article from Cyril Mottier on the subject.

All that done (« fiou again ! »), you have a drawable.xml, several pictures (depending on the components, it can be up to ten) for several densities (imagine for mdpi, hdpi and xhdpi, you multiply by 3), styles.xml, themes.xml (for both ICS and older Android versions). A lot of work !

Android Holo Colors Generator

Imagine if all the previous stuff (styles, themes, png) was generated for you. That’s the idea I had when I created Android Holo Colors Generator.

  1. You choose a Theme name, to be used in themes.xml and AndroidManifest.xml
  2. You pick the color of your application:
  3. You choose the parent Theme:
  4. You choose the components you need:
  5. And you download the package with everything you need, ready-to-use res folder containing xmls and pngs:
  6. Finally, you include all the files in your project and that’s it ! A few seconds rather than long hours to create pictures manually.

Conclusion

Android provides an interesting mechanism to style your application but it can be tedious to do it by yourself. Hopefully, there is now a tool that do the job for you. I hope you’ll appreciate. Do not hesitate to give feedbacks and send issues on the github project.

Share