Storing Objects in Android
by Tony Sicilian on December 20th, 2013 | Filed in: Android Core
One alternative to using SQLite on Android is to store Java objects in SharedPreferences. Here, we’ll look at two different ways to do that.
Why
not go for SQLite for all storage needs? The reasons can be varied:
besides the impedance mismatch between object orientation and relational
databases, SQLite might be overkill (brings more overhead) for some
simple use cases, or its use and syntax might be disliked altogether.
As an example, we’ll work with the following User class:
01 | /** User object to be saved in db */ |
05 | private String userName; |
06 | private boolean registered; |
10 | public User( int id, String userName, boolean registered, double score){ |
12 | this .userName = userName; |
13 | this .registered = registered; |
The unique identifier id would most likely be handed out by our server, though we could also compute it on the device itself once we create a User and store it separately in SharedPreferences, depending on the design of our application. Here, we’ll just use it as an object storage key.
No comments:
Post a Comment