Search code examples
androidjsonsqlitecachingandroid-lru-cache

Android cache read-only REST API responses when offline


I'm pondering 2 approaches

  • Caching the JSON responses as JSON files
  • Caching the Java POJOs (the JSON responses are already de-serialised using Retrofit) using Reservoir.

Description of the data:
The data I want to cache here are a list of 20 products from an e-commerce site. They are not complicated objects and there is no nesting since jsonapi.org specs are used here. With Retrofit I can already get 20 Product POJOs where Product is the Java model class with less than 10 attributes.

Which approach is better and why?

I'm not considering SQLite databases since I think it is more expensive and only suitable when

  • data integrity is required
  • there are write operations e.g. shopping cart
  • larger amount of data with complicated relationships

Solution

  • It really depends on 2 main factors: 1. Use cases 2. How comfortable are with a specific system.

    You can use any you think suits you. SQLite is ok if you really need DB like data structures and some complex query-ing mechanism. You can wrap SQLite with some ORM system like GreenDAO or ORMLite if it helps you. There is also Realm, more Object Oriented approach (with it's issues).

    You can also opt for SharedPreferences (I personally dislike this approach) or just serialize POJOs with parcelable or Java Serialization to files. It really depends on what you want to achieve as any approach has it's pros and cons.

    In case of SQL oriented DB's there is a big user base of SQL which is good but you need mapping not that good.

    Realm, might be the Next Big Thing in mobile devices DBs (good) but it's still immature and you have to work with concrete classes when retrieving (bad), I might want an abstract/interface/base class.

    Parcelable - you have to write a lot of code (bad) but it's pretty fast (good)

    Java Serialization - easy to refactor any serializable class, no code for serialization, good for small to medium amount of data. Not that good for really large amounts of data as it uses Reflection.