27

Does it make sense to use an ORM in Android development or is the framework optimized for a tighter coupling between the UI and the DB layer?


Background: I've just started with Android development, and my first instinct (coming from a .net background) was to look for a small object-relational mapper and other tools that help reduce boilerplate clode (e.g. POJOs + OrmLite + Lombok).

However, while developing my first toy application I stumbled upon a UI class that explicitly requires a database cursor: AlphabetIndexer. That made me wonder if maybe the Android library is not suited for a strict decoupling of UI and DB layer and that I will miss out on a lot of useful, time-saving features if I try to use POJOs everywhere (instead of direct database access).


Clarification: I'm quite aware of the advantages of using ORM in general, I'm specifically interested in how well the Android class library plays along with it.

Heinzi
  • 9,646
  • 3
  • 46
  • 59

2 Answers2

20

Android does not play as nicely with other frameworks as it could. Its recommended style of development assumes you build everything from its API, without other libraries. The UI layer is very tightly coupled to the model. This style is ideal for writing smaller, modular apps, not for complex applications.

You need to give some thought as to whether you will want any of Android's functionality; if you don't need it, then you have nothing to lose by using an ORM. If this is not the case, you may need to settle for a hybrid. Use an ORM for all you can, but give yourself hooks to Cursors and any other low-level objects you require. If the ORM you choose requires DAOs (I'm not familiar with the one you mentioned), then this layer is probably the best place for them.

Alternatively, you may need to use no external ORM at all. If your needs are straightforward you can write a simple data access layer that meets them. Most apps database requirements are not great. If you have only a couple of tables, just write a couple access classes and the model objects and call it good.

YAGNI and KISS are the keywords to success here. I suggest you spend a few days prototyping. Don't be afraid to throw out the simple test apps. Try out all your ideas alone, then decide if any or all will work for your project.

dckrooney
  • 227
  • 1
  • 7
Michael K
  • 15,539
  • 9
  • 61
  • 93
6

It depends on what you do with your data model. If you have existing code that manipulates an object oriented model, and if you want to persist those objects in a sqlite database, you need an orm.

If you are writing new Android code from scratch, I would avoid an in-memory data model unless the app performs really complex OO manipulations, as a CAD program might, for example. But, for most programs, keep the data model in the database, and let the chain of Cursor, Adapter, and View objects do a lot of heavy lifting for you.

Zigurd
  • 81
  • 1
  • 2