-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Persisting Data to the Device
The Android framework offers several options and strategies for persistence:
- Shared Preferences - Easily save basic data as key-value pairs in a private persisted dictionary.
- Local Files - Save arbitrary files to internal or external device storage.
- SQLite Database - Persist data in tables within an application specific database.
- ORM - Describe and persist model objects using a higher level query/update syntax.
Settings can be persisted for your application by using SharedPreferences to persist key-value pairs:
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
String username = pref.getString("username", "n/a");
SharedPreferences can be edited by getting access to the Editor instance:
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
Editor edit = pref.edit();
edit.putString("username", "billy");
edit.putString("user_id", "65");
edit.commit();
Android can read/write files to internal as well as external storage. Applications have access to an application-specific directory where preferences and sqlite databases are also stored. Every Activity has helpers to get the writeable directory. File I/O API is a subset of the normal Java File API.
Writing files is as simple as getting the stream using [openFileOutput
method](http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int) and writing to it using a BufferedWriter:
// Use Activity method to create a file in the writeable directory
FileOutputStream fos = openFileOutput("filename", MODE_WORLD_WRITEABLE);
// Create buffered writer
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
writer.write("Hi, I'm writing stuff");
writer.close();
- http://developer.android.com/guide/topics/data/data-storage.html
- http://developer.android.com/training/basics/data-storage/index.html
- http://mobile.tutsplus.com/tutorials/android/data-management-options-for-android-applications/
- http://developer.android.com/reference/android/content/SharedPreferences.html
Created by CodePath with much help from the community. Contributed content licensed under cc-wiki with attribution required. You are free to remix and reuse, as long as you attribute and use a similar license.
Finding these guides helpful?
We need help from the broader community to improve these guides, add new topics and keep the topics up-to-date. See our contribution guidelines here and our topic issues list for great ways to help out.
Check these same guides through our standalone viewer for a better browsing experience and an improved search. Follow us on twitter @codepath for access to more useful Android development resources.