Share
Embed
Android Data
Android gives you several options to store your data, and the Android community gives you even more. This talk will cover the many different data storage options available to you and the reasons you might choose one over the other. We'll look at implementation details, common pitfalls, and examples of how you might use each in the real world.
Michael Pardo
September 21, 2014
Transcript
107 slides
-
SharedPreferences • Stores key-value pairs as XML • Good for
a relatively small collection • Primitive data types only -
Real-world uses • Game item inventory • Application state •
User preferences -
// Provide a name for the preferences file name SharedPreferences
prefs = getSharedPreferences( PREFS_NAME, Context.MODE_PRIVATE); -
// Uses the activity's class name as the preferences file
name SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); -
// Uses the activity's class name as the preferences file
name SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); ! // Same as above SharedPreferences prefs = getSharedPreferences( activity.getLocalClassName(), Context.MODE_PRIVATE); -
// Use package name as the preferences file name SharedPreferences
prefs = PreferenceManager.getDefaultSharedPreferences( context); -
// Use package name as the preferences file name SharedPreferences
prefs = PreferenceManager.getDefaultSharedPreferences( context); ! // Same as above SharedPreferences prefs = getSharedPreferences( getPackageName() + "_preferences", Context.MODE_PRIVATE); -
// Get instance of SharedPreferences SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); !
// Retrieve stored value boolean firstRun = prefs.getBoolean("firstRun", true); -
// Get instance of SharedPreferences SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); !
// Retrieve stored value boolean firstRun = prefs.getBoolean("firstRun", true); ! if (firstRun) { // Get instance of editor and persist value SharedPreferences.Editor editor = prefs.edit(); editor.putInt("firstRun", false); editor.commit(); } -
Complex Preferences // Get instance of ComplexPreferences ComplexPreferences prefs =
ComplexPreferences.getComplexPreferences( this, PREFS_NAME, Context.MODE_PRIVATE); -
Complex Preferences // Get instance of ComplexPreferences ComplexPreferences prefs =
ComplexPreferences.getComplexPreferences( this, PREFS_NAME, Context.MODE_PRIVATE); ! // Persist Inventory prefs.putObject("inventory", inventory); prefs.commit(); -
Complex Preferences // Get instance of ComplexPreferences ComplexPreferences prefs =
ComplexPreferences.getComplexPreferences( this, PREFS_NAME, Context.MODE_PRIVATE); ! // Persist Inventory prefs.putObject("inventory", inventory); prefs.commit(); ! // Retrieve Inventory Inventory inventory = prefs.getObject("inventory", Inventory.class); -
SimpleSharedPreferences // Create instance of SimpleSharedPrefernces SimpleSharedPreferences prefs = new
SimpleSharedPreferences(context); -
SimpleSharedPreferences // Create instance of SimpleSharedPrefernces SimpleSharedPreferences prefs = new
SimpleSharedPreferences(context); ! // Retrieve stored value boolean firstRun = prefs.getBoolean("firstRun", true); -
SimpleSharedPreferences // Create instance of SimpleSharedPrefernces SimpleSharedPreferences prefs = new
SimpleSharedPreferences(context); ! // Retrieve stored value boolean firstRun = prefs.getBoolean("firstRun", true); ! if (firstRun) { // Persist value prefs.putBoolean("firstRun", false); } -
Typed Preferences // Get instance of SharedPreferences SharedPreferences prefs =
getPreferences(Context.MODE_PRIVATE); -
Typed Preferences // Get instance of SharedPreferences SharedPreferences prefs =
getPreferences(Context.MODE_PRIVATE); ! // Create instance of BooleanPreference BooleanPreference firstRun = new BooleanPreference(prefs, "firstRun", true); -
Typed Preferences // Get instance of SharedPreferences SharedPreferences prefs =
getPreferences(Context.MODE_PRIVATE); ! // Create instance of BooleanPreference BooleanPreference firstRun = new BooleanPreference(prefs, "firstRun", true); ! // Retrieve stored value if (firstRun.get()) { // Persist value firstRun.set(true); } -
Ease of Use Complexity of Data Amount of Data SharedPreferences
Filesystem SQLite -
Filesystem • Same as Java I/O API • Good for
large amounts of data • Internal and external storage -
Internal Storage • Always available • Privately accessible by default
• All files removed from internal storage upon uninstallation -
External Storage • Not always available • Publicly accessible •
All files removed from getExternalFilesDir() upon uninstallation -
Real-world uses • API request cache • Game state object
• Edited images -
JSONObject gameState = game.getState(); ! String fileName = "game_state.json"; String
fileContents = gameState.toString(); ! // Use context.openFileOutput() to open an output stream FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE); ! fos.write(fileContents.getBytes()); fos.close(); -
JSONObject gameState = game.getState(); ! String fileName = "game_state.json"; String
fileContents = gameState.toString(); ! // Use context.getFilesDir() to open an output stream FileOutputStream fos = new FileOutputStream(new File(getFilesDir(), fileName)); ! fos.write(fileContents.getBytes()); fos.close(); -
<!-- Read permission is implicit. --> <manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/> ... </manifest> ! ! <!-- Will be required in a future release, but not at the moment. --> <manifest ...> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ... </manifest> -
public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED);
} ! public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY); } -
context.openFileOutput(String name, int mode); ! context.openFileInput(String name); ! context.getFileStreamPath(String name);
! context.getFilesDir(); ! context.getCacheDir(); ! Environment.getDownloadCacheDirectory(); ! Environment.getExternalStorageDirectory(); ! Environment.getExternalStoragePublicDirectory(String type); ! Environment.getExternalStorageState(); -
Apache Commons IO // Get URL content InputStream in =
new URL( "http://developer.android.com" ).openStream(); try { String html = IOUtils.toString(in); } finally { IOUtils.closeQuietly(in); } -
Apache Commons IO // Get file lines File file =
new File(getFilesDir() , "todo.txt"); List<String> lines = FileUtils.readLines(file, "UTF-8"); -
Apache Commons IO String filename = "/data/data/com.michaelpardo.app/cache/../todo.txt"; String normalized =
FilenameUtils.normalize(filename); // result is "/data/data/com.michaelpardo.app/todo.txt" -
Guava // Read the lines of a UTF-8 text file
ImmutableList<String> lines = Files.asCharSource(file, Charsets.UTF_8) .readLines(); -
Guava // Count distinct word occurrences in a file Multiset<String>
wordOccurrences = HashMultiset.create( Splitter.on(CharMatcher.WHITESPACE) .trimResults() .omitEmptyStrings() .split(Files.asCharSource(file, Charsets.UTF_8).read())); -
Guava // Copy the data from a URL to a
file Resources.asByteSource(url).copyTo(Files.asByteSink(file)); -
Ease of Use Complexity of Data Amount of Data SharedPreferences
Filesystem SQLite -
SQLite • SQL database engine • Good for structured, relational
data • A lot of boilerplate -
Real-world uses • Address book • Restaurant ordering system •
Product inventory -
public final class PostContract { public PostContract() {} ! public
static abstract class Post implements BaseColumns { public static final String TABLE_NAME = "posts"; public static final String COLUMN_NAME_TITLE = "title"; public static final String COLUMN_NAME_AUTHOR_ID = “author_id"; ... } } -
public class PostsDbHelper extends SQLiteOpenHelper { public static final int
DATABASE_VERSION = 1; public static final String DATABASE_NAME = "Posts.db"; ! public FeedReaderDbHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } ! public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } ! public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(SQL_DELETE_ENTRIES); onCreate(db); } ! public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } } -
// Create instance of database helper PostsDbHelper mDbHelper = new
PostsDbHelper(getContext()); -
// Create instance of database helper PostsDbHelper mDbHelper = new
PostsDbHelper(getContext()); ! // Get writable database SQLiteDatabase db = mDbHelper.getWritableDatabase(); -
// Create array of columns to retrieve String[] projection =
{ Post._ID, Post.COLUMN_NAME_TITLE, ... }; -
// Create array of columns to retrieve String[] projection =
{ Post._ID, Post.COLUMN_NAME_TITLE, ... }; ! // Retrieve cursor Cursor c = db.query( Post.TABLE_NAME, projection, selection, selectionArgs, null, // groupBy null, // having null, // orderBy null // limit ); -
// Move to first row cursor.moveToFirst(); ! // Get column
index int index = cursor.getColumnIndexOrThrow(Post._ID); -
// Move to first row cursor.moveToFirst(); ! // Get column
index int index = cursor.getColumnIndexOrThrow(Post._ID); ! // Get column value long id = cursor.getLong(index); -
// Move to first row cursor.moveToFirst(); ! // Get column
index int index = cursor.getColumnIndexOrThrow(Post._ID); ! // Get column value long id = cursor.getLong(index); ! // Close cursor when finished cursor.close(); -
// Create instance of ContentValues and set values ContentValues values
= new ContentValues(); values.put(Post.COLUMN_NAME_TITLE, title); values.put(Post.COLUMN_NAME_AUTHOR_ID, authorId); -
// Create instance of ContentValues and set values ContentValues values
= new ContentValues(); values.put(Post.COLUMN_NAME_TITLE, title); values.put(Post.COLUMN_NAME_AUTHOR_ID, authorId); ! // Insert row using ContentValues long newRowId = db.insert( Post.TABLE_NAME, null, values ); -
// Create instance of ContentValues and set values ContentValues values
= new ContentValues(); values.put(Post.COLUMN_NAME_AUTHOR_ID, authorId); -
// Create instance of ContentValues and set values ContentValues values
= new ContentValues(); values.put(Post.COLUMN_NAME_AUTHOR_ID, authorId); ! // Create selection definition String selection = Post.COLUMN_NAME_AUTHOR_ID + " LIKE ?"; String[] selectionArgs = { String.valueOf(oldAuthorId) }; -
// Create instance of ContentValues and set values ContentValues values
= new ContentValues(); values.put(Post.COLUMN_NAME_AUTHOR_ID, authorId); ! // Create selection definition String selection = Post.COLUMN_NAME_AUTHOR_ID + " LIKE ?"; String[] selectionArgs = { String.valueOf(oldAuthorId) }; ! // Update rows using ContentValues and selection int count = db.update( Post.TABLE_NAME, values, selection, selectionArgs ); -
// Create selection definition String selection = Post.COLUMN_NAME_AUTHOR_ID + "
LIKE ?"; String[] selectionArgs = { String.valueOf(authorId) }; -
// Create selection definition String selection = Post.COLUMN_NAME_AUTHOR_ID + "
LIKE ?"; String[] selectionArgs = { String.valueOf(authorId) }; ! // Delete rows using selection db.delete( Post.TABLE_NAME, selection, selectionArgs ); -
ActiveAndroid @Table("posts") public class Post extends Model { @Column("title") String
mTitle; @Column("author") User mAuthor; ... } -
ActiveAndroid // Query List<Post> posts = new Select().from(Post.class).execute(); ! //
Save or update Post post = new Post(); post.setTitle("ActiveAndroid"); post.setAuthor(user); post.save(); -
ActiveAndroid // Query List<Post> posts = new Select().from(Post.class).execute(); ! //
Save or update Post post = new Post(); post.setTitle("ActiveAndroid"); post.setAuthor(user); post.save(); ! // Delete post.delete(); -
greenDAO Schema schema = new Schema(1, "de.greenrobot.posts"); ! Entity post
= schema.addEntity("post"); post.addIdProperty(); post.addStringProperty("title"); ! Property userIdProperty = user.addLongProperty("author").getProperty(); post.addToOne(user, userIdProperty); ! DaoGenerator daoGenerator = new DaoGenerator(); daoGenerator.generateAll(schema, "../MyProject/src-gen"); -
greenDAO // Query List<Post> posts = userDao.queryBuilder().list(); ! // Save
Post post = new Post(); post.setTitle("greenDAO"); post.setAuthor(user); daoSession.insert(post); -
greenDAO // Query List<Post> posts = userDao.queryBuilder().list(); ! // Save
Post post = new Post(); post.setTitle("greenDAO"); post.setAuthor(user); daoSession.insert(post); ! // Update post.setModifiedDate(new Date()); daoSession.update(post); -
greenDAO // Query List<Post> posts = userDao.queryBuilder().list(); ! // Save
Post post = new Post(); post.setTitle("greenDAO"); post.setAuthor(user); daoSession.insert(post); ! // Update post.setModifiedDate(new Date()); daoSession.update(post); ! // Delete daoSession.delete(post); -
OrmLite @DatabaseTable(tableName = "posts") public class Post { @DatabaseField private
String title; @DatabaseField private User author; ... } -
OrmLite // Query List<Post> posts = postDao.queryForAll(); ! // Save
Post post = new Post(); post.setTitle("ORMLite"); post.setAuthor(user); postDao.create(post); -
OrmLite // Query List<Post> posts = postDao.queryForAll(); ! // Save
Post post = new Post(); post.setTitle("ORMLite"); post.setAuthor(user); postDao.create(post); ! // Update post.setModifiedDate(new Date()); postDao.update(post); -
OrmLite // Query List<Post> posts = postDao.queryForAll(); ! // Save
Post post = new Post(); post.setTitle("ORMLite"); post.setAuthor(user); postDao.create(post); ! // Update post.setModifiedDate(new Date()); postDao.update(post); ! // Delete postDao.delete(post); -
SugarORM // Query List<Post> posts = Post.find(Post.class); ! // Save
or update Post post = new Post(); post.setTitle("SugarORM"); post.setAuthor(user); SugarRecord.save(post); -
SugarORM // Query List<Post> posts = Post.find(Post.class); ! // Save
or update Post post = new Post(); post.setTitle("SugarORM"); post.setAuthor(user); SugarRecord.save(post); ! // Delete SugarRecord.delete(post); -
Ease of Use Complexity of Data Amount of Data SharedPreferences
Filesystem SQLite -
Network • File sync or mobile backend • Cross-device storage
• Many storage options • Not always available -
MBaaS Libraries • BaasBox • Helios • DropBox Datastore •
Kinvey • Parse -
BaasBox • Administration console • Users management • Content management
• File management • “Friendship” • DB management • Push notifications • API access management -
Helios • Data synchronization • Push notifications • In-App purchases
• Logging and Analytics • Passbook & Newsstand (iOS) -
Dropbox Datastore • Cloud datastore • Local datastores • Shared
datastores • Push notifications -
Kinvey • Cloud datastore • Local datastore • User management
• File management • Push notifications • Location content • Backend services • Encryption • External data sources -
Parse • Cloud datastore • Local datastore • Social integration
• Push notifications • Analytics -
NoSQL • Key value pairs or documents • Simple design
• Non-relational • Implementations vary -
Couchbase Lite • JSON document store • Full query API
• Server and peer-to-peer replication -
JasDB • JSON document store • Full query API •
REST and native APIs -
SimpleNoSQL • JSON document store • Lightweight functional queries •
Backed by SQLite -
SnappyDB • Key value store • Use primitive type and
array values • Based on Google’s LevelDB • Uses Snappy compression and Kryo serialization -
WaspDB • Key value store • Use complex key and
value types • Uses Kryo serialization -
Easy to use Complex data A lot of data Distributed
SharedPreferences Filesystem SQLite Network NoSQL