Search code examples
androidlocal-storageandroid-sharedpreferences

Is it a good idea to store multiple values as SharedPreference?


In my android app I have about 100 places (maximum will be 200). I want to allow the user to mark each place as visited and store this selection.

So the user can mark/unmark that he already visited some places/cities.

Is it a good idea if I store the values as SharedPreference?

My code:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("London", "1");
editor.commit(); 

and next time when user marks another place then:

editor.putString("Paris", "1");

I am asking due to amount of possible places to be stored there, which will be maximum 200 in my case. I am usually using this kind of storage just to store some settings or so, but I think this is an easy way to store the values in my case too, I don't want to use database or anything similar for storage.


Solution

  • Whether this is a good idea or not depends on your requirements and expectations. If you store the data like this, it will work for sure, but, there will be some limitations:

    • It might be complicated to show a list of places to the user. If you store some other data to shared preferences you will need a way to distinguish places from other data. In this case you'll probably need to add a prefix to all your keys, such as "place_London", "place_Paris", etc.
    • You are relying on English key names so you might have issues with localization if you support other languages
    • It will be much harder to support versioning and scalability. E.g. if later you have an entity called "Place" and it has more information than just a name with a flag, then it will be much harder to keep it in shared preferences. E.g. if at some point you want to add a corresponding country name to all places, what do you do?

    I think in this scenario you actually DO want to use database. It will pay off.