Android Data Save

Source: Internet
Author: User
Tags sqlite database

Ways to permanently save data:
1.Shared Preferences stores basic data types in key-value pairs (booleans, floats, ints, longs, and strings), The stored data is restricted to one application (one package) for internal use

The 2.Internal Storage stores private files in the internal storage. These files are a application private and other application cannot be accessed to
3.External Storage Storing public data in external memory

4.SQLite Databases
Store structured data in a private database.
5.Network Connection
Store data on the Web with your own network server.
Android provides a-to-expose even your private data to other Applications-with a content provider. A content provider is an optional component this exposes Read/write access to your application data, subject to whatever R Estrictions want to impose

Using Shared Preferences
Get a Sharedpreferences object in two ways:

Getsharedpreferences ()-Use this method when there are multiple preferences files. The first parameter of the method specifies the name of the preferences file that you want to manipulate
Getpreferences ()-This method is used when there is only one preferences file. Because This is the only preferences file for your Activity, and you don't supply a name.
After getting the object, you can call the object's method to read the data in the preferences file and write the data to the preferences file

READ: Using Sharedpreferences's Getboolean () and GetString () methods

Write:

Call the edit () method to get the Sharedpreferences.editor object.
Writes a value using Putboolean () and putstring ().
Commit the new values with commit (): Use this method to commit the newly written value
Look at the following example:

 Public classCalc extends Activity { Public StaticFinal String Prefs_name ="Myprefsfile"; @Overrideprotected voidonCreate (Bundle state) {super.oncreate (state); . . .                //Restore PreferencesSharedpreferences settings = getsharedpreferences (Prefs_name,0); Boolean Silent= Settings.getboolean ("Silentmode",false);        Setsilent (silent); } @Overrideprotected voidOnStop () {super.onstop (); //We need an Editor object to make preference changes. //All objects is from android.context.ContextSharedpreferences settings = getsharedpreferences (Prefs_name,0); Sharedpreferences.editor Editor=Settings.edit (); Editor.putboolean ("Silentmode", Msilentmode); //Commit the edits! Editor.commit (); }    }   Public classCalc extends Activity { Public StaticFinal String Prefs_name ="Myprefsfile"; @Overrideprotected voidonCreate (Bundle state) {super.oncreate (state); . . .          //Restore PreferencesSharedpreferences settings = getsharedpreferences (Prefs_name,0); Boolean Silent= Settings.getboolean ("Silentmode",false);     Setsilent (silent); } @Overrideprotected voidOnStop () {super.onstop (); //We need an Editor object to make preference changes. //All objects is from android.context.ContextSharedpreferences settings = getsharedpreferences (Prefs_name,0); Sharedpreferences.editor Editor=Settings.edit (); Editor.putboolean ("Silentmode", Msilentmode); //Commit the edits!Editor.commit (); } }

Using the Internal Storage
Storage of private files. The data will be removed after the user uninstalls the application

To write a private file to memory:

Call the Openfileoutput () method to get the output stream of the file. Specify the file name and operation mode in the parameters of the method
Write using the Write () method
Close the stream: Close ().
Example:

View Plaincopy to Clipboardprint?String FILENAME="Hello_file"; Stringstring="Hello world!"; FileOutputStream Fos=openfileoutput (FILENAME, context.mode_private); Fos.write (string. GetBytes ());  Fos.close (); String FILENAME="Hello_file"; Stringstring="Hello world!"; FileOutputStream Fos=openfileoutput (FILENAME, context.mode_private); Fos.write (string. GetBytes ()); Fos.close ();

Available modes are: Mode_private, Mode_append, mode_world_readable and mode_world_writeable.

To read a file from memory into a program:

Call the Openfileinput () method to get the input stream. Method parameter specifies the file name
Read using the Read () method.
Close the stream: Close ().
Read-only static files at compile time:

To put the file in the res/raw/directory, use the Openrawresource (r.raw.<filename>) method to open the file, the method returns an input stream, which can be used to read the contents of the file

Saving cache files

If you want to save data temporarily rather than save it for a long time

Use the Getcachedir () method to open a File (application the path where the temporary cache data is stored)

When device memory is low, the system may automatically delete such data to free up memory space. But you can't rely on this possibility, you have to ensure that the cache file can not occupy too much memory space. When application is unloaded, this part of the data is removed

Other useful methods
Getfilesdir ()
Gets the absolute path to the filesystem directory where your internal files is saved.
Get the full path based on the storage internal files directory (different file system get paths will be different)
Getdir ()
Creates (or opens an existing) directory within your internal storage space.
Create a directory in memory
DeleteFile ()
Deletes a file saved on the internal storage.
To delete a file in memory
FileList ()
Returns an array of files currently saved by your application.
Get all the files stored in a application and store them in an array
Using the External Storage
External storage. These files can be freely read and written between devices, as long as the device's system is compatible with Android. Easy to lose, so take extra care when operating

The storage for storage are: removable media storage (such as SD card) and non-Removable Storage

Checking Media Availability
Check if media is available

Media is checked for availability before use, and the Getexternalstoragestate () method is called to get the state of media. Use the following:

View Plaincopy to Clipboardprint?Boolean mexternalstorageavailable=false; Boolean mexternalstoragewriteable=false; String State=environment.getexternalstoragestate (); if(Environment.MEDIA_MOUNTED.equals (state)) {//We can read and write the mediamexternalstorageavailable = Mexternalstoragewriteable =true; } Else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) {//We can only read the mediaMexternalstorageavailable =true; Mexternalstoragewriteable=false; } Else {        //Something else is wrong. It may be one of the many other states, but all we need//To know is we can neither read nor writemexternalstorageavailable = Mexternalstoragewriteable =false; } Boolean mexternalstorageavailable=false; Boolean mexternalstoragewriteable=false; String State=environment.getexternalstoragestate (); if(Environment.MEDIA_MOUNTED.equals (state)) {//We can read and write the mediamexternalstorageavailable = Mexternalstoragewriteable =true; } Else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) {//We can only read the mediaMexternalstorageavailable =true; Mexternalstoragewriteable=false; } Else {     //Something else is wrong. It may be one of the many other states, but all we need//To know is we can neither read nor writemexternalstorageavailable = Mexternalstoragewriteable =false; }

Generally common states are: read-write, read-only, and unavailable

Getexternalstoragestate () also returns additional states, such as whether media is shared, installed properly, or whether an error occurred while uninstalling, to inform the user of the device's status

Accessing files on external storage
When you use Level8 or a higher API, use Getexternalfilesdir () to open a File (representing the directory of the data store in external storage).

Represents the root of the external storage when parameters are not passed. There are parameters that correspond to the specified directory type, such as Directory_music and Directory_ringtones, which represent the music directory and the ringtone directory, respectively. If the specified directory does not exist, the directory is created. By specifying a directory type, you can have the Android multimedia scanner categorize your files. If your application is uninstalled by the user, the directory and content stored in this way will be removed

If you are using LEVEL7 or earlier APIs, use getExternalStorageDirectory () to open the root directory of the external storage represented by file.

You also need to write the data in the following directory:/android/data/<package_name>/files/the contents of the above directory and directory will be removed when users uninstall this version of the app using Level8 or later APIs saving Files that should be shared
If you want to save files that are not related to the app, that is, the files saved after the application unload are retained, save the files in the external storage Common directory, which is located in the root directory of external storage, such as music/, pictures/, ringtones/, etc.

When you use Level8 or higher APIs, use the Getexternalstoragepublicdirectory () method, pass parameters Directory_music, Directory_pictures, Directory_ RINGTONES, you can save the file in the specified directory. The directory does not exist to create

If using LEVEL7 or earlier APIs, use the getExternalStorageDirectory () method to open the root directory of the external storage represented by file, and store the shared files in one of the following directories:

music/-Media scanner classifies all media found here as user music.
podcasts/-Media scanner classifies all media found here as a podcast.
ringtones/-Media scanner classifies all media found here as a ringtone.
alarms/-Media scanner classifies all media found here as a alarm sound.
notifications/-Media scanner classifies all media found here as a notification sound.
Pictures/-All photos (excluding those taken with the camera).
Movies/-All Movies (excluding those taken with the camcorder).
download/-Miscellaneous downloads.
Saving cache files
As mentioned above, different methods are used depending on the API version:

High version API: Using Getexternalcachedir ()

Low version api:getexternalstoragedirectory () Open the root directory, and cache data is written to the/android/data/<package_name>/cache/directory

Using Databases
Android fully supports SQLite database

The classic way to create a SQLite database is to construct a subclass of Sqliteopenhelper and overwrite the OnCreate () method by using the SQLite command in the method:

 Public classMydbopenhelper extends Sqliteopenhelper {Private StaticFinalintDatabase_version =2; Private StaticFinal String Dictionary_table_name ="Dictionary"; Private StaticFinal 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 voidonCreate (Sqlitedatabase db) {db.execsql (dictionary_table_create); }    }   Public classMydbopenhelper extends Sqliteopenhelper {Private StaticFinalintDatabase_version =2; Private StaticFinal String Dictionary_table_name ="Dictionary"; Private StaticFinal 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 voidonCreate (Sqlitedatabase db) {db.execsql (dictionary_table_create); } }

See the Note Pad and searchable Dictionary for an example of using SQLite databases in Android.

Debugging Tools for SQLite database in Android: Sqlite3

Using a Network Connection
You can use the network (when it's available) to store and retrieve data on your own web-based services. To does network operations, use classes in the following packages:

java.net.*
android.net.*

Android Data Save

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.