In the process of building an Android application I encountered a number of small and foolish issues which I thought that I would outline such that you don't make the same mistakes.

I probably shouldn't be admitting to making these kinds of mistakes, but.. well.. I am :)

Match you lifecycle calls

I utilise greenrobot's EventBus library to send various notifications across the application.

I could not for the life of me see as to why a subscriber was not picking up an event that I was posting.

The problem was that I was subscribing to the event in my Activity's onCreate but unsubscribing in onStop.
onStop is called when you open another Activity (even when the initial activity is not destroyed).

As such, when I went back to the initial activity, it was no longer subscribed to the event. Because it wasn't being recreated it was not being resubscribed.

The resolution is to unsubscribe in the appropriate lifecycle pairs:

  • onCreate and onDestroy
  • onStart and onStop
  • onResume and onPause

Learn more about the activity lifecycle here.

The other consideration here is that if you are going to have a global subscriber (e.g in a generalised activity superclass), don't use the onCreate onDestroy pairing. Just because an activity is not on the screen it does not necessarily mean that it has been destroyed. You do not want 'old' activities to be receiving events not destined for them.

Use the code analyzer provided by AndroidStudio

Having released the latest version of the application, I noticed that the APK was somewhat bigger than one might expect (~17mb). AndroidStudio has a little known treasure - its code analyzer. If you select 'Analyze > Inspect code', you can have your code analysed (at which point you can optimise).

In my case, I had left a number of drawables in the APK which I had not ended up using (silly me). Removing them reduced my APK size significantly.

Use SparseArray instead of HashMap

This one is a little tidbit. It will likely make an insignificant difference, but hey.. every little helps.

As outlined in the documentation for SparseArray,

"SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping."

So.. replace those instances of HashMap<Integer, Object> with SparseArray<Object> - it is more efficient.

That is all

That is all for now. If you have encountered any similarly foolish issues in your app development journey, please do share them in the comments. Save us all some time and self loathing ;)