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

143 Views Asked by At

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.

3

There are 3 best solutions below

1
Gennadii Saprykin On BEST ANSWER

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.

0
Tartar On

SharedPreferences is a key/value way to save data. I think it is not appropriate to save large amount of structured data as you have to define a key for each value you have.

Using SQLite might be a better option for your case.

0
Ganesh K On

You should switch to a more reliable way of storing data in storage instead of using SharedPreferences.

Sqlite is good option but if you don't like to write SQL Queries and want a solution where you want to store data in your storage, Realm is an amazing alternative.

Although before implementing please read more on the pros and cons of using realm. You can read more about Realm here :-

realm.io

Realm vs Room vs ObjectBox