Android Data Storage--sharedpreference

Source: Internet
Author: User
Tags sqlite database

As a complete application, data storage operations are essential, so the Android system provides four ways to store data: Sharedpreference, File, SQLite, and content Provider. As the Android system, the data are basically private, are stored in the "data/data/package name" directory, all to achieve data sharing, the correct way to use the content Provider.

SQLite: SQLite is a lightweight database that supports basic SQL syntax and is often used as a way to store data. Android provides a type named Sqlitedatebase for this database, encapsulating some API for manipulating the database.

sharedpreference: In addition to the SQLite database, another common method of data storage, which is essentially an XML file, is often used to store simpler parameter settings.

file: That is, commonly said files (I/O) storage, often store a large amount of data, but the disadvantage is that updating data will be a difficult thing.

ContentProvider: A way of storing data that can be shared across all applications in an Android system, because the data is usually private to each application, and all this storage is less used, but it is an essential storage method. such as audio, video, pictures, and contacts, can generally be used in this way process storage. Each contentprovider provides a public URI (wrapped as a URI object), and if the application has data to share, it needs to use ContentProvider to define a URI for the data, and then the other application passes the content Provider pass in the URI to manipulate the data.

sharedpreference: is a kind of lightweight data storage, its essence is based on XML file storage Key-value key value pair data, usually used to save some simple configuration information. Its storage location is under the "data/data/package name/shared_prefs" directory. The Sharedpreference object itself can only fetch data without supporting storage and modification, and storage modifications are implemented through the editor object.

Compared with SQLite database, Sharedpreference object is more convenient and concise than creating database, creating table, writing SQL statement and so on. But Sharedpreference also has its own flaws, such as its function of storing boolean, int, float, long, and string five simple data types, such as its inability to perform conditional queries. All data storage operations, no matter how simple sharedpreference, can only be a complement to storage, not a complete replacement for other data storage methods such as SQLite data.

sharedpreference Storage mode operation steps :

First, according to the context to obtain Sharedpreference object

    • Call the Getsharedpreference () method of the context object, and the Sharedpreference object obtained by the method can be shared by other components under the same application
    • Invokes the Getpreference () method of the Activity object, and the Sharedpreference object obtained by the method can only be used in the activity
Second, using the edit () method in the Sharedpreference object to get editor object three, through the editor object store Key-value key value to data four, through the Editor object commit () method to submit data
Four operating modes of the Sharedpreferencecontext.mode_private: The default mode of operation, which means that the file is private and can only be accessed by the application itself, in which the contents of the original file are overwritten. Context.mode_append: This mode checks whether a file exists, appends content to the file, or creates a new file context.mode_world_readable: Indicates that the current file can be read by another application
context.mode_world_writeable: Indicates that the current file can be written by another application

Example :--by clicking TextView to get sharedpreference saved data

androidmanifest.xml--did not make any changes to create the project by default

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "/http Schemas.android.com/apk/res/android "package=" Com.example.sharedpreferencedemo "android:versioncode=" 1 "android:v Ersionname= "1.0" > <uses-sdk android:minsdkversion= "8" android:targetsdkversion= "/> <a" Pplication android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app _name "Android:theme=" @style/apptheme "> <activity android:name=" Com.example.sharedpreferen Cedemo. Mainactivity "android:label=" @string/app_name "> <intent-filter> <action Android:name= "Android.intent.action.MAIN"/> <category android:name= "Android.intent.category.LAUNCHER "/> </intent-filter> </activity> </application></manifest> 
Activity_main.xml

<linearlayout xmlns: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:gravity= "center"    tools:context= ". Mainactivity ">    <textview        android:id=" @+id/textview "        android:layout_width=" Wrap_content "        android:layout_height= "wrap_content"        android:text= "@string/hello_world"/></linearlayout>
Mainactivity.java

Package Com.example.sharedpreferencedemo;import Android.os.bundle;import Android.view.view;import Android.widget.textview;import Android.app.activity;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;public class Mainactivity extends Activity {private TextView TextView;    Private Sharedpreferences sharedpreferences;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        /*1, gets the Sharedpreference object, this parameter a hello specifies the saved file name */sharedpreferences = getsharedpreferences ("Hello", mode_private);        /*2, deposit data, can be stored in various types of data, data through the key key value tag corresponding data */editor editor = Sharedpreferences.edit ();        Editor.putstring ("string", "Hello World");        Editor.putint ("int", 10);        Editor.putboolean ("Boolean", true);                        /*3, submit data */Editor.commit ();        TextView = (TextView) This.findviewbyid (R.id.textview); TextvIew.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated Method stub//If the key value does not exist, the data of the second parameter is returned string string = Sharedpreferences.getstring ("string", "") + "\ n" + Sharedpreferences.getint ("int", 0) + "\ n" +sharedpreferences.getboolean ("Boolean", False); Textview.settext (string);    Textview.settextsize (20);}); }    }
Download the program

When you run this program, the data is saved in the/data/data/com.example.sharedpreferencedemo/shared_prefs/hello.xml file. Enter Window->show view->other->androd->file Explorer
View files under


Click the first button in the upper-right corner of the File Explorer dialog box to export the Hello.xml file to your computer from a receipt to view its contents


The contents are as follows :

Program Test :-- Click TextView to get sharedpreference saved data




Android Data Storage--sharedpreference

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.