The Android swissknife

This is a comprehensive list of applications and websites that will make your life much easier when developing Android apps, or at least, my life will be much harder without them. I call it the Android swissknife.

Flat UI Colors: A list of flat colors to use in our apps. Select the format, click the color, and it will be copied to your clipboard.

Android cheat-sheet for Graphic Designers: A big cheatsheet about UI and design related concepts for Android apps. For those like me, who can’t remember the specific size of each icon on each density.

Android Holo Colors: Select the colors, version, controls, and hop! you have a zip file with all the needed drawables and the theme.

Android Asset Studio: Amazing set of assets generators for Android

Parcelabler: Making objects parcellable is boring as hell. With this page, just paste your class code and it will generated a “parcelled” version. Easy peasy.

Android Layout Finder: One of my favorites. Just paste a layout, select the widgets and views and it will automatically generate a findViews method, or an Adapter (even with a ViewHolder). Thanks @EsteveAguilera for sharing it.

Android Layout/Style XML Converter: From layout to style and back.

Jsonschema2Pojo: this is a great one. It generates a pojo from a Json file. You can choose if you want to use Gson or Jackson annotations (and your’ll learn a lot seeing how it does some things).

Roman Nurik’s View Server: This library allows us to use the Hierarchy Viewer from a device apk even if the device is not rooted.

Am I missing something? share in the comments and I’ll update the list.

Update – July 24th

Some other niceties:

DPI calculator for Android: quick DPIs conversion tool. Also available as a Chrome extension.

Gradle, please: a gradle-format dependencies search tool. Useful for the usual suspects.

Android drawable generator: this web generates all the xml stuff for buttons with a lot of settings to play with. It’s a pitty it doesn’t make multiple states.

APK Downloader: this one is supposed to let you download apps from Google Play that are not allowed in your country, but I never managed to make it work as they had a lot of limitations on daily downloads. According to their latest comments, now it works much better, I didn’t tested it lately.

Android Design Tips: another design cheatsheet with a dpi conversion tool

The Android Arsenal: a library and views repository classified by categories.

WSDL2Code: in the last times I had to consume data from SOAP web services. This website will generate pure Android code to access these services from the WSDL specification.Generate, paste and use

Looking for the perfect Android architecture I: Despicable Content Providers

I’ve been looking for the best architecture for an Android app. I’m not looking for the best speed or performance, but they should be acceptable. It should be quite Android-compliant and above everything, easy to replicate. My final target is to have a foundation for new projects (pro and personal ones) and be able to say “this is the way I work”. I have a lot of ideas in my mind, but without sharing or discussing them, they are worthless. So, let’s share them, discuss them and let´s improve together.

I’ll start talking about Content Providers (CP). I’m assuming that you know what they are and how they work, and also about SQLite and all the related stuff. If you don’t know about these topics, check out the tutorial from our friend Vogella at  http://www.vogella.com/articles/AndroidSQLite/article.html.

Check section 9.4 of that tutorial. You’ll see the structure of a CP. Basically, four functions, one per operation (query, insert, delete and update) with an structure like this:

I hate the switch statement. I think is ugly and unmaintainable. Also, the example is using only two URLs, but an app with 20 entities will easily become a God class.

My proposal is an structure I call the DespicableContentProvider. Why? because it has MinionContentProviders (I know, don’t use cute names, but I couldn’t resist and the analogy helps a lot to understand it). If you don’t know anything about Despicable and Minions, chech this: http://www.youtube.com/watch?v=jzpOLs1t8Hg

You can check the code both for the Despicable base class and the Minion base class at https://gist.github.com/sergiandreplace/8165986. Free, cute and distributables.

Before start working with them, let’s see some rules I follow when working with CP:

  • The CP works like a web api. Authority is the host name.
  • Every url is an endpoint for an entity.
  • Urls are like content://<authority>/<entity>[/#id].
  • Urls ending with an id are asking for an specific element and are type Item. Other ones are Dir type (for coherence with MIME types)
  • Mime type will be vnd.android.cursor.{dir|item}/vnd.{AUTHORITY}.{ENTITY}. My CP are usually private for the app, so I don’t care too much about MIME types.
  • CP consumers know NOTHING about the database. In fact,  the only one accessing the database is the CP. Even for big projects I use different contracts. One for the database and another one for the CP consumers.
  • When performing an Item request (one with an id in the url) all the filtering parameters are ignored (I’m already asking for only one, why filter?)

Basically, every Minion knows how to perform an Insert, Update, Delete or Query against an entity for an Item or a Dir (not both). Here is an example:

Basically I’ve implemented three things, first getBasePath, that returns the specific url path to the entity, getType function, that returns the name to be used to indentify this entity as MIME type, and the four operations for this specific entity. The main difference with the CRUD opeartions are that you receive the db object via parameter and you don’t need to notify the change as the Despicable will do it.

An Item type is very similar:

The main differences are:

  1. Class name is singular (it’s my way…)
  2. Return path now includes /# as per UriMatcher syntax
  3. On each one of the CRUD operations we ignore the parameters received for filtering and we just query by _id
  4. In this case, I’ve decided you can’t insert an Item specifying an id in the path. This is just an example, and real behaviour will be domain-specific.

Easy peasy, isn’t? So we only need to create one per entity.

Once we have the Minions, let’s work on the Despicable. Check this:

GetAuthority method just returns the name of the authority. It’s used by the parent class to retrieve it on runtime. The method getDb should return a database to work with. The recruitMinions method is responsible to add an instance of each Minion to the collection of the Despicable.

That’s it. Quite cool, isn’t it. At least is tidier and easier to maintain.

Now, our CP implements the  four operations for each entity, and also a bulk insert that just executes the insert in a loop inside a transaction.

And for the same price, a couple of helping functions I usually include in the CP.:

They are very useful in the contract and the CursorHelpers that will be discussed in next entry.

I’d love to receive comments about this and see other points of view and ways of working with CP. And also, any suggestion or improvement will be very welcome.

Continuous testing on Scala SBT

A nice trick I’ve learned from Ignasi (@ignasi35) one of the BCN Dev Scala Meetup group (http://www.meetup.com/Scala-Developers-Barcelona/)

This is a shortcut to execute the tests while editing the exercises for the Functional Programming course on Coursera.

You can open SBT in your project folder and run the command test. This will compile and run the unit tests defined in the project.

If you run ~test it will run the tests and then it will keep waiting until a file is modified. Once you modify a file, tests will be executed again, and it will keep waiting again, and so on…

Little nice trick :)

CursorAdapter and pivot queries

I like Content Providers, but sometimes is difficult to use Loaders and CursorAdapter when you have to make “pivot” queries.

Let’s see an example of the problem and a solution that can help to solve a lot of cases.

Imagine we have a list of shops, and you want to show the list of cities in this table. Also, you want to show the postal codes with address in each city.

An initial approach would be to have a ContentProvider that returns a list of cities, and for each bindView execute a query that returns the associated postal codes. But this is extremely slow.

A nice solution I’ve found is to use the aggregate function group_concat from SQLite.

For example:

That will return a list like:

Voila! now we can process the second field  the bindView and show it accordingly. I usually create a CursorHelper for each content provider cursor that makes the task to transfor object to cursor and cursor to object. In this case, we can have a City object with a String for name and an Array or Collection for the post codes and just use the String.split to transform it when reading the row.

Quick and dirty!


Settings fonts in Android

Setting multiple fonts in Android is quite a pain in the ass. Until Android 4.2 there is no way to specify different font families in a Layout, and doing it from code makes us setup the font control by control, and we have to perform findViewById for all controls even when not needed, resulting in a degradation of performance.

Dealing with this, I’ve tried to reimplement the inflation process, but at the end this resulted in slower apps, and some components like action bar gave me some problems. (This was explained in a previous post, but some #$%@ hacker decided that his/her/its stupid message was more important than my post).
I’ve came to a faster solution, not ideal, but faster to implement and use.
Basically I’ve created a wrapper for all controls that implemented text (TextView, EditText, etc) that used the attribute tag to setup the font.

Something like this:

And the code for the FancyTextView:

Then, we only need to copy the appropiate fonts to assets folder.

Pending improvements:

  • Detect if the font is not available and failsafe to default font
  • Create a hashmap to store the Typeface objects to avoid multiple instantiation (that could make a difference on big layouts)
  • Change filenames by alias using a string array as resource, so we can map them and change at once if required.

Introducing RaREST, a brand new Android Rest Client library.

I’ve published a preliminary version of my Rest library RaREST (v.0.9). There are still a couple of things missing (specially logging configuration) and much more testing won’t hurt anyone, but if any of you wants to try it, feel free to download and give feedback.

RaREST is based on a single configuration file that contains all the rest services info needed to invoke them, so it makes the amount of code needed very short.

It supports using services as template for other services, preprocessing and postprocessing of the REST call and many other functionalities.

There is still lack for a lot of improvement (anybody said mulipart?) but is a good starting point.

It’s licensed under Apache 2.0 and you cand find source, downloadables and documentation on http://code.google.com/p/rarest/

Enjoy it!