Reputation: 35
I want to create a dictionary that maps two strings like so: "package-name","game"
I know that this can be done using the following code:
HashMap<String, String> map = new HashMap<>();
map.put("app_package_name","game");
So in my application, I have a service that make changes depending on the application type as defined by its value. It seems like I cannot declare the map as a static global variable for the entire service class to use, which may means every time my service runs in the app to service the intent, the map will be recreated and new key-value pairs will be put again?
How should I do it if I want to just declare the map and put everything once, then when I handle the service intent, I just need to refer to the map object and double check its key? Is there a better way to do this?
P.S I would prefer to stick to dictionaries if possible.
Upvotes: 1
Views: 1251
Reputation: 789
As I understood - you need service to run all the time. But problem with services - they can be killed by system in any time. And if you store your map in such service it would be erased during service kill process. The simplest solution - use database. Preferably with Room framework with parallel put values and keys in map. On every read of map check if it's not null and not empty. If it is - populate it with data from database, else - use data from map. Don't try to write whole map while system trying to kill service - this would lead to unpredictable behaviour.
Upvotes: 3
Reputation: 471
You can put your data in shared preferences and retrieve it when you would like, or serialize your obejct and save as JSON, and then work with it.
Upvotes: 0