Question

I want to keep some objects in memory for operations in all the activities of my app and I also want to store those objects when the app closes. Which is the most efficient way of doing this ? Some possibilities that I can think of are:

1) Keeping local copies of objects in all the activities, serialize them and pass them through intent.

2) Keep local copies of objects in all the activities, serialize them and do file read and write on activity resume and pause respectively.

3) Make them static variables but I don't know when to do the file read/write operations in that case? This approach may leak memory.

4) Use Application object and define my objects as variables in that object. Since it has a definite life cycle like activity, I can do read/write accordingly.

Was it helpful?

Solution

I recommend your approach number 2. The reason is that there is no such thing as "the app closes". Android tries to keep it in memory until the memory is needed for other purposes. The process of your app is then simply killed, you don't get any callbacks called.

Singletons or the Application object can be used to cache the objects if you are careful to load and store them as necessary. However, this also means, that the memory used for them is only reclaimed if the app process terminates.

OTHER TIPS

It depends on your data. All approaches are good in some cases.

I think you have 2 options:

  • keep data in sqlite. It is easier then files and faster. When activity starts request required data from db and show it. (use files if you really want)
  • create a singletone class to store data. Data will be loaded in memory and you can access it very fast. When data changes save it to sqlite or file. google "share data between activities"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top