Pros and Cons of SQLite and Shared Preferences [closed]
Asked Answered
O

5

184

What is the good mechanism to store information among SQLite database and Shared Preferences?

Why use shared preferences? Why use sqlite? I tried to find the difference between them, and which is the better mechanism for data storing, but I am unable to find the appropriate answer on Google. Please help me with example and explanations.

Optometrist answered 8/6, 2011 at 8:54 Comment(3)
It pretty much depends on kind of data you want to store. SharedPreferences allows a quicker and simpler access to data, it's more comfortable to use when keeping small amounts of data.Berezina
Do not store anything in Shared Preferences except simple strings and primitives - and if you do use a separate file for each - despite the docs Shared Preferences are not thread safe and even if used solely on the main thread extremely prone to corruption should you store more than 1 key value pair in a file.Michey
SharedPreferences are cached in memory after first use, so they should be pretty fast on consequent Read uses.Boarish
D
189

It really depends on the data you want to store.

SQLite

Large amounts of same structured data should be stored in a SQLite database as databases are designed for this kind of data. As the data is structured and managed by the database, it can be queried to get a sub set of the data which matches certain criteria using a query language like SQL. This makes it possible to search in the data. Of course managing and searching large sets of data influences the performance so reading data from a database can be slower than reading data from SharedPreferences.

SharedPreferences

SharedPreferences is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.

Dubious answered 8/6, 2011 at 9:49 Comment(9)
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.Larry
You don't need to know the key names to use SharedPreferences. See getAll().Serology
FYI, there is a THIRD option: read/write XML to a file. (See android.util.xml classes). Appropriate for moderately complex data that can be read/written all at once. For example, a grid of values that user does not change frequently. Especially if it is data that you might later want to send elsewhere, so will need in a parseable format.Nationalize
But SharedPreferences stores the key value pairs in an XML file. Only that you don't have to write your own xml parser and manage the saving protcol yourself.Afterbirth
is it advisable to save a json as json string in shared pref?Impanation
Note that SharedPreferences isn't process-safe.Clew
@Clew It means that sharedPreferences could not load, but SQLite operations always will be executed? I have to store 300 values (fixed amount of data), is a good idea to use sharedPreferences?Salsbury
@JCarlos As long as you are not doing some cross process stuff, you'll be fine using SharedPreferences.Clew
@Flo, I have a Json Response you can see this json Response from this link -> samples.openweathermap.org/data/2.5/…. This is basically giving me weather forecast for 5 days. what i need to do is, i need to update this forecast everyday and store it somewhere to use it in my UI. I am confuse between caching this response in SharedPreferences or SQLITE. Please help me out.Alexina
R
116

This question has an accepted answer, but I think there is more to said on the topic - regarding speed.

An application's SharedPreferences and Sqlite DB are both just files, stored in the application's directories on the device's file system. If the amount of data is not too big, the Sqlite option will involve a larger and more complicated file with more processing overhead for simple access.

So, if the nature of the data does not dictate your choice (as explained in accepted answer), and speed matters, then you are probably better to use SharedPreferences.

And reading some data is often on the critical path to displaying the main activty so I think speed is often very important.

One final thought regarding speed and efficiency - if you need to use an Sqlite database for some structured data then it is probably more efficient to also store user preferences in the database so you are not opening a second file. This is a fairly minor consideration - probably worth consideration only if you need to access both the structured data and preferences before you can display the main activity.

Reeher answered 27/11, 2012 at 2:16 Comment(8)
What about code readability? I think when storing multiple records in SharedPrefs instead of a db table, the code becomes convoluted. Sql syntax is easier to read than looping over SharedPrefs entries...Nominative
Igor, I'd disagree. SharedPreferences are really 1-dimensional, it's very straight-forward to use a preference. For instance, I'm building a stock checking app, I'm simply storing the stock symbols in preferences. I don't need to grab them individually, as I always list all of them, and this is all I do, store or grab. It's so simple, much simpler than using a DB.Cassel
I can not think of a situation where the readability of code gets difficult while the structure of data to be saved do not demand use of a hierarchical database. Even if there is any readability issues it can be solved by using a wrapper class with required functions .Mosa
Can we store multiple key-values in the form of jsonstring data under shared preferences ? Is there a character limit which may truncate my json values ?Gregg
SharedPreferences are loaded into the memory only once (per app process lifecycle) and kept there; after that it's always super fast. So there isn't really any practical performance win by putting SharedPref data into SQLite (just for the sake of avoiding extra SharedPref file access). And by the way you shouldn't put your SQLite stuff into the SharedPrefs; as I said, it's always in memory which might cause you problems (out-of-memory ones).Parlance
Does sqlite consumes more ram than shared preference if we are inserting/updating every 2-3 seconds?Threescore
My (very simplified) analogies for both: SharedPreferences is a Map, SQLite is a List. Both have different use cases.Haggis
What would the right definition of 'big' be in 'nature of data not too big' ?Enjambement
U
26

My take is, it is not about speed or size but the kinds of operation you want to do to your data.

If you plan to do join, sort, and other DB operations on your data then go for Sqlite. An example is sorting data by date.

If you want to map simple values (like int, boolean, String) then use Preferences. DB operations won't work here and needless to say you need to have all the keys. An example is user password or app configuration.

The big temptation to embrace Preferences is when you want to use it to store a flattened POJO (a serialized JSON object) as String. Having such need is actually the sign to use Sqlite. Why ? Because complex data will eventually need complex oprations. Imagine retrieving a specific entry which could be handled by a simple "SELECT ... WHERE id = 1". In Preferences path, this will be a long process from deserializing to iterating the results.

Uncanonical answered 6/4, 2015 at 3:37 Comment(1)
Also, SharedPreferences does not support transactions, so if you need transactions then use SQLite. For example, if the user presses a "log out" button, you may want to clear multiple SharedPreferences key/values at once (e.g. both the user and password keys), so that you're sure that either both keys are unset or both are set.Frightened
R
8
  • For storing huge amount of data, go for SQLite database system. This will allow the user to search for data as well.

  • On the other hand, for storing small amount of data, go for Shared Preferences. In this case, a huge database system is unnecessary. This will allow user to simply save data and load them.

Regulator answered 6/11, 2015 at 7:41 Comment(3)
300 key-value pairs is a huge amount of data? I need to store it exactly.Salsbury
In that case, you should go for SQLite database. Otherwise, it will be hard to manage and retrieve those 300 data.Regulator
But if all keys are known won't it be easier to fetch the data from Shared Preferences?Twink
A
-19

Forget SQLLite forget SharedPreferences, use Realm. A single solution for all your local storage. You can use plain old Java Objects as RealmObjects and store your data there. You can convert selcted queries into JSON files. No need to parse the entire data base. Check this link: https://realm.io/news/introducing-realm/

Afterbirth answered 27/11, 2015 at 10:20 Comment(2)
forget everything you know about slipcovers.Trash
This does not answer the (off-topic) question.Turban

© 2022 - 2024 — McMap. All rights reserved.