This article translated from: http://developer.android.com/guide/topics/data/data-storage.html
Android provides several optional solutions for persistent data storage. The specific solution depends on your specific needs, such as whether the data is private to your application or accessible to other applications (and users, and the space required by the data.
The following are available storage solutions:
Shared preferences
Store private raw data in the form of key-value pairs.
Internal Storage
Store private data in the device memory.
External Storage
Store public data on shared external storage
SQLite Databases
Store structured data in a private database
Network Connection
Use your network server to save data on the web.
To expose your data (even private data) to other applications, Android provides a method to use content provider. Content
Provider is an optional component that exposes read/write access to your application data and imposes any restrictions on it. For more information about using the conent provider, see the content providers documentation.
Use shared preferences
SharedpreferencesClass provides a general framework that allows you to save and obtain persistent key-value pairs of the original data type. You can use
SharedpreferencesTo save any original data types: Boolean, float, Int, long, and string. This type of data is stored across user sessions (even if your application is killed ).
Use either of the following methods to obtain
SharedpreferencesObject:
1.
Getsharedpreferences ()---
If you need to obtain multiple preferences files by name identifiers, use this method. The first parameter of this method specifies the preferences file name.
2.
Getpreferences ()---
If you only need a preferences file for your activity, please use this method, because this method is only for your activity's preferences file, you do not need to provide a name.
Data storage method:
1. Call the Edit () method to obtain sharedpreferences. EditorObject;
2. Use putboolean ()And
Putstring ()Method to add values;
3. Use the Commit () method to submit new values.
Use getboolean ()And
Getstring ()To read data.
In the following example, the mute button preference of the calculator application is saved:
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 ();
// We need an editor object to make preference changes.
// All objects are from Android. Context. Context
Sharedpreferences settings = getsharedpreferences (prefs_name, 0 );
Sharedpreferences. Editor editor = settings. Edit ();
Editor. putboolean ("silentmode", msilentmode );
// Commit the edits!
Editor. Commit ();
}
}