Search code examples
androidandroid-intentandroid-activityserialization

Persist object when changing Activity


I am currently facing a problem with persisting object state in an android app.

I have some kind of multi level master-detail flow.

For example, I have a list of Clients. Each Client has multiple Orders and each Order has multiple articles.

Until now I did the following:

  • When you click a Client in the MasterActivity I write the Client into the Bundle and open the DetailActivity.
  • In the DetailActivity I read the Client from the Bundle and display it.

This worked more or less fine most times, however it now happens, that an object is too big to be serialized (for example a Client with a lot of Orders).

Therefore I wanted to serialize only the ID of the Client and load it from the database inside the DetailActivity. Usually this approach works fine but I have one situation where it does not work:

The Articles are only saved, when you save the Order (their Master). So if you create a new Article for an Order and you don't save the Order, the Article isn't saved too.

That means, that I always need to have the full object, reloading it from the database inside the DetailActivity means, that I loose all the unsaved changes. However, persisting it, using the Bundles could exceed the limit (500kB to 1MB).

So my question is, what is the preferred way to persist such data?


Solution

  • A nicer way is to create your own singleton class which points to data you want to transfer between activities.

    I suggest DataManager singleton activity which has Article articleToPass Make the setter set the articleToPass to point to what ever you want. and the getter or reader, will read fetch the article and nullify the articleToPass.

    manage your app data using this DataManager singleton (This dataManager singleton can be initialized either in the extending Application class or MainActivity).

    Incase you must persist the object when app is destroyed and loading back:

    1. Create from Article object a DB entry which contains all data you need (I see no reason why saving data you don't need here)
    2. Dump all data to some file (Using Shared Prefs, key and values)
    3. When entering the Details screen you want make a query to a sever of yours requesting all data you need by ID or such.
    4. Convert all object you need to JSON (simply using GSON), and dump the JSON to a file, and load it when you need.

    I think the resolutions above are enough :) hope i helped