Android Data Storage (1)

Source: Internet
Author: User

Android provides several options for storing persistent application data. Select a suitable solution based on specific requirements, such as whether the data is private or shared by the application, and the storage space required by the data.

The following are available data storage solutions:

Shared Preferences)

Store private raw data in the form of key-value pairs.

Internal Storage)

Store private data on the device's memory.

External Storage)

Store public data on the shared external storage.

SQLite Database

Store structured data in a private database.

Network Connection)

Store data on your Internet server.

Android provides a content provider that can expose your private data to other applications. The content provider is an optional component that exposes the read/write permissions of application data. Such read/write access is affected by any restrictions you impose.

Share preferences

The SharedPreference class provides a general framework that allows you to store and obtain persistent data in the form of a key-value pair of the original data type. SharedPreference can be used to save any type of raw data: Boolean, floating point, integer, and string. This type of data is persistently stored (even if the application process is killed) across the user's session cycle ).

There are two ways to get the SharedPreferences object for the application:

1. getSharedPreferences () method --- this method is required if multiple preferences are to be identified by names. The first parameter of this method must specify the preferences.

2. getPreferences () method-this method is used if you only need a preference file for the Activity. Because this method only returns the preference file of the current Activity and does not need to provide the preference file name.

The following describes how to write data to a preference file:

1. Call the edit () method to obtain a SharedPreferences. Editor object;

2. Call methods such as putBoolean () and putString () to add the value to be saved;

3. Call the commit () method to submit the new value to be saved.

Use methods such as getBoolean () and getString () of the SharedPreferences object to read the saved value.

The following sample code saves the mute key mode preference of the calculator:

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 ();
}
}

Use internal storage www.2cto.com

Files can be directly stored in the internal memory of the device. By default, files stored in the internal memory are private data of the application, and other applications (or Users) they cannot be accessed. When you detach an application, these files are also deleted.

The following method creates and writes a private file in the internal storage:

1. Call the openFileOutput method. You must specify the file name and operation mode. It returns a FileOutputStream object.

2. Use the write () method of the FileOutputStream object to write data to the file;

3. Use the close () method of the FileOutputStream object to close the output stream.

For example:

String FILENAME = "hello_file ";
String string = "hello world! ";

FileOutputStream fos = openFileOutput (FILENAME, Context. MODE_PRIVATE );
Fos. write (string. getBytes ());
Fos. close ();

The MODE_PRIVATE parameter indicates that the file is to be created (or, if a file with the same name exists, the old file will be replaced) and the file is a private file of the application. Other available modes include MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.

The following describes how to read a file from the internal storage:

1. Call openFileInput () to pass the file name to be read to this method. This method returns a FileInputStream object.

2. Use the read () method of the FileInputStream object to read bytes from the file.

3. close the input stream using the close () method of the FileInputStream object.

Tip: If you want to save a static file to the application during compilation, save the file to the res/raw/directory of the project. You can use the openRawResource () method to open this file. This method needs to pass the resource ID of R. raw. <filename> to it. This method returns an InputStream object used to read the file (however, this file cannot be written ).

Save cache files

If you only want to cache some data, instead of permanently saving it, you should use the getCacheDir () method to open a File object, it represents the internal directory of the application to save the temporary cache file.

When the device's internal storage space is insufficient, Android may delete these cached files to recycle the storage space. However, you should not rely on the system to clean up these files. You should always maintain the cached files on your own, and limit the storage space consumption to a reasonable range, such as 1 MB. When you detach an application, these files are deleted.

Other useful methods

GetFileDir ()

Obtain the absolute path of the file system directory where internal files are saved.

GetDir ()

Create (or open the existing Directory) in the internal bucket.

DeleteFile ()

Delete files stored in an internal bucket.

FileList ()

Returns the list of files currently saved by the application.

 

From FireOfStar's column

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.