Chapter 5 data-centric-Data Access (6), Chapter 5 Access

Source: Internet
Author: User

Chapter 5 data-centric-Data Access (6), Chapter 5 Access
5.3 security and convenience-use SharedPreferences

The preceding operations on files and databases are relatively complex and require operations such as opening, reading, and closing. Someone may think, if I only need to access a few simple data items, is there a simple way? Indeed, Android also encapsulates a lightweight data access method-Preferences.

Preferences is a lightweight data storage mechanism that combines some simple data types, including boolean, int, float, long, and String, key-value pairs are stored in the private Preferences directory (/data/<package name>/shared_prefs/) of the application. Preferences can only be used in the same package and cannot be used between different packages. This Preferences mechanism is widely used to store configuration information in applications.

On the Android platform, you only need to use a Context object to call the getSharedPreferences (String name, int mode) method to pass in the Preferences file name and open mode to obtain a SharedPreferences object. If the Preferences file does not exist, the Preferences file is created after data is submitted. Using the SharedPreferences object, you can call some getter methods and input corresponding keys to read data. To modify the data of the Preferences file, first use the SharedPreferences object to call the edit () method to obtain an internal Editor object, and then use this Editor object to edit the Preferences file. Note: After compilation, you must call the commit () method to submit the modifications to the Preferences file.

The following is an example of saving the text in EditText:

// Import omitted

Public class PreferenceTest extends Activity {

 

Private EditText edit;

Private static final String TEMP_NAME = "temp_name ";

 

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

Edit = new EditText (this );

// Get the SharedPreferences object read-only

SharedPreferences pre =

GetSharedPreferences (TEMP_NAME, MODE_WORLD_READABLE );

// Read "content"

String content = pre. getString ("content ","");

Edit. setText (content );

SetContentView (edit );

}

@ Override

Protected void onStop (){

Super. onStop ();

// Obtain the writable SharedPreferences. Editor object

SharedPreferences. Editor editor = getSharedPreferences (TEMP_NAME,

MODE_WORLD_WRITEABLE). edit ();

// Save "content"

Editor. putString ("content", edit. getText (). toString ());

// Submit data

Editor. commit ();

}

}

 

Some instructions on the method "public SharedPreferences getSharedPreferences (String name, int mode:

The first parameter is the file name, and the second parameter is the operation mode. There are three operation modes: MODE_PRIVATE (private), MODE_WORLD_READABLE (readable), and MODE_WORLD_WRITEABLE (writable ).

You can see that using Preferences to save and read data is very simple.

 

Experience Sharing:

Files can be stored on the SD card, while files stored on the SD card will not be deleted as the application is detached. However, if the application is uninstalled, the Preferences data does not exist. Note This when using Preferences to save data.

 

5.4 my data experts-ContentProvider, ContentResolver

In Android, data protection is very strict. Apart from the data stored on the SD card, the databases, files, and other contents owned by an application do not allow direct access from other applications, however, sometimes communication is necessary, not only for third parties, but also for applications. To solve this problem, you can rely on ContentProvider.

A ContentProvider implements a set of standard method interfaces, so that other applications can save or read various data types of this ContentProvider. That is to say, a program can expose its own data by implementing an abstract interface of ContentProvider, which is seen by other programs. Other programs can also read, modify, and delete data through the ContentProvider. Of course, some permissions are involved. The following lists some common interfaces, as shown in table 5-3.

Interface

Description

Query (Uri uri, String [] projection, String selection, String [] selectionArgs, String sortOrder)

Query by Uri and return a Cursor.

Insert (Uri url, ContentValues values)

Inserts a set of data into the place specified by the Uri.

Update (Uri uri, ContentValues values, String where, String [] selectionArgs)

Updates the data at the specified Uri location.

Delete (Uri url, String where, String [] selectionArgs)

Deletes the specified Uri and meets certain conditions.

Table 5-3 interfaces of ContentProvider

 

Experience Sharing:

The Android system has a series of built-in contentproviders for some common data types (such as music, video, images, and mobile phone contacts), all of which are under the android. provider package. With a specific license, you can access these Content providers in your own developed applications.

 

External programs can access the data provided by ContentProvider through the ContentResolver interface, and get the ContentResolver instance of the current application through getContentResolver () in the Activity. The interfaces provided by ContentResolver correspond to the interfaces to be implemented in ContentProvider. For details, see table 5-3.

In both the content provider (ContentProvider) and the user (ContentResolver), we can see a common object Uri. This object is similar to an address. there are usually two types, one is to specify all data, the other is data that specifies an ID. Let's look at the example below.

Content: // contacts/people/This Uri specifies all the contact data.

The content: // contacts/people/1 Uri specifies the data of the contact whose ID is 1.

 

Generally, a Uri consists of three parts:

L The first part is: "content ://".

L The second part is a string segment for obtaining data.

L ID (if no ID is specified, all is returned ).

The URI is often long and sometimes error-prone and hard to understand. Therefore, some helper classes are defined in Android and some constants are defined to replace these long strings. For example, the following code:

Uri mUri = android. provider. Contacts. People. CONTENT_URI; // The actual URI of the contact is equal:

Uri mUri = Uri. parse ("content: // contacts/people ");

---------------------------------------- It is difficult for programmers to make money. Therefore, they must learn financial management. The annual ROI of the p2p platform affiliated to Ping An group is 7%-9%. This is the preferred personal experience to replace bank financial management. We recommend investing in don't invest in security, which is almost impossible to transfer. It is very difficult to withdraw the website link in advance. Don't make it in white --------------------------------------------

The above is a theoretical analysis. Let's take an example to see how to use it. We need to obtain the contact list of the mobile phone and display it.

// Import omitted

Public class ContentResolverTest extends Activity {

 

// The column to be returned when querying the Content Provider

Private String [] columns = {ContactsContract. Contacts. DISPLAY_NAME,

ContactsContract. Contacts. _ ID ,};

Private Uri contactUri = ContactsContract. Contacts. CONTENT_URI;

Private TextView TV;

 

@ Override

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

TV = new TextView (this );

String result = getQueryData ();

TV. setTextColor (Color. GREEN );

TV. setTextSize (20366f );

TV. setText ("ID name" + result );

SetContentView (TV );

}

/**

* Obtains the contact list information and returns a String object.

*/

Public String getQueryData (){

String result = "";

// Obtain the ContentResolver object

ContentResolver resolver = getContentResolver ();

Cursor cursor = resolver. query (contactUri, columns, null, null );

// Obtain the index of the _ ID field

Int idIndex = cursor. getColumnIndex (ContactsContract. Contacts. _ ID );

// Obtain the index of the Name field

Int nameIndex = cursor

. GetColumnIndex (ContactsContract. Contacts. DISPLAY_NAME );

// Traverse Cursor to extract data

For (cursor. moveToFirst ();! Cursor. isAfterLast (); cursor. moveToNext ()){

Result = result + cursor. getString (idIndex) + ",";

Result = result + cursor. getString (nameIndex) + ";";

}

Cursor. close ();

Return result;

}

}

 

Experience Sharing:

The contact may be stored on the mobile phone or on the mobile phone card. The above Code only obtains the contact list from the mobile phone. In actual development, if such a requirement exists, we also need to obtain all contacts from the mobile phone card and compare them with the contacts on the mobile phone to obtain a complete contact list. Here, we do not describe how to obtain contacts from mobile phone cards. Readers can search for related information from the Internet.

 

Experience Sharing:

In Android development, if you need to access hardware devices, you will often encounter permission problems. If an error similar to "Android Permission denied" occurs during debugging, check whether the system function is used and the corresponding permissions are not added.

For example, in the above example, we need to add the corresponding permissions.

<Uses-permission android: name = "android. permission. READ_CONTACTS"/>

<! -- Read contact permissions -->

<Uses-permission android: name = "android. permission. WRITE_CONTACTS"/>

<! -- Write contact permissions -->

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.