> Android provides several options for you to save persistent application data:
1. Shared Preferences
Store data on the web with your own network server.
> Android provides a way for you to expose even your private data to other applications — with a content provider .The SharedPreferences
class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences
to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
To get a SharedPreferences
object for your application, use one of two methods:
getSharedPreferences()
- Use this if you need multiple preferences files identified by name, which you specify with the first parameter.getPreferences()
- Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
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(); } }> Using the Internal Storage
You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.
To create and write a private file to the internal storage:
- Call
openFileOutput()
with the name of the file and the operating mode. This returns aFileOutputStream
. - Write to the file with
write()
. - Close the stream with
close()
.
String FILENAME = "hello_file"; String string = "hello world!"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close();
MODE_PRIVATE
will create the file (or replace a file of the same name) and make it private to your application. Other modes available are:
MODE_APPEND
,
MODE_WORLD_READABLE
, and
MODE_WORLD_WRITEABLE
.
Tip: If you want to save a static file in your application at compile time, save the file in your project res/raw/
directory. You can open it with openRawResource()
, passing the R.raw.<filename>
resource ID. This method returns an InputStream
that you can use to read the file (but you cannot write to the original file).
> Saving cache files
If you'd like to cache some data, rather than store it persistently, you should use getCacheDir()
to open aFile
that represents the internal directory where your application should save temporary cache files.
When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.
Other useful methods
- Gets the absolute path to the filesystem directory where your internal files are saved.
- Creates (or opens an existing) directory within your internal storage space.
- Deletes a file saved on the internal storage.
- Returns an array of files currently saved by your application.
getFilesDir()
getDir()
deleteFile()
fileList()
Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.
Caution: External storage can become unavailable if the user mounts the external storage on a computer or removes the media, and there's no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />Note: Beginning with Android 4.4, these permissions are not required if you're reading or writing only files that are private to your app.
here are a couple methods you can use to check the availability:
/* Checks if external storage is available for read and write */ public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /* Checks if external storage is available to at least read */ public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; }> Hiding your files from the Media Scanner
Include an empty file named.nomedia
in your external files directory (note the dot prefix in the filename). This prevents media scanner from reading your media files and providing them to other apps through the MediaStore
content provider. However, if your files are truly private to your app, you should save them in an app-private directory.
To get a File
representing the appropriate public directory, callgetExternalStoragePublicDirectory()
, passing it the type of directory you want, such as DIRECTORY_MUSIC
,DIRECTORY_PICTURES
, DIRECTORY_RINGTONES
, or others.
here's a method that creates a directory for a new photo album in the public pictures directory:
public File getAlbumStorageDir(String albumName) { // Get the directory for the user's public pictures directory. File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e(LOG_TAG, "Directory not created"); } return file; }
Beginning with Android 4.4, reading or writing files in your app's private directories does not require theREAD_EXTERNAL_STORAGE
or WRITE_EXTERNAL_STORAGE
permissions. So you can declare the permission should be requested only on the lower versions of Android by adding the maxSdkVersion
attribute:
<manifest ...> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" /> ... </manifest>Caution Although the directories provided by
getExternalFilesDir()
and
getExternalFilesDirs()
are not accessible by the
MediaStore
content provider, other apps with the
READ_EXTERNAL_STORAGE
permission can access all files on the external storage, including these. If you need to completely restrict access for your files, you should instead write your files to the
internal storage
.
Tip: To preserve file space and maintain your app's performance, it's important that you carefully manage your cache files and remove those that aren't needed anymore throughout your app's lifecycle.
> Using Databases
Android provides full support for SQLite databases. Any databases you create will be accessible by name to any class in the application, but not outside the application.
public class DictionaryOpenHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 2; private static final String DICTIONARY_TABLE_NAME = "dictionary"; private static final String DICTIONARY_TABLE_CREATE = "CREATE TABLE " + DICTIONARY_TABLE_NAME + " (" + KEY_WORD + " TEXT, " + KEY_DEFINITION + " TEXT);"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DICTIONARY_TABLE_CREATE); } }Android does not impose any limitations beyond the standard SQLite concepts. We do recommend including an autoincrement value key field that can be used as a unique ID to quickly find a record. This is not required for private data, but if you implement a content provider , you must include a unique ID using the
BaseColumns._ID
constant.
The Android SDK includes a sqlite3
database tool that allows you to browse table contents, run SQL commands, and perform other useful functions on SQLite databases.(Database debugging)
> Using a Network Connection
To do network operations, use classes in the following packages: