SlideShare a Scribd company logo
Busy Android Developer's Guide to Peristence Ted Neward Neward & Associates http://www.tedneward.com | ted@tedneward.com
Credentials Who is this guy? Architectural Consultant, Neudesic Software Principal, Architect, Consultant and Mentor ask me how I can help your project or your team Microsoft MVP (F#, C#, Architect) JSR 175, 277 Expert Group Member Author Professional F# 2.0 (w/Erickson, et al; Wrox, 2010) Effective Enterprise Java (Addison-Wesley, 2004) C# In a Nutshell (w/Drayton, et all; OReilly, 2003) SSCLI Essentials (w/Stutz, et al; OReilly, 2003) Server-Based Java Programming (Manning, 2000) Blog: http://blogs.tedneward.com Papers: http://www.tedneward.com/writings Twitter: @tedneward
Preferences Android SharedPreferences essentially, an XML file stored in your app's data area as such, it's probably the easiest to use ... ... but it has the usual limitations of XML usage is pretty straightforward Activity.getPreferences() to return a SharedPreferences object MODE_PRIVATE makes the prefs invisible to all but this app MODE_WORLD_READABLE/WRITEABLE allows other apps access to view existing data, call get*() to change, call edit() first, then put*()s, then commit() to write
Preferences public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); settings.edit().putBoolean("silentMode", true).commit(); // ... or break it up into three steps if you prefer } }
File I/O Android exposes the filesystem to standard Java I/O Two major categories of storage: internal storage ... and external storage (which may or may not be actually removable) Beyond where the files are stored, there's no real difference except that external storage can disappear at any time, isn't secure, and can be read over the USB cable Any sort of file storage is possible from here so anything that takes a File is a candidate for use
File I/O "Internal storage": storage permanent to the device use openFileOutput() to return a java.io.FileOutputStream use openFileInput() for a java.io.FileInputStream both use MODE_PRIVATE, MODE_APPEND, MODE_WORLD_READABLE/WRITEABLE getFilesDir() returns File for app's internal storage directory deleteFile(), fileList()
File I/O "Cached" data is a little different getCacheDir() returns a File to the "cache" directory Android feels free to delete this data in low-storage scenarios but Android docs suggest not to rely on this; police yourself
File I/O "External storage": removable storage (SD cards) API 7 and earlier getExternalStorageState() tells us SD card state getExternalStorageDirectory() returns a java.io.File for the directory Files that should be shared go in a slightly different place from getExternalStorageDirectory(), store to Music/, Podcasts/, Ringtones/, Alarms/, Notifications/, Pictures/, Movies/, or Downloads/
File I/O "External storage": removable storage (SD cards) API 8 and later getExternalStorageState() tells us SD card state getExternalFilesDir() returns a java.io.File for the directory Files that should be sharde go in a slightly different place getExternalStoragePublicDirectory(), passing in DIRECTORY_MUSIC, DIRECTORY_RINGTONES, etc
SQLite SQLite is a small-scale footprint RDBMS ".. a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." http://www.sqlite.org Mostly SQL-92 compliant, but there are a few SQLisms unsupported: RIGHT and FULL OUTER JOIN Complete ALTER TABLE support Complete trigger support Writing to VIEWs GRANT and REVOKE Storage is single-file database, stored locally
SQLite Android supports SQLite (android.database.sqlite) SQLiteDatabase: core class for all things SQLite openDatabase() or openOrCreateDatabase() beginTransaction(), endTransaction() insert(), delete(), update(), replace(), query() execSQL() queries return either a "projection" (String[]) or a Cursor object either can generally be bound to a View Adapter ... or you can manually iterate/bind
SQLite Android convenience classes SQLiteOpenHelper: extend this to receive "events" about the database onCreate() onUpgrade() onOpen() provide a database name, and a version (to super()) SQLiteStatement: precompiled SQL for fast reuse essentially, a JDBC PreparedStatement
SQLite Android SDK ships with sqlite3 tool SQL console to SQLite files on device generally you use adb to open a shell, then sqlite3: $ adb -s emulator-5554 shell # sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db SQLite version 3.3.12 Enter ".help" for instructions .... enter commands, then quit... sqlite> .exit
db4o db4o is a small-footprintobject database http://www.db4o.com object database means no mapping files no ORM, no impedance mismatch, no external schema... simply define POJOs (no annotations required, even)
db4o Opening the database ObjectContainer db = null; try { db = Db4o.openFile("mydata.db4o"); // . . . } catch (Exception ex) { // Do more than just log the exception, please } finally {  if (db != null) db.close(); }
db4o Storing an object // Create the new Person Person p = new Person("Matthew", "Neward", 13, new Address(...)); // Store db.set(p); db.commit();
db4o Fetching an object (prototype-based) // Fetch all the Persons ObjectSet persons =  // use empty/default object (all fields hold null/0 values) db.get(new Person()); // or could use type parameter:  // db.get(Person.class); while (persons.hasNext()) System.out.println(persons.next()); // Fetch all the Newards ObjectSet newards = db.get(new Person(null, "Neward", 0, null); while (newards.hasNext()) System.out.println(newards.next());
db4o Updating an object // Fetch Matthew Neward (note the absence of error-checking) Person matthew = (Person) db.get(new Person("Matthew", "Neward", 0, null).next(); // Happy Birthday! matthew.setAge(matthew.getAge() + 1); // Store db.set(matthew); db.commit();
db4o db4o provides more functionality than just what's shown here Native queries Automatic reference retrieval ("fetch depth") Native refactoring support Store to memory or to disk (or across the network) Transactions model ... and more
Wrapping up "What do you know?"
Summary Android provides a local-storage option ... that offers the traditional storage options ... that can be customized in many ways ... that ultimately will only get more powerful
Resources Busy Coder's Guide to Android (and more) Mark Murphy, http://www.commonsware.com Android website http://developer.android.com Presentations by this guy Busy Android Dev's Guide to UI Busy Android Dev's Guide to Communication ... and more

More Related Content

What's hot (20)

PPTX
Jsoup Tutorial for Beginners - Javatpoint
JavaTpoint.Com
 
PPTX
Spring data jpa
Jeevesh Pandey
 
PDF
Writing Swift code with great testability
John Sundell
 
PDF
Softshake - Offline applications
jeromevdl
 
PPTX
Jsoup tutorial
Ramakrishna kapa
 
PDF
Oracle forensics 101
fangjiafu
 
PDF
ORM Injection
Simone Onofri
 
PDF
The Beauty And The Beast Php N W09
Bastian Feder
 
PDF
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
PPTX
10 sharing files and data in windows phone 8
WindowsPhoneRocks
 
PPT
Ant
sundar22in
 
PPTX
What's Parse
Tsutomu Ogasawara
 
ODP
Zend Framework 1.9 Setup & Using Zend_Tool
Gordon Forsythe
 
PDF
ERRest - The Next Steps
WO Community
 
PPTX
Fixing the Java Serialization Mess
Salesforce Engineering
 
PDF
ERRest - Designing a good REST service
WO Community
 
PPT
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
PDF
ORM2Pwn: Exploiting injections in Hibernate ORM
Mikhail Egorov
 
PDF
ERRest in Depth
WO Community
 
PDF
Brief introduction of Slick
Knoldus Inc.
 
Jsoup Tutorial for Beginners - Javatpoint
JavaTpoint.Com
 
Spring data jpa
Jeevesh Pandey
 
Writing Swift code with great testability
John Sundell
 
Softshake - Offline applications
jeromevdl
 
Jsoup tutorial
Ramakrishna kapa
 
Oracle forensics 101
fangjiafu
 
ORM Injection
Simone Onofri
 
The Beauty And The Beast Php N W09
Bastian Feder
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
10 sharing files and data in windows phone 8
WindowsPhoneRocks
 
What's Parse
Tsutomu Ogasawara
 
Zend Framework 1.9 Setup & Using Zend_Tool
Gordon Forsythe
 
ERRest - The Next Steps
WO Community
 
Fixing the Java Serialization Mess
Salesforce Engineering
 
ERRest - Designing a good REST service
WO Community
 
Testing persistence in PHP with DbUnit
Peter Wilcsinszky
 
ORM2Pwn: Exploiting injections in Hibernate ORM
Mikhail Egorov
 
ERRest in Depth
WO Community
 
Brief introduction of Slick
Knoldus Inc.
 

Viewers also liked (20)

PDF
2005 Summer Newsletter
Direct Relief
 
PDF
2004 Winter Newsletter
Direct Relief
 
PDF
I danni del fumo sono dovuti ai radicali liberi: è possibile contrastarli per...
CreAgri Europe
 
PPT
Presentazione di CreAgri Europe
CreAgri Europe
 
PDF
Brochure
sriraminenifoods
 
PPS
Theballproject inspire
Rohit Dsouza
 
PDF
Intro to OpenStack - Scott Sanchez and Niki Acosta
Scott Sanchez
 
PPSX
DROGUERIA LIZBETH2
johanitalabonita
 
PPTX
Kepercayaan pelajar terhadap pembelajaran matematik
Ñûrãzwã Šãlěh
 
PPTX
BTD2015 - Your Place In DevTOps is Finding Solutions - Not Just Bugs!
Andreas Grabner
 
PDF
2010 Fall Newsletter
Direct Relief
 
PPT
Apostas desportivas betclic portugal
Tristanwalker
 
PDF
Hum2220 0915 syllabus
ProfWillAdams
 
PDF
Java Tech & Tools | Grails in the Java Enterprise | Peter Ledbrook
JAX London
 
PPT
Pencemaran air
bungachinta
 
DOCX
8 instrumento autoeficacia grupo 8
Luis Aracas
 
PPTX
Magna carta
vdub1994
 
PPTX
MorenoMassip_Avi
alanmorenomassip
 
PPT
Robin hood
Alejandra Solano
 
PDF
Poultry Planner July 2012
Manish Arora
 
2005 Summer Newsletter
Direct Relief
 
2004 Winter Newsletter
Direct Relief
 
I danni del fumo sono dovuti ai radicali liberi: è possibile contrastarli per...
CreAgri Europe
 
Presentazione di CreAgri Europe
CreAgri Europe
 
Theballproject inspire
Rohit Dsouza
 
Intro to OpenStack - Scott Sanchez and Niki Acosta
Scott Sanchez
 
DROGUERIA LIZBETH2
johanitalabonita
 
Kepercayaan pelajar terhadap pembelajaran matematik
Ñûrãzwã Šãlěh
 
BTD2015 - Your Place In DevTOps is Finding Solutions - Not Just Bugs!
Andreas Grabner
 
2010 Fall Newsletter
Direct Relief
 
Apostas desportivas betclic portugal
Tristanwalker
 
Hum2220 0915 syllabus
ProfWillAdams
 
Java Tech & Tools | Grails in the Java Enterprise | Peter Ledbrook
JAX London
 
Pencemaran air
bungachinta
 
8 instrumento autoeficacia grupo 8
Luis Aracas
 
Magna carta
vdub1994
 
MorenoMassip_Avi
alanmorenomassip
 
Robin hood
Alejandra Solano
 
Poultry Planner July 2012
Manish Arora
 
Ad

Similar to Android | Busy Java Developers Guide to Android: Persistence | Ted Neward (20)

PPT
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
PDF
Modern JavaScript Programming
Wildan Maulana
 
PPT
Data Storage In Android
Aakash Ugale
 
PDF
大規模サイトにおけるユーザーレベルのキャッシュ活用によるパフォーマンスチューニング
Yoshikazu Aoyama
 
PPT
Demystifying Maven
Mike Desjardins
 
KEY
Open Atrium (DrupalCon Paris 2009, Day 3)
Cameron Eagans
 
PPTX
Java Technology
ifnu bima
 
PDF
Persitance Data with sqlite
Arif Huda
 
PPT
CLR Exception Handing And Memory Management
Shiny Zhu
 
PPT
Sqllite
Senthil Kumar
 
PPT
Xml Java
cbee48
 
KEY
node.js: Javascript's in your backend
David Padbury
 
ODP
Bring the fun back to java
ciklum_ods
 
PPT
Code Documentation. That ugly thing...
Christos Manios
 
PDF
PHP
webhostingguy
 
PDF
php-and-zend-framework-getting-started
tutorialsruby
 
PDF
php-and-zend-framework-getting-started
tutorialsruby
 
PDF
php-and-zend-framework-getting-started
tutorialsruby
 
PDF
php-and-zend-framework-getting-started
tutorialsruby
 
PDF
Drupal 8 and iOS - an Open Source App
littleMAS
 
Architecture | Busy Java Developers Guide to NoSQL | Ted Neward
JAX London
 
Modern JavaScript Programming
Wildan Maulana
 
Data Storage In Android
Aakash Ugale
 
大規模サイトにおけるユーザーレベルのキャッシュ活用によるパフォーマンスチューニング
Yoshikazu Aoyama
 
Demystifying Maven
Mike Desjardins
 
Open Atrium (DrupalCon Paris 2009, Day 3)
Cameron Eagans
 
Java Technology
ifnu bima
 
Persitance Data with sqlite
Arif Huda
 
CLR Exception Handing And Memory Management
Shiny Zhu
 
Sqllite
Senthil Kumar
 
Xml Java
cbee48
 
node.js: Javascript's in your backend
David Padbury
 
Bring the fun back to java
ciklum_ods
 
Code Documentation. That ugly thing...
Christos Manios
 
php-and-zend-framework-getting-started
tutorialsruby
 
php-and-zend-framework-getting-started
tutorialsruby
 
php-and-zend-framework-getting-started
tutorialsruby
 
php-and-zend-framework-getting-started
tutorialsruby
 
Drupal 8 and iOS - an Open Source App
littleMAS
 
Ad

More from JAX London (20)

PDF
Java Tech & Tools | Continuous Delivery - the Writing is on the Wall | John S...
JAX London
 
ODP
Java Tech & Tools | Mapping, GIS and Geolocating Data in Java | Joachim Van d...
JAX London
 
PDF
Keynote | Middleware Everywhere - Ready for Mobile and Cloud | Dr. Mark Little
JAX London
 
PDF
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
JAX London
 
PDF
Spring Day | Behind the Scenes at Spring Batch | Dave Syer
JAX London
 
PDF
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
JAX London
 
PDF
Spring Day | Identity Management with Spring Security | Dave Syer
JAX London
 
PDF
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
PDF
Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
JAX London
 
PPT
Keynote | The Rise and Fall and Rise of Java | James Governor
JAX London
 
ODP
Java Tech & Tools | OSGi Best Practices | Emily Jiang
JAX London
 
PPTX
Java Tech & Tools | Beyond the Data Grid: Coherence, Normalisation, Joins and...
JAX London
 
PDF
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
JAX London
 
PDF
Java Tech & Tools | Social Media in Programming in Java | Khanderao Kand
JAX London
 
PDF
Java Tech & Tools | Just Keep Passing the Message | Russel Winder
JAX London
 
PDF
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
JAX London
 
ODP
Java EE | Modular EJBs for Enterprise OSGi | Tim Ward
JAX London
 
PDF
Java EE | Apache TomEE - Java EE Web Profile on Tomcat | Jonathan Gallimore
JAX London
 
KEY
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
JAX London
 
PDF
Java Core | Java 8 and OSGi Modularisation | Tim Ellison & Neil Bartlett
JAX London
 
Java Tech & Tools | Continuous Delivery - the Writing is on the Wall | John S...
JAX London
 
Java Tech & Tools | Mapping, GIS and Geolocating Data in Java | Joachim Van d...
JAX London
 
Keynote | Middleware Everywhere - Ready for Mobile and Cloud | Dr. Mark Little
JAX London
 
Spring Day | WaveMaker - Spring Roo - SpringSource Tool Suite: Choosing the R...
JAX London
 
Spring Day | Behind the Scenes at Spring Batch | Dave Syer
JAX London
 
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
JAX London
 
Spring Day | Identity Management with Spring Security | Dave Syer
JAX London
 
Spring Day | Spring and Scala | Eberhard Wolff
JAX London
 
Spring Day | Data Access 2.0? Please Welcome Spring Data! | Oliver Gierke
JAX London
 
Keynote | The Rise and Fall and Rise of Java | James Governor
JAX London
 
Java Tech & Tools | OSGi Best Practices | Emily Jiang
JAX London
 
Java Tech & Tools | Beyond the Data Grid: Coherence, Normalisation, Joins and...
JAX London
 
Java Tech & Tools | Big Blobs: Moving Big Data In and Out of the Cloud | Adri...
JAX London
 
Java Tech & Tools | Social Media in Programming in Java | Khanderao Kand
JAX London
 
Java Tech & Tools | Just Keep Passing the Message | Russel Winder
JAX London
 
Java Tech & Tools | Deploying Java & Play Framework Apps to the Cloud | Sande...
JAX London
 
Java EE | Modular EJBs for Enterprise OSGi | Tim Ward
JAX London
 
Java EE | Apache TomEE - Java EE Web Profile on Tomcat | Jonathan Gallimore
JAX London
 
Java Core | Understanding the Disruptor: a Beginner's Guide to Hardcore Concu...
JAX London
 
Java Core | Java 8 and OSGi Modularisation | Tim Ellison & Neil Bartlett
JAX London
 

Recently uploaded (20)

PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 

Android | Busy Java Developers Guide to Android: Persistence | Ted Neward

  • 1. Busy Android Developer's Guide to Peristence Ted Neward Neward & Associates http://www.tedneward.com | [email protected]
  • 2. Credentials Who is this guy? Architectural Consultant, Neudesic Software Principal, Architect, Consultant and Mentor ask me how I can help your project or your team Microsoft MVP (F#, C#, Architect) JSR 175, 277 Expert Group Member Author Professional F# 2.0 (w/Erickson, et al; Wrox, 2010) Effective Enterprise Java (Addison-Wesley, 2004) C# In a Nutshell (w/Drayton, et all; OReilly, 2003) SSCLI Essentials (w/Stutz, et al; OReilly, 2003) Server-Based Java Programming (Manning, 2000) Blog: http://blogs.tedneward.com Papers: http://www.tedneward.com/writings Twitter: @tedneward
  • 3. Preferences Android SharedPreferences essentially, an XML file stored in your app's data area as such, it's probably the easiest to use ... ... but it has the usual limitations of XML usage is pretty straightforward Activity.getPreferences() to return a SharedPreferences object MODE_PRIVATE makes the prefs invisible to all but this app MODE_WORLD_READABLE/WRITEABLE allows other apps access to view existing data, call get*() to change, call edit() first, then put*()s, then commit() to write
  • 4. Preferences public class Calc extends Activity { public static final String PREFS_NAME = "MyPrefsFile"; @Override protected void onCreate(Bundle state){ super.onCreate(state); . . . // Restore preferences SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); boolean silent = settings.getBoolean("silentMode", false); setSilent(silent); } @Override protected void onStop(){ super.onStop(); SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); settings.edit().putBoolean("silentMode", true).commit(); // ... or break it up into three steps if you prefer } }
  • 5. File I/O Android exposes the filesystem to standard Java I/O Two major categories of storage: internal storage ... and external storage (which may or may not be actually removable) Beyond where the files are stored, there's no real difference except that external storage can disappear at any time, isn't secure, and can be read over the USB cable Any sort of file storage is possible from here so anything that takes a File is a candidate for use
  • 6. File I/O "Internal storage": storage permanent to the device use openFileOutput() to return a java.io.FileOutputStream use openFileInput() for a java.io.FileInputStream both use MODE_PRIVATE, MODE_APPEND, MODE_WORLD_READABLE/WRITEABLE getFilesDir() returns File for app's internal storage directory deleteFile(), fileList()
  • 7. File I/O "Cached" data is a little different getCacheDir() returns a File to the "cache" directory Android feels free to delete this data in low-storage scenarios but Android docs suggest not to rely on this; police yourself
  • 8. File I/O "External storage": removable storage (SD cards) API 7 and earlier getExternalStorageState() tells us SD card state getExternalStorageDirectory() returns a java.io.File for the directory Files that should be shared go in a slightly different place from getExternalStorageDirectory(), store to Music/, Podcasts/, Ringtones/, Alarms/, Notifications/, Pictures/, Movies/, or Downloads/
  • 9. File I/O "External storage": removable storage (SD cards) API 8 and later getExternalStorageState() tells us SD card state getExternalFilesDir() returns a java.io.File for the directory Files that should be sharde go in a slightly different place getExternalStoragePublicDirectory(), passing in DIRECTORY_MUSIC, DIRECTORY_RINGTONES, etc
  • 10. SQLite SQLite is a small-scale footprint RDBMS ".. a software library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine." http://www.sqlite.org Mostly SQL-92 compliant, but there are a few SQLisms unsupported: RIGHT and FULL OUTER JOIN Complete ALTER TABLE support Complete trigger support Writing to VIEWs GRANT and REVOKE Storage is single-file database, stored locally
  • 11. SQLite Android supports SQLite (android.database.sqlite) SQLiteDatabase: core class for all things SQLite openDatabase() or openOrCreateDatabase() beginTransaction(), endTransaction() insert(), delete(), update(), replace(), query() execSQL() queries return either a "projection" (String[]) or a Cursor object either can generally be bound to a View Adapter ... or you can manually iterate/bind
  • 12. SQLite Android convenience classes SQLiteOpenHelper: extend this to receive "events" about the database onCreate() onUpgrade() onOpen() provide a database name, and a version (to super()) SQLiteStatement: precompiled SQL for fast reuse essentially, a JDBC PreparedStatement
  • 13. SQLite Android SDK ships with sqlite3 tool SQL console to SQLite files on device generally you use adb to open a shell, then sqlite3: $ adb -s emulator-5554 shell # sqlite3 /data/data/com.example.google.rss.rssexample/databases/rssitems.db SQLite version 3.3.12 Enter ".help" for instructions .... enter commands, then quit... sqlite> .exit
  • 14. db4o db4o is a small-footprintobject database http://www.db4o.com object database means no mapping files no ORM, no impedance mismatch, no external schema... simply define POJOs (no annotations required, even)
  • 15. db4o Opening the database ObjectContainer db = null; try { db = Db4o.openFile("mydata.db4o"); // . . . } catch (Exception ex) { // Do more than just log the exception, please } finally { if (db != null) db.close(); }
  • 16. db4o Storing an object // Create the new Person Person p = new Person("Matthew", "Neward", 13, new Address(...)); // Store db.set(p); db.commit();
  • 17. db4o Fetching an object (prototype-based) // Fetch all the Persons ObjectSet persons = // use empty/default object (all fields hold null/0 values) db.get(new Person()); // or could use type parameter: // db.get(Person.class); while (persons.hasNext()) System.out.println(persons.next()); // Fetch all the Newards ObjectSet newards = db.get(new Person(null, "Neward", 0, null); while (newards.hasNext()) System.out.println(newards.next());
  • 18. db4o Updating an object // Fetch Matthew Neward (note the absence of error-checking) Person matthew = (Person) db.get(new Person("Matthew", "Neward", 0, null).next(); // Happy Birthday! matthew.setAge(matthew.getAge() + 1); // Store db.set(matthew); db.commit();
  • 19. db4o db4o provides more functionality than just what's shown here Native queries Automatic reference retrieval ("fetch depth") Native refactoring support Store to memory or to disk (or across the network) Transactions model ... and more
  • 20. Wrapping up "What do you know?"
  • 21. Summary Android provides a local-storage option ... that offers the traditional storage options ... that can be customized in many ways ... that ultimately will only get more powerful
  • 22. Resources Busy Coder's Guide to Android (and more) Mark Murphy, http://www.commonsware.com Android website http://developer.android.com Presentations by this guy Busy Android Dev's Guide to UI Busy Android Dev's Guide to Communication ... and more