Alon Levanon
Alon Levanon

Reputation: 701

Keep HashMap data while app is running - Android

I have a HashMap which contains data that is relevant to a specific Activity. The data should be fetched from a server and is quite big so I dont want to fetch it inside that certain Activity. Instead, I am fetching all the data in the main activity, into a custom class and then I create a HashMap for holding all of the objects and save it in my Application class.

When the user goes into the other activity, the data is ready to go without any need to wait, by calling the HashMap I created earlier from the Application class.

It is all working fine except some times when the app is in the background for a long time, the data stored in the HashMap is being initialize by Android.

I've read that storing objects in the Apllication class is bad and I wont be able to avoid this error, so my question is what is the right approach for doing that proccess? I need a solution that will keep my HashMap object alive as long as there's an instance of my app.

Upvotes: 0

Views: 691

Answers (3)

Alexander
Alexander

Reputation: 597

The data should be fetched from a server and is quite big so I dont want to fetch it inside that certain Activity.

Mb better to use Sqlite for data storage purposes because android devices doesnt have unlimited resoureces?

Upvotes: 0

Drew
Drew

Reputation: 3334

One of the available approaches is to use a "headless" retained Fragment to persist the HashMap data across Activity recreation. According to android docs such Fragment's lifecycle is quite different:

  • onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
  • onCreate(Bundle) will not be called since the fragment is not being re-created.
  • onAttach(Activity) and onActivityCreated(Bundle) will still be called.

Thus, when your Activity dies from a configuration change and so on, your Fragment does not. When Activity is recreated, it could request your retained Fragment for a piece of "cached" data. Read this, if you like to do it this way.

The other approach I could think of is to cache your data in a database or a file, but that would be an overkill, I guess.

Upvotes: 0

Matt Logan
Matt Logan

Reputation: 5926

I have a HashMap which contains data that is relevant to a specific Activity.

If this is the case, why wouldn't you want to keep the HashMap as an instance variable in your activity? Storing data for a specific Activity in your Application object isn't good object-oriented design.

If you need to keep the data in the HashMap when the Activity is destroyed and created, you can save it in onSaveInstanceState().

Upvotes: 2

Related Questions