Sunday, December 22, 2013

Storing Objects in Android

Storing Objects in Android

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 */
02public class User{
04    private int id; // used for object storage
05    private String userName;
06    private boolean registered;
07    private double score;
09    /** Constructor */
10   public User(int id, String userName, boolean registered, double score){
11 = id;
12       this.userName = userName;
13       this.registered = registered;
14       this.score = score;
15   }
16   // getters and setters here...
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