When a user logs in to an app I'm developing, the back-end sends back information about the user. I want to persist the information so it can be used in other activities and when there is no network access.
The two main persistence options I'm aware of for Android are SharedPrefereces and SQLite, and I'm trying to determine which would be more appropriate for my use case. There are three requirements:
- The data to store are mostly a small number of primitive data types or simple reference types, but an array or an object of a derived type may also need to be stored.
- Reading and writing the data should be as simple as possible.
- Data that is written must be available on any subsequent read.
Here is my attempt to compare SharedPreferences and SQLite along these dimensions. (Note that there are other questions on StackOverflow that ask for comparisons of SharedPreferences and SQLite -- "Pros and Cons of SQLite and Shared Preferences", "Saving data on Android : File Storage vs SQLite Database vs Shared Preferences" -- but the answers do not address all three dimensions.)
SharedPreferences
- Works most naturally with primitive and simple reference types, but GSON can be used to store data of any type.
- Data can be written and read from the UI thread.
- Due to a race condition, there is no guarantee that data written to SharedPreferences will be available on any subsequent read.
SQLite
- Can be used in a natural way to store structured data of any degree of complexity.
- Data should be written and read in a thread separate from the UI thread.
- Using a singleton DatabaseHelper guarantees that data written to the database will be available on any subsequent read.
If my assessment is correct, it looks like the SharedPreferences race condition means I have to use SQLite instead to satisfy the requirements even though doing so is more involved. But is my assessment correct?