Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SharedPreferences limitations?

I developed a game on Android. I am currently saving most of the game stats in a Database. However the app does not utilize more than a single row in the DB. I am now interested in introducing some new stats but this will cause my DB to re-install and thus clear out everyone's progress. In order to avoid this in the future I am considering storing the game stats with SharedPreferences instead. My question is how many different things can be stored that way before it becomes a problem. In total I would be storing around 40 values, all integers.

like image 925
Tim Avatar asked Jul 08 '10 00:07

Tim


People also ask

How much data we can store in SharedPreferences?

SharedPreferences are not intended to store a lot of data, there is no limit per se (since it is an xml file), but for larger sets of data, I would suggest using Room (or SQLite for the older projects).

What are SharedPreferences what are its advantages?

Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device. To get a handle to a preference file, and to read, write, and manage preference data, use the SharedPreferences class. The Android framework manages the shared preferences file itself.

Is SQLite better than SharedPreferences?

To give an example, SharedPreferences are useful for storing user preferences, where there are just a handful of variables that need storing. SQLite on the other hand would be better for storing data where there is a large set of items, such as song titles in a music library which need to be searched through.

Can we save image in SharedPreferences?

Once the user allows access to the camera, we can capture an image. We get the captured image inside onActivityResult() method. Now we call the PreferenceManager method and store the captured image into SharedPreferences.


1 Answers

SharedPreferences are written to xml files, so the maximum size of a file on Android is how large a SharedPreferences xml file can be. I can safely say that 40 integer values will not be a problem.

The maximum size of a value in a SharedPreferences file is limited to the maximum size of the value you are attempting to store. (Meaning you can't put a String value that is longer than Strings can be in Java.)

The only thing I would suggest is making sure to batch the edits as much as possible (meaning don't .commit() each change) and also don't create a new editor for each change. (These are just good practices.)

SharedPreferences settings = getSharedPreferences(PREFS_FILE_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("firstValue", mFirst);
editor.putInt("secondValue", mSecond);
editor.putInt("thirdValue", mThird);

// Commiting the edits
editor.commit();
like image 165
Guzba Avatar answered Sep 22 '22 17:09

Guzba