Look Ma! I'm on the Internet!

Mobiconf 2015

Mobiconf 2015

I’ve been invited as speaker at Mobiconf 2015 in Krakow. It was a really nice event and the place was a real cinema, quite an intimidating stage :)

I want to thank to the organizers for such a wonderful event and the excellent treatment received. If they are interested on inviting me again, I will for sure repeat next year.

Here is a list of the conferences I’ve attended and a small wrap-up. I’ll add the links to presentations once they are online.

Kevin Goldsmith – Apportioning Monoliths

Kevin is dev lead on Spotify. He was working on Microsoft for many years and he compared they way of working in the 90’s in MS with their current methods on Spotify. Basically, the first was a huge falldown process with a 3 years production phase. In Spotify they have now a 2 week release cycle and they want to move it down to 1 week
He also explained how they moved from a team-per-layer structure to a team-per-functionality structure and how this allowed this to avoid inter-layer locks. This speech really got me, as I worked in a company performing translations for Microsoft in that time and I lived part of the issues he mentioned.

Sergi Martínez – Android Data Binding

That was mine. Android introduced data binding in I/O 2015 and is still in beta, but it could be a huge difference in the way we create UIs. There are still some things missing, like the two-way binding, which can be achieved at the moment with a lot of tricks. Data binding also allows using the MVVM pattern, as we use View Models to feed the data into views. I’ll write an article about that.

Diego Gómez Olivera – Booking Now Architectural Overview: Clean code for Android

Diego is an Android engineer at Booking Now and a GDE. He explained how they implemented the Clean Architecture pattern in their application. The communication of the different components is based on a Bus architecture to send commands and receive actions. They use tiny bus, as it was the most efficient in their benchmarks over GreenBus and Otto.

Svetlana Isakova – Kotlin on Android

Svetlana is part of team that created the Kotlin language in JetBrains. This speech was an introduction to the characteristics of the language and why they think it is a good language with a lower development effort needed. The second part was a brief introduction to the language itself introducing the changes and new elements of the version 2.0. Really nice good-looking language, but still not intended for production.

Denzil Ferreira – AWARE: mobile context instrumentation framework

Denzil is an investigator at the Oulu university in Sweden. He and his team work on the AWARE framework, an open-source library for Android responsible for getting information about the user context, not only from device sensors but from other data sources. The framework is really scalable via plug-ins and the backend allows to easily retrieve information and change what data is collected on the fly. It also simplifies a lot the use of sensors and, specially, collecting and sampling data. I’ve specifically ask for car sensors and he told me that plug-ins are not available yet, but he was tinkering with it (because he has a VW car) and they are easily integrable via plugins. More: http://www.awareframework.com/

Cesar Valiente – New permissions model on a “Nice” way

Cesar works at Wunderlist (now Microsoft) as Android dev and is a GDE. He introduced us in the new permissions feature in Android Marshmallow. He told us about the “official” way of using them, and how easy it works, but also discussed about how difficult is to integrate in an efficient way into a complex application. He shown us the full workflow and a proposal to integrate it into a project based on Clean Architecture

Savvas Dalkitsis – Lightweight Android lifecycle annotations

Savvas is an android dev at Shazam. We were introduced to a library Shazam published that allows to use Aspect Oriented Programming to Android UI. They moved from calling them aspects to traits. Basically, it allows to add an remove features from view objects (View, Activity, Fragment) with just annotations. Quite amazing library, for me the best example was adding the annotion @FABButton as annotation, and hop, the activity has a FAB button configured via annotation parameters. The library allows us to easily create new annotations that add new functionalities. Worth to check.

Marcin Kasz – Your beacons have been hacked! Why security Matters

Marcin from Kontakt.io discussed about the importance of security on a beacon implementation. We reviewed the most common types of attacks and some tricks to avoid them. My favorite was piggybanking, where a competitor uses your beacons to show you geolocated prices of products that are cheaper in their store.

James Nocentini – How to develop an offline-first native Android app

James works on the CoachBase project for Android. The speech was an explanation on how their system works. The great advantage of CouchDb for Android is that synchronization between server and client is made automatically in the background and can also be done between clients in P2P mode. We were introduced to several synchronization strategies and he made a nice demo of a website accessible by everybody showing a picture of a city and a text to introduce the name and how this picture was changed in every mobile through sync. I’m not sure if it’s valid for all cases, but could be interesting for a project like the Christmas parade.

Frederik Schweiger – Hello again, Android Wear!

Frederik is from the GDG Düsseldorf and a real enthusiast in Android Wear. He made a review of Wear basics and updated to the current state of the art. He also shown us some examples of apps he made like a remote door opener for his car. The good thing about this speech was that being the last one, a lot of people already left the convention and we had more an open discussion that a round of questions. Some interesting answers to my questions: despite having wifi, new wear doesn’t allow direct connection, is just for cloud notifications. Google fit is accessible from the watch, but only gets info obtained from the watch, not from the cloud and permission must be given from the phone before, and yes, the watch can fully access sensors.

It’s the Arts 2! – Dealing with bitmaps

In the previous article (Having fun with canvas) we started playing around with the canvas using some Bitmap objects. Unfortunately, playing with Bitmaps it’s no so easy. They tend to be huge and need a lot of memory in order to be stored.

There are a lot of articles talking about how bitmaps are stored in memory, but, tl;dr, so I’m just going to set some basic points about it:

  • Bitmaps are not stored in the same memory space as objects
  • Bitmaps are stored raw. It means that if you have a 100×100 pixels using 24 bits per pixel it will need 100x100x24 bytes = 240,000 bytes (around 240Kb).
  • We need to get rid of bitmaps as soon as possible, at the same moment we stop using them
  • Remember, Bitmaps loaded from disk are immutable so we can’t draw on them (but we can use them to draw on another canvas)

Let’s see how to fix these issues one by one.

Loading smaller bitmaps

In the previous article, we saw that you can load a Bitmap from disk (specifically a Resource) like this:

The problem here is that maybe the bitmap is too large for the final size in screen, so we are wasting precious memory that is not needed. For example, if our bitmap is 1000×1000 but it’s going to be shown in a view that is just 100×100, we are loading 24,000,000 bytes when we only need 240,000. Wow! 24Mb of image loaded to be drawn as a 240Kb image. Remember, image is precious.

He knows about memory

There is a second implementation of the method decodeResource that allows us to set a BitmapFactory.Options object in order to tweak how the bitmap is loaded.

We pay special attention to the parameter inJustDecodeBounds. This parameter will make BitmapFactory to not load the bitmap, but just load the out parameters of the Options object, giving us the width and height of the image.

We also have a parameter named inSampleSize, that forces BitmapFactory to load the image using this parameter as a reducing scale factor.

Now we have the elements that we need to load smaller bitmaps. Recap:

  1. Determine the minimum size of the bitmap that we need
  2. Setup a BitmapFactory.Options object with the inJustDecodeBounds set as true
  3. Decode the bitmap
  4. Get width and height from the resulting options object
  5. Calculate the appropiate scaling factor
  6. Set the factor to the inSampleSize property and inJustDecodeBound as false
  7. Load the bitmap

Here you have a function that does the work:

And the method calculateInSampleSize

This method has been taken from Android documentation. You can find this code and MUCH more information about handling memory on http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Mutable bitmaps, immutable bitmaps and getting rid of them

As said before, bitmaps loaded via BitmapFactory. If you need to make them mutable, you have two options:

  • Set the property inMutable from BitmapFactory.Options to true before loading
  • Copy the bitmap using the method copy from Bitmap class with the parameter mutable as true.

Making bitmaps mutable needs more memory, so use it wisely, only when you need to draw ON the bitmap. Sometimes is better, if you are going to paint it on a canvas later, to paint your bitmap on the canvas, then paint over. It depends on what you want to achieve. Remember…

Oh! who cares…

Last but not least, we can mark bitmaps to be cleaned from memory before the GC destroys the bitmap object. Just call the recycle() method in the bitmap object and the memory used to hold the pixels will be clean. The object will still exist, but any try to use it will give you an error.

We will see examples on how to use it in future articles, but for the moment, get used to the concept.

Just to summarize. Memory is important. Bitmaps are huge. Optimize them by loading smaller bitmaps and freeing them asap.

Stay cool and reduce your bitmaps memory footprint

It’s the arts! The Workshop

It’s the arts! The Workshop

Last week I had the pleasure to make a 4 hours workshop titled “It’s the Arts! Playing around with the Android Canvas” organized by GDG Barcelona.

The workshop was based on 3 topics, each one with an introduction to explain concepts and related classes and methods plus a set of exercises to test and practice the topic.

After the workshop we enjoyed a nice BBQ with all assistants!

The event was performed at La Fábrica,  a new space to share and hack in Barcelona (Sagrera).

You can find the slides on Slideshare and the exercises on Github.

You can also find pictures of the event in the G+ event page.

As usual, a lot of topics were left out of the workshop, as Android canvas is a huge graphics framework, but I’m happy I was able to introduce a lot of concepts, some of them really hard if you have never worked with graphics before. I think that making exercises as a progressive git project will help people to review these exercises later on at their own pace.

As this workshop required a lot of preparation (170 slides!), I will probably repeat it in the future, so stay alert!

Thanks again to the people from GDG and La Fábrica, and of course, to all the people who assisted to the workshop!

See you in the next event!


It’s the Arts! Having fun with a canvas

It’s the Arts! Having fun with a canvas

Making your own views in Android is a lot of fun, and using the Canvas to make them more appealing is even more fun. Graphical effects, animations, and a lot of other things can be achieved extending a simple view and modifying its behavior during the canvas drawing phase.

Starting at this task is quite hard. Information seems to be written for people who already know what they are doing. Then, when you start to see concepts like matrixes, PorterDuff, and so on, you are forced to check if you missed documentation explaining it all .

In this articles I will start reviewing the basic steps to start working with the canvas and drawings.

Catdroid Android Fundamentals Study Jam

Catdroid Android Fundamentals Study Jam

Del 1 de Febrero al 31 de Marzo se va a realizar una convocatoria del curso de Udacity de Android Fundamentals (https://www.udacity.com/course/ud853).

La diferencia esta vez es que en vez de simplemente hacer el curso via Udacity pagando, se podrá acceder al curso gratuito vía el Study Jam.

¿Y qué es el Study Jam? Pues es una iniciativa de Google para crear grupos de estudio locales tutorizados para seguir el curso (en versión gratuita) y con titulación de Udacity.

En este caso, uno de los tutores de Barcelona voy a ser yo, y quisiera saber quien podría estar interesado ya que tenemos que empezar a buscar un sitio donde hacerlo y reserva material (y regalitos).


– Curso online de iniciación a Android gratuito

– Tutorías semanales impartidas por mi para repasar temas y resolver dudas

– El curso dura dos meses (Febrero/Marzo) y requiere de unas 8 horas de dedicación semanales (aprox)

– Al final hay que entregar un aplicación (este tema no es exactamente así, pero ya os lo contaré en persona que es complejo)

Las tutorías son todos los martes a las 19:00 del 10 de febrero al 24 de marzo (7 sesiones) y se realizarán en el Itnig (Carrer Àlaba, 61), mapa y dirección en el eventbrite.

Sólo hay 20 plazas disponibles. Os rogaría que aquellos que ya conocéis Android y queréis hacerlo por repasar o ampliar dejéis plaza a los que si se inician de cero, asimismo, si no tenéis claro si podréis dedicarle el tiempo requerido, también dejéis paso a los que si están seguros.

El enlace es este: https://www.eventbrite.com/e/registro-catdroid-android-fundamentals-study-jam-15383772277

Una vez apuntados, iré mandando más información al correo que uséis para registraros.

Cualquier duda o cuestión, preguntad aquí mismo.

Nota. Los chicos del GDG hacen otra convocatoria cuya tutoría se hará los sábados. Si os interesa, tenéis más info en el foro del GDG BCN (https://groups.google.com/forum/?fromgroups#!topic/gdg-barcelona/3cwwyG6bm4g)

Espero veros allí!

Publicar librerías aar en un repositorio maven en Github

Desde que Android Studio nos lanzó al mundillo de Gradle cada vez da más rabia encontrar librerías que no podemos incluir en nuestro proyecto con un simple compile. Así que, va siendo hora de tener un método fácil de publicar nuestras librerías sin tener que pasar todo el proceso de publicación de Maven Central, que es bastante pesadito.

La idea es tener un repositorio de Github que actue como un repositorio de Maven. En este ejemplo utilizo Github, pero en realidad funciona para cualquier sistema con capacidad de compartir archivos, como por ejemplo BitBucket o incluso un servidor web propio.

Crear el repositorio local

Lo primero que necesitamos es una carpeta local donde establecer el repositorio. Por ejemplo, D:\m2-repo. Aquí en realidad alojaremos dos repositorios, uno para artefactos release y otro para artefactos snapshot. Simplemente tendremos dos subcarpetas con esos nombres. El sistema que seguimos ya las creará cuando las necesite.

En esta carpeta creamos un repositorio Git y lo enlazamos con nuestro repositorio Github. Si quieres utilizar otro sistema de publicación pues aquí es donde toca configurarlo.

Crear y configurar el proyecto de Android con la librería

Para simplificar, damos por supuesto que tenemos dos módulos, uno con la librería y otro módulo de aplicación que utilizamos para pruebas o samples.

Ahora toca aplicar el script de Gradle para publicar en Maven. Incluimos la siguiente referencia al final del fichero build.gradle de la librería:

Este es un script de Gradle que he creado a partir del script de Chris Bane. La gran diferencia es que el suyo está pensado para publicar en servidores Maven, por lo que aquí he quitado todo lo relativo a credenciales, ya que el repositorio Maven destino es una carpeta local del disco. También he modificado un par de cosas que fallaban con la última versión de Gradle.

Si lo prefieres, puedes sustituir esta linea por el contenido del script para tenerlo todo localmente. Up to you.

Las instrucciones de configuración están en el proyecto de Github: gradle-local-mvn-push. No las reproduzco aquí por no hacer este post eterno.

Generar y publicar

Una vez lo tenemos todo configurado, sólo tenemos que invocar las tareas de Gradle necesarias desde la raíz del proyecto:

Si usamos el wrapper desde Windows, hay que cambiar gradle por gradlew.

Esto generará los artefactos necesarios y los copiará en la carpeta del repositorio Maven, con sus sources, su javadoc y todo lo necesario.

Ahora sólo hay que subir el repositorio Maven a Github y nuestra librería estará lista para ser utilizada con un simple compile.

Primero añadimos nuestro repositorio como

y luego incluimos la librería deseada

¡Y listos!

Ya no dependemos de Maven Central y podemos publicar nuestras librerías donde queramos.

Este post va dedicado. Para DG que es la fan número 1 de este blog.

La navaja suiza de Android

Un pequeño listado de aplicaciones y sitios indispensables cuando trabajas con Android. Lo que yo llamo la navaja suiza:

Flat UI Colors: Listado de colores “planos” para utilizar en nuestras apps. Selecciona formato, haz clic en un color y ¡voilà! lo tienes en el portapapeles.

Android cheat-sheet for Graphic Designers: Una chuleta exhaustiva sobre cosas relacionadas con el diseño de apps. Para los que no somos capaces de recordar cosas como el tamaño de los iconos en cada densidad.

Android Holo Colors: Selecciona color, versión, controles y automáticamente nos genera un zip con los drawables y styles necesarios.

Android Asset Studio: Impresionante conjunto de generadores de assets para Android

Parcelabler: Hacer un objeto parcelable es bastante lento y tedioso. Con esta página, tan sólo pega el código de tu clase y a cambio la recibes completamente “parcelablizada”.

Android Layout Finder: Uno de mis favoritos. Pega un layout, elige los widgets/layouts que quieres y te genera el método findViews() de un layout, o todo un Adapter con ViewHolder y todo en el que sólo hay que rellenar el pintado de datos. Gracias a @EsteveAguilera por encontrarnos esta joya.

Android Layout/Style XML Converter: Muy útil para extraer estilos de un layout.

Jsonschema2Pojo: Genial página que nos propone un pojo a partir de un json. Además, permite añadirle anotaciones para Gson o Jackson.

Roman Nurik’s View Server: Pequeña librería que nos permite ejecutar el Hierarchy Viewer contra nuestra app aunque el dispositivo no esté rooteado.

¿Conoces más? Pues comparte en los comentarios e ire ampliando la lista.

Actualización 24 de julio

Algunas cosillas más que he ido obteniendo:

DPI calculator for Android: un rápido conversor entre DPIs. También disponible como extensión de Chrome.

Gradle, please: un buscador de dependencias en formato Gradle. Muy util para incluir rápidamente a los sospechosos habítuales.

Android drawable generator: esta web genera el tag para un objeto button y el drawable necesario. Multitud de parametros personalizables. Lástima que no haga también los múltiples estados.

APK Downloader: se supone que permite descargar apks no disponibles en tu país desde Google Play, pero nunca he conseguido hacerlo funcionar, ya que tenían muchas limitaciones de número de descargas diarias. Según dicen, ya está solventado.

Android Design Tips: una chuleta con cosas básicas de diseño y UI (tamaños, márgenes, etc). También incluye un conversor de DPIs

The Android Arsenal: repositorio de librerías y componentes clasificados por categorías.

WSDL2Code: últimamente me está tocando atacar servidores SOAP. Esta ultra-útil página genera la capa cliente de Android a partir de un WSDL. Generar, copiar, y utilitzar.

Actualización 3 de agosto de 2014

Mockup Phone: un sistema rápido de hacer mockups de capturas de pantalla. Rápido y fácil:

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 II: General architecture of an app


Today, I’m going to talk about the architecture I use to apply on my apps. First, a few basic guidelines I always respect:

  • This is intended for client apps attacking a REST api (or similar). This is not valid for games or certain stuff.
  • All data should be persisted. If you respect your user then persist the data!
  • The local database it’s not a database per se, it’s a cache.
  • The real database is located on the server and we only have a part of it. Keep this always in mind.
  • I would sometimes ignore the normal forms for simplicity and performace sake. It does not matter, remember, I’m just a cache, the good database with normalized data is on the server.
  • The splash screens on Android apps are evil.
  • The style guide is sacred. It only can be ignored to innovate and improve. I don’t know anyone capable to do this. Doing it differently does not mean innovation. Doing it like in iPhone it’s not innovation.
  • My rules are mine and I skip then whenever I want.

General architecture by layers

For a couple of years I worked with Code Igniter, an excellent Framework MVC in PHP (yes, I have a past as PHP developer, I was young, I needed the money). I’m sorry, but I don’t think Android is MVC. This is like discussing the sex of the angels, there will be people agreeing with me and others not, so we will assume that our architecture is NOT based on MVC.

When talking about layers, I split the application between Frontend and Backend. Or as I use to call them: ui and sdk (or core).

In fact, in big projects I usually create the sdk in a library project and the ui in a main project. This helps a lot to separate these two layers and to distribute the work.

On the ui layer I got everything in charge of managing the interface: activities, fragments, views, adapters, etc. All of them, data consumer objects.  It can be that something else is included here because of Android nature, even if they are not ui, like object Application, Notifications, Push, NFC handlers, etc.

On the other side, on the sdk layer (the one with the main part) I got the parts managing the data: beans, clients, ContentProviders and tasks (and some other things such as helpers).

The UI layer

We will talk deeply about this one with examples another time. By now, here go some overviews and rules I use to follow.

All the elements from this layer are included inside the ui package. So, we will have ui.activity, ui.fragment, ui.adapter, ui.view, etc.

All classes have as suffix what they are , for example,  MainActivity, FooAdapter, etc.

Each element has a set of public constants, final and static that start with EXTRA with the name of the parameters that can be expected in the bundle provided to this class.

The Intents between activities and fragments do not send full objetcs (and even less arrays). They only send the object id. For example, if I have an activity (or fragment, in this case it’s the same) ProductListActivity with a list of products when selecting one I invoke the following activity ProductActivity I just only send the id and this second one invokes the content provider to return the record and to read it. If the data can change during the view by external elements I use a loader to show the details, and it receives notifications from content providers.

The adapters ALWAYS uses ViewHolder.

The SDK layer

This layer is the one in charge of data input and output to the server and its persistence. See below a graphic with the main elements:

android architecture

A review on the packages I use to create the what’s included in each:

  • bean: all the data objects. Maybe you call them DTO, domain or something similar. No problem. But I make no difference here. I try the beans to be as POJO as possible and I don’t make them getters or setters. They are simple structures with annotations for the JSON deserialization.
  • client: These are the representations of the web services. For example, a LoginClinet class invokes the login service , manages the answers and returns it processed. I use a a structure from simple IntentService that invokes the web service that the client provides as parameters. We will discuss about this topic on another article. The advantage of the system is that you make easily a lot of  clients. Here takes place the serialization/deserialization to JSON ( or what ever it’s needed).
  • model: all the persisted data model, on the root I place the data contract, the set of constant that define tables, fields and entities of the content provider. In some cases, when the applications are quite big, I split the database contract and the one from the content provider. But please take into account that then the maintenance is complex and tedious.
  • model.content: the content provider, following the structure explained in previous article with DespicableContentProvider and MinionContentProvider
  • model.cursor: here I have one CursorHelper per entity. Basicaly, they are in charge of passing from cursor record to object and viceversa.
  • model.db: contains DatabaseHelper and similar.
  • service: the IntentService invoked by clients, and any other service that might be needed.
  • task: these are atomics process that invoke clients and ContentProviders. For example, the typical task of UpdateProductsTask invokes GetProductsClient, makes a delete over the Content Provider of products and then a bulk insert. This process has an output showing if it has been successful or not.

The key is also in my library to accessing web services called Rarest. For more information, please check www.rarestandroid.com.

On the next article we will see a nice example showing the above explained.

En busca de la arquitectura de Android perfecta II: arquitectura general de una app


Hoy voy a hablar de la arquitectura que suelo seguir en mis apps. Para empezar, unas cuantas normas básicas que siempre sigo:

  • Estoy hablando de apps cliente de una api REST (o similar). Esto no sirve para juegos ni para según que cosas.
  • Todos los datos van a ser persistidos. ¡Si respetas a tu usuario, persiste los datos!
  • La base de datos local no es una base de datos per se, es una caché. La base de datos de verdad está en el servidor, y nosotros sólo tenemos una parte de ella. Tengamos esto siempre en cuenta.
  • Me permito ignorar algunas veces las formas normales en pro de la simplicidad y el rendimiento. Total, sólo soy una caché, la base de datos buena y con datos normalizados está en servidor.
  • Las pantallas de splash en apps de Android son el demonio
  • La guía de estilo es sagrada. Sólo se puede romper para innovar y mejorar. Todavía no he conocido a nadie capaz de hacerlo. Hacerlo diferente no es innovar. Hacerlo como en iPhone no es innovar.
  • Mis reglas son mías y me las salto cuando quiero

Arquitectura general por capas

Durante un par de años trabajé con Code Igniter, un excelente Framework MVC sobre PHP (sí, tengo un pasado como programador de PHP, era joven, necesitaba el dinero). Y yo lo siento, pero por más que miro, no creo que Android sea MVC. Esto es discutir el sexo de los ángeles, hay gente que está de acuerdo conmigo, y gente que no, así que vamos a partir de la idea de que nuestra arquitectura NO se va a basar en MVC.

En cuanto a capas hablamos, yo divido la aplicación en Frontend y Backend, o como les suelo llamar, ui y sdk.

De hecho, en grandes proyectos suelo montar el sdk en un proyecto librería y la ui en un proyecto principal. Esto ayuda mucho a separar estas dos capas y a distribuir el trabajo.

En la capa ui tengo todo aquello encargado de gestionar la interfaz: activities, fragments, views, adapters, etc. Todo ello objetos consumidores de datos. Cae alguna cosilla más que a veces tiene que estar aquí por la idiosincracia de Android aunque no sean ui tal cual, como el objeto Application, Notifications, el Push, etc.

Por otro lado, en la capa de sdk (que tiene la chicha) tengo lo que gestiona los datos: beans, clientes, ContentProviders y tareas (y algunas cosillas más del tipo helpers).

La capa UI

De esta hablaremos otro día a fondo con ejemplos, de momento ahí van algunas generalidades y normas que uso.

Todos los elementos de esta capa los incluyo dentro del paquete ui. Así tendremos ui.activity, ui.fragment, ui.adapter, ui.view, etc.

Todas las clases tienen como sufijo lo que son, por ejemplo MainActivity, ForlayosAdapter, etc.

Cada elemento tiene un conjunto de constantes públicas, finales y estáticas que empiezan por EXTRA con los nombres de los parámetros que pueden ir en el bundle del intent de llamada.

Los Intents entre activities y fragments no se mandan objetos enteros (y mucho menos arrays). Sólo se mandan el id del objeto. Así por ejemplo, si tengo una actividad (o fragment, ahora da igual) ProductListActivity con una lista de productos, al seleccionar uno invoco a la siguiente actividad ProductActivity sólo le paso el id, y esta segunda invoca al content provider para que le retorne el registro y lo lee. Si además los datos pueden cambiar durante su visualización por elementos externos, utilizo un loader para mostrar el detalle.

Los adapters SIEMPRE con ViewHolder.

La capa SDK

Esta capa es la que se encarga de la entrada y salida de datos hacia el servidor y de la persistencia de la misma. Aquí u gráfico con los elementos principales:

android architecture

Repasemos los paquetes que suelo crear y que hay en cada uno:

  • bean: pues aquí van todos los objetos de datos. ¿qué tu le llamas DTO, domain o algo así? pues bién, no me pelearé por eso, pero lo que no hago son distinciones. Cada vez intento que sean los más POJO posibles y no les hago ni getters ni setters, vamos, que son estructuras tontitas con anotaciones para la deserializacíon JSON.
  • client: aquí todos los clientes. Son las representaciones del los servicios web. Por ejemplo, una clase LoginClient invoca al servicio de login, gestiona la respuesta y nos la devuelve procesada. Uso una estructura de IntentService tonto que invoca al servicio web que el client le pasa como parámetros. Ya hablaremos de esto en otro artículo. La gracia del sistema es que haces los client como churros. Aquí se produce la serialización/deserialización a JSON (o lo que toque).
  • model: aquí todo el modelo de datos, en la raíz coloco el contrato de datos, el conjunto de constantes que definen tablas, campos y entidades del content provider. En algunos casos cuando las aplicaciones son muy grandes, separo el contrato de base de datos y el de content provider, pero ojo que entonces el mantenimiento es farragoso y complicado.
  • model.content: los content provider, siguiendo la estructura del artículo anterior con DespicableContentProvider y MinionContentProvider
  • model.cursor: aqui tengo un CursorHelper por entidad. Básicamente se encargan de pasar de registro del cursor a objeto y viceversa
  • model.db: el DatabaseHelper y similares.
  • service: aquí va el IntentService que invocan los clientes, así como cualquier otro servicio que pueda necesitar.
  • task: son procesos atómicos que invocan clientes y ContentProviders. Por ejemplo, la típica tarea de UpdateProductsTask invoca a GetProductsClient, hace un delete sobre el Content Provider de productos y luego un bulk insert. Este proceso tiene una salida indicando si ha ido bien o mal.

El meollo de esto está también en mi librería de acceso a servicios web llamada Rarest. Teneis info en www.rarestandroid.com.

Ale, el próximo día veremos un lindo ejemplo con todo esto.

1 of 4