Android data Storage (i)----sharedpreferences detailed

Source: Internet
Author: User
Tags call back sqlite database

First, how to store the Android data:

The Android system offers a total of four data storage options. are: Sharepreference, SQLite, Content provider, and file; There is also a network store. Because the data is basically private in the Android system, it is stored in the "data/data/package name" directory, so to achieve data sharing, the correct way is to use content Provider.

In Android, data persistence can be achieved in several ways:

    • Shared Preferences: In addition to the SQLite database, another common way to store data. The form of shared parameters, a way of storing data in the form of Key-value key-value pairs , is essentially an XML file. Android built-in, general application configuration information is recommended to be saved in this way .
    • Internal Storage: Store data using the memory that comes with your Android device.
    • External Storage: The use of external storage devices to store data, generally referred to as sdcard.
    • SQLite Databases: Store structured data in a SQLite database. SQLite is a lightweight database that supports basic SQL syntax and is often used as a way of storing data. Android provides a class named Sqlitedatabase for this database, encapsulating some of the APIs that manipulate the database.
    • Network Connection: Get data using a Web-based service.
Second, the Android file system:

1. Android System files directory:

2. Android Application data storage mechanism:

In Android, third-party apps and their data are stored in the database directory. Where the application installation package will be stored in the /data/app/ directory, the file name of each installation package is as follows: app package names apk, to avoid duplication. For example, a package named Com.test.sample, the Application Data directory is /data/data/com.test.sample/. The corresponding database files are stored in the /data/data/com.test.sample/database/ directory, and the settings files are stored in the /data/data/com.test.sample/shared_prefs /, custom app data files are stored under directory /data/data/com.test.sample/files/ , and so on.

Not only that, Android will also create an account for each app, only through the app's account will be able to run the application's installation package files, read and write files in the Application Data directory (with the exception of the root authority, of course), so that the application data can no longer be acquired or destroyed by other applications.

3. android File operation:

From the application Data directory can be seen, the data file can be divided into two categories, one is placed in the extended memory files, that is, the files in the/sdcard/directory, they can be shared by each application, and the other is placed in the Application Data directory files, they can only be used by individual applications, can not be read and written by other applications.

Third, Sharedpreferences:

In all applications, the interaction of data is necessarily involved. Sometimes, applications have a small amount of data that needs to be saved, and the format of the data is simple. For example: software settings, user account settings, user habits settings , etc., this time can be used to sharedpreferences.

In fact, Sharedpreferences uses the XML format to provide a permanent means of data storage for Android applications and to store data in a way that uses key-value pairs . For an Android application, it is stored in the /data/data/your_app_package_name/shared_prefs/ directory of the file system and can be accessed by all activity in the same application. Android provides the relevant API to process this data without requiring programmers to manipulate these files directly or to consider data synchronization issues.

Because the sharedpreferences itself is an interface , the program cannot directly create an instance of Sharedpreferences, only through the getsharedpreferences provided by the context (String name , int mode) method to get an instance of Sharedpreferences:

 Public Abstract Sharedpreferences getsharedpreferences (String name,int mode)

This method receives two parameters, the first parameter specifies the name of the Sharedpreferences file (in the form of an XML file), and creates one if the specified file does not exist. sharedpreferences files are stored in the /data/data/<packagename>/shared_prefs/ directory, and the second parameter specifies the mode of operation:

    • mode_private: The default mode of operation, the same as the direct 0 effect, indicating that only the current application can read and write to this sharedpreferences file
    • Mode_world_readable: Specifies that this sharedpreferences is read-only and cannot be modified for other programs.
    • Mode_world_writeable: Specifies that this sharedpreferences can be read and written by other programs.
    • mode_multi_process:android2.3 has been abandoned since then.

Once you get the Sharedpreferences object, you can store the data in the Sharedpreferences file, which is divided into the following three steps :

    • Call the edit () method of the Sharedpreferences object to get a Sharedpreferences.editor object
    • Add data to the Sharedpreferences.editor object , such as adding a Boolean data using the Putboolean method, adding a string to the Putstring () method, and so on
    • Call the Commit () method to commit the data that was added to complete the data store operation

Third, example: Save the edited text message content:

Usually this problem occurs, we have to edit the text message at the same time we have a phone call, then the phone must be to start another activiy, then the current edit text message activity to edit the information we want to temporarily save, and so on after the call back to the activity, You can continue to edit text messages. How does this function need to be implemented?

(1) Save data:

First Use the Sharedpreferences tool class:

1     PrivateEditText etmsg;2     PrivateButton Sendbutton;3     Privatesharedpreferences sp;4     5 @Override6     protected voidonCreate (Bundle savedinstancestate) {7         Super. OnCreate (savedinstancestate);8 Setcontentview (r.layout.activity_main);9         TenEtmsg =(EditText) Findviewbyid (R.ID.EDITTEXT1); OneSendbutton =(Button) Findviewbyid (r.id.button1); A          -         //tool to get the share properties operation (file name, operation mode) -SP = this.getsharedpreferences ("Data", 0); the}

In the 14th line of code above, the method is called: Public sharedpreferences getsharedpreferences (String name, int mode)

Where the first parameter represents the XML file ( do not add the suffix name ), if there is this file, it will manipulate the file, if there is no such file, the file will be created, the second parameter represents an operation mode, 0 represents the private.

We then save the data in the OnPause () method, which is saved in the OnPause () method because the OnPause () method is executed first in all life cycle functions that may be destroyed by memory. The code is as follows:

// saving data in the OnPause () method     @Override    protectedvoid  onPause () {        super. OnPause ();         = Etmsg.gettext (). toString ();         = Sp.edit ();        Editor.putstring (//        editor.commit ();            }

Save the data in the MSG variable, then get the editor and put it in. Of course, these are just operations in memory, and the commit () method is executed if the file is to be reflected.

(2) Restore data:

Next, we re-restore the data in the Onresume () method: (Why do I have to restore the data in this method, I don't have to explain)

@Override      protected void Onresume () {         super. Onresume ();         Etmsg.settext (sp.getstring ("msg", ""));             }

When the program starts for the first time, the data is not saved, so a default null value is returned. Put the returned data in the Etmsg control.

Now we run the program and it can be executed.

For example, now edit the content, then go to another program, and then come back (even if we quit the program), the content of the edits still exist. At this time, we open the file browser, found that the data is stored in the /data/data/<packagename>/shared_prefs/ directory in the Data.xml file, and is permanently saved; after the Onresume () method restores the data, we also add some code to delete the contents of the file (unable to delete the file itself), or it will be permanently stored locally as garbage. The code is as follows:

protected void Onresume () {        super. Onresume ();        Etmsg.settext (sp.getstring ("msg", ""));    =             sp.edit ();        Editor.clear ();        Editor.commit ();    }

After the summary, the final full version of the code is as follows:

Activity_main.xml File Code:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context=". Mainactivity " >    <EditTextAndroid:id= "@+id/edittext1"Android:layout_width= "Match_parent"Android:layout_height= "0DP"android:gravity= "Top"Android:layout_weight= "1"Android:ems= "Ten" />    <ButtonAndroid:id= "@+id/button1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "button" /></LinearLayout>

The code for Mainactivity.java is as follows:

1  Packagecom.example.smyh001;2 Importandroid.app.Activity;3 Importandroid.content.SharedPreferences;4 ImportAndroid.content.SharedPreferences.Editor;5 ImportAndroid.os.Bundle;6 ImportAndroid.view.Menu;7 ImportAndroid.widget.Button;8 ImportAndroid.widget.EditText;9  Public classMainactivityextendsActivity {Ten     PrivateEditText etmsg; One     PrivateButton Sendbutton; A     Privatesharedpreferences sp; -      - @Override the     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -          +Etmsg =(EditText) Findviewbyid (R.ID.EDITTEXT1); -Sendbutton =(Button) Findviewbyid (r.id.button1); +          A         //tools to get shared property operations atSP = getsharedpreferences ("Data", 0); -     } -     //saving data in the OnPause () method - @Override -     protected voidOnPause () { -         Super. OnPause (); inString msg =Etmsg.gettext (). toString (); -Editor Editor =Sp.edit (); toEditor.putstring ("msg", MSG);//Execution method: Public abstract Sharedpreferences.editor putstring (string key, String value) + Editor.commit ();  -     } the      *     //to restore data in the Onresume () method $ @OverridePanax Notoginseng     protected voidOnresume () { -         Super. Onresume (); theEtmsg.settext (sp.getstring ("msg", "" "));  +Editor Editor =Sp.edit (); A editor.clear (); the editor.commit (); +     }     -}

After running the program, we enter some text in the edit box:

Exit the program, and then export the Data.xml file, which opens and appears as follows:

The input text is saved in the Data.xml file. When we go back to the program, the previously entered text is left on the interface, and the text in the Data.xml file is emptied.

Code optimization:

In the above code, if we add the following line of code after the 40th line of code:

    1. etMsg.setSelection((sp.getString("msg", "")).length());

When you return to the original program, the SetSelection method moves the input cursor to the end of the text so that you can continue typing. The parameters inside the sp.getstring ("msg", "") are the strings that were previously entered.

Iv. Example: Realize the function of remembering password


Temporary.


V. Use of the Preferenceactivity class:

Android data Storage (i)----sharedpreferences detailed

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.