The importance of being plural

Or how you can use quantity strings in Android

Through the years I often came into the request to fixing what seems a recurring issue:

<<The app shows “You have 1 unread messages” or worse “You have 0 unread messages” and we need to fix that in oder to show the correct message.>>

I’m pretty sure that everyone, at least once in their programmer life, asked ownself what would the proper way to handle this in code be.

To go back to the above example, based on the number of messages you could have: “no messages”, “1 message”, “2 messages” and so on.

Let’s see how to do this the right way in an Android app.

You can do it obviously by hand writing your code or by using what’s called “Quantity strings” or “plurals”.

Basically, what we can do in Android is to define different string resources based on the quantity (in particular, android supports zero,one, two, few, many, and other).

Plurals can be defined as android xml resources by using the <plurals> element as follows

Android “plurals” XML element

and be retrieved via code by calling the getQuantityString method, passing in the quantity (you will need to pass the quantity twice if your string includes string formatting with a number).

Let us now see a practical example based on the problem shown at the beginning of the post.

We will define plurals usually in our strings.xml, or if you prefer inside a dedicated plurals.xml file, this way:

<plurals name="unread_messages">
<item quantity="zero">You have no messages to read.</item>
<item quantity="one">You have one unread message!</item>
<item quantity="other">You have %d unread messages!</item>

Once we have plurals defined in xml we can easily use it in our code

val count = getUnreadMessages()
val text = resources.getQuantityString(R.plurals.unread_messages, count, count)

and retrieve the proper string for the actual message count.

That’s it.