Custom attributes for custom Android Component

Let’s suppose you need to create a custom view or a custom fragment.

These components could be inflated by xml or instancited programmatically.
In case they are inflated, you could have the need to pass custom attributes to define a initial state of your component.

For example : you wanted to create a custom Fragment (call it MyFragment) that manipulates a string and an integer.

#1. declare your attributes in res/attrs.xml as follow:

As you can see, each attribute requires a format, which can be one of the followings :


#2. In you layout (where you declare your fragment), add your custom attributes to your component:

There, you need to be carefull to add a new namespace :

The value of the namespace (‘options’) could be anything you want.

#3. Extract these attributes from your fragment :
If you check the Fragment API reference, the only callback where you could deal with custom attributes is the onInflate() method

As described, this callback should only be responsible for extracting the attributes :

 » all you should do here is parse the attributes and save them away. »

Let’s suppose I have a Business Object called Company

All I have to do is parsing the attributes and creating my Company BO within onInflate() method as follow:

 

#4. Testing
I should have started by writing in TDD but I wanted to describe the attributes definition and parsing first. The following Unit Tests will use Junit4, Mockito as well as Robolectric (tested with 2.2).

The onInflate() method needs an activity instance to properly fetch the attributes. So we will create an Activity instance first.

Our Unit Test will consist in testing that the Company BO is properly created when onInflate() method is called.

To do so, we will populate a list of attributes that we will pass as parameter to onInflate by using RoboAttributeSet;


# How about custom views ?

The previous steps remain identical (attrs.xml, extraction) for views apart from the method where the parsing occurs. Indeed, in Views, you can parse the custom attributes from the constructor itself .

# Conclusion

Creating custom components often requires custom attributes to precisely initiate that component. What is really interesting here is the ability to properly test the parsing of the attributes using RoboAttributeSet component.

Saving Fragment State on Configuration Change

prerequisite
Fragment Component
Fragment lifecycle

What I needed :
As you know (if not, please read the prerequisite first), the Fragment lifecycle is highly tied to the activity lifecycle. That said, my need was simply to retain some state of my Fragment and restore it later on after a recreation. A typical scenario is when user rotates screen.
To do so, one needs to override onSaveInstanceState method of the Fragment and save any value into a Bundle, as follow :

The saved Bundle could be retrieved during either onCreate(), onCreateView(), onViewCreated(), onActivityCreated() or onViewStateRestored() callbacks.

What was the problem ?
In my case, the saved bundle was always null in any of the callbacks listed above, although I properly called onSaveInstanceState().

How to solve it ?
Firstly, my Activity’s layout looked like this :

What was missing here is an android:id field within my fragment so Android could recognize the stored Fragment! We simply correct the layout as follow :

As described in the documentation,

Each fragment requires a unique identifier that the system can use to restore the fragment if the activity is restarted (and which you can use to capture the fragment to perform transactions, such as remove it). There are three ways to provide an ID for a fragment:
Supply the android:id attribute with a unique ID.
Supply the android:tag attribute with a unique string.
If you provide neither of the previous two, the system uses the ID of the container view.

Conclusion
In a word, always feed your fragment with an identifier !

What are you doing Google ? #3

This is the third post of a looooong list regarding what I do not agree with the Android source code.
I have the chance to create Android applications, so I regularly read codes, good ones as well as bad ones…

What is my goal of doing so ?
I give myself the freedom to criticize what Google do because, as a developer, we have to improve days after days! Improving means not only practicing, but also
exploring and studying quality open source projects. So either we have to study the right stuff, or we have to highlight what is wrong!
Btw, don’t misunderstand me, I like Google projects !

Naming consistency
Let’s talk in this post about naming consistency. To do so, we will take the MotionEvent class from the android project.
As stated in the documentation, « [MotionEvent is] used to report movement (mouse, pen, finger, trackball) events »
I am currently writing another post which will deeply describe the android touch mechanism (some teasing now 🙂 but here is the big picture :
A MotionEvent holds an action (down, up, move…). It also holds a set of axis values which represent individual fingers position(in multi touch environment).
Each finger in the set has an unique id, called pointerId. However, each finger in that set has also an index that could vary within 2 MotionEvents.

So as you can second guess, the MotionEvent object exposes methods to get the pointerId (unique value) from a varying pointerIndex.
This method is the following : public final int getPointerId (int pointerIndex)

Here, the method is quiet clean and explicite : it requires a pointerIndex as a parameter and returns the pointerId. So your sense of developer will naturaly guide you to look
for a method called getPointerIndex() from the MotionEvent object, so you could feed the previous getPointerId(int pointerIndex) method.

Guess what? No such method!
At least, no such method having this name. Yeah, why being simple and consistent when we can complexify things?
Just dig a bit and you will find a method called public final int getActionIndex ()
The documentation says : « [getActionIndex ()] returns the associated pointer index. » Well, this is exactly what we are looking for but why on earth
the name of the method (actionIndex) is unconsistent with the value returned (pointerIndex) as well as from the documentation ? This is all the more frustrating as the parameter of the previous method needs this value named differently.

So, the code we need is the following :
int pointerIndex = event.getActionIndex();
int pointerId = event.getPointerId(pointerIndex) ;

A good code is a code which has lots of specificities. Readability, naming, consistency.

As much as possible, be rigorous with yourself and don’t neglect these simple little naming consistencies.

What do you think ?

What are you doing Android ? #2

This is a second post of a long comming list, I think… Check my previous one.

Clean coding is, from my point of view, the ultimate goal for a developper. A goal that could take a life long experience. In that journey, I, sometimes, don’t undestand some design choices made by the Android Team regarding their SDK (AOSP & play-services…) that goes against that goal… I have plenty question in my mind while using the SDK, from architecture choices to naming…

Let’s take a simple example regarding the naming convention:

Check this TileOverlayOptions class as an example : 

It has various getters such as getZIndex() or getTileProvider(). However, its related setters are not setZIndex() nor setTileProvider() as expected, but defined as zIndex(float zIndex) and tileProvider(TileProvider tileProvider).

Google is so powerfull that it allows itself to break the naming convention of getters/setters.
These little changes could sound derisory but why breaking standart industry convention ? Is there any meaningfull reason for that ?
Indeed, in standard java, methods should be verbs that describe its action, as described in the documentation :

Although a method name can be any legal identifier, code conventions restrict method names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second and following words should be capitalized.

Here, zIndex() and tileProvider() are nouns that does not reflect at a glance what they are supposed to do. Of course we can deduce it, but it requires some -epsilon- extra effort than facing the standard naming rules.

As a developper, being effective to reach our goal goes through these simple little standard steps. Don’t neglect them.

What do you think ?

What are you doing Android ?

I, sometimes, don’t undestand some design choices made by the Android Team regarding their SDK (AOSP & play-services…)… I have plenty question in my mind while using the SDK…

But let’s take a simple example.

I was interested in the Maps v2 SDK and especially the ability to add another TileOverlay while benefiting from the maps core (gesture, rendering & so…).
So I looked into the documentation and found that the GoogleMap object has the addTileOverlay() methods that returns a TileOverlay.

This is exactly what I need. Perfect.

Then, I wanted to remove this overlay. So I looked for the equivalent method, expecting something like removeOverlay(TileOverlay previouslyAddedOverlay) from the GoogleMap object.. But no such thing…
By digging a bit more, one can find the remove() method from the TileOverlay object itself.

Wait. What is that ??

The GoogleMap object has the responsability to add an Overlay but it does not have the one to remove it ? Instead, the added Overlay can remove itself ?
This is, from my point of view, a serious responsability issue. Indeed, if we imagine the underlying implementation, this means that the Overlay has to be highly coupled with its parent so it could ask the latter to remove itself. I think this coupling is just some waste and should have been avoided.

If we try to develop a coherent Object with well defined responsability, we would expect that if Foo could add Bar, Foo should also be responsable for removing Bar…

What do you think ?

Junit4 : testing Exception

Junit 4.7 introduces the ExpectedException rule that eases Exception testing.

# the ‘yeah, kind of…’ way
I love Square’s projects. They are pushing great libs, especially on Android. They push a high level of quality on their code (unit testing, decoupling, readability & so…).

However, I was kind of surprised when I looked into the Phrase project, a single Class project that processes Android String formatting. Awesome project by the way.
The code is quite clean and the test cases seem well relevant, but testing Exception is like :

Ok. it does the job, but the readability could clearly be improved as there are some uncessary extra code here. Adding try/catch blocks into Unit tests is simply not the way to do AMHA. These tests could be enhanced 🙂

# the partial way
You can use the expected parameter within the @Test annotation to specify the expected Throwable. The code is clearly more readable than previously:

@Test(expected = IllegalArgumentException.class)
  public void loneCurlyBraceIsAMistake() {
      from("hi { {age}.");
  }

However, this way has its limit, this is why it is ‘partial’. Consider this test :

In this precise test case, you don’t know if the Constructor throws the Exception or the following method. You could (and should) of course split the test but let’s see some better way.

# a better way
As briefly evoked in the introduction, Junit 4.7 introduces the ExpectedException rule. The power of this rule lies 1. in covering the previously explained limitation, 2. in gaining in readability and 3. in the ability to not only handle the Exception type, but also the Exception message.
Consider the Square/Phrase test updated with ExpectedException :

As you can see, the test is clearly more consize and more readable. You only need to declare the ExpectedException rule in your test class as public. That’s it 🙂

I have submited a pull request to Square/Phrase project by correcting all the Unit Tests dealing with Exceptions so the quality and readability of the code will hopefully benefit to the community.

To sum up ‘Testing Exception’ :
– avoid try/catch blocks within your unit tests
– push readability as much as possible
– use ExpectedException rule to test the Throwable and the associated message

Let me code, let me create !

I am a mobile developer. Developping software is an art through which you express your creativity.
But before creating anything, an unecessary amount of time is often wasted to setup, to administrate and to manage environment (development, integration, production & so…). 

Let me describe you the big picture:
Once uppon a time, when a was young and uncarefull about neither time passing nor producing value, I would have done a thousand things before even coding a single line of code to fulfill my idea.

  1.  I would have started by installing a Linux distribution (ubuntu to name one) onto an old dusty desktop machine laying into a locker.
  2. I would then have installed all necessary software to develop into the targeted plateform (android, maven & so.)
  3. I would then have installed a Source Version Control software, such as GIT, to access and store my ‘precious’ code. This would also have implied configuring ssh server and managing allowed/denied account to commit.
  4. Then, I would (or wouldn’t) have installed and configured a continous integration system, such as jenkins.
  5. To access my code from everywhere, I would have of course setup all the required network routing (configuring iptables, configuring some virtual hosts to route subdomain names, one for svc, the other for jenkins). To do so, I would necessarely have configured some domain name pointing to my self hosted desktop computer.
  6. Exposing my desktop server to the world, I would have configured some banning policy to block brut force attacks (fail2ban is your friend)
  7. And more !

This is all fun and full of learning, but let’s remind my primary goal: Expressing my creativity through coding.

  • Have I done something close to that goal ? Not at all.
  • Am I a sysadmin ? Certainly not.
  • Am I looking as a sysadmin so far ? Kind of…
  • Am I wasting my time doing so ? Regarding my primary goal, definitely.


Most of the time, your enthutiasm stops there in a subtile manner. Indeed, you are so proud and exshauted of having setup all the environment that you convince yourself that, from now one, you can start developping anytime (converting your idea into something concrete). So you take some rest and know that you could start coding in a few days, anytime. Your primary idea slowly evaporates. You have done nothing, except wasting your time.

You don’t want your idea flying away, do you ?
Experiment brings you wisdom.


#1 Code is not the value, Execution is
You slowly understand that your code is not the value as you naively think, but you realize that the value is in fact in the Execution of your idea.
Trying to secure your code into your own CVS system hosted into your own server is so unecessary at this stage.

I would recommand you to host your code into hubs (github, gitlab, bitbucket), costing you few dollars per month and bringing you the required level of security.
I would personaly use github for my open source projects an gitlab for my non foss projects.

Cost : 0$ (gitlab) to few dollars

#2 Continious Integration into the Cloud
Continous integration is, for me, a « can’t go without it » thing (regarding the project). Instead of going through the installation described above, I would definitely recommand you to go with online PaaS, such as Cloudbees. It fills all my requirements (Android support, Maven).

Cost : 0$ (free plan)

#3 Organize your development
You can not develop all your features at once, nor starting one before finishing the other. It is better to complete small batch of features sequentially, in an agile manner (definition of ready, definition of done). This helps you avoid dispersing and will benefit you. Then, again, there are online tools that will definitely help you being 
effective (kanbanflow.com for free, http://kanbanize.com for free, Jira Agile 20$/month). I would choose Atlassian for my needs.

As you can see, you can easily start developping, in a peace of mind manner and effective way, for 0$ per month (or few dollars). Your only concern is creating value serenely.
  
Don’t forget : 
The value is not the code, the value is the execution.