Android ContentResolver Instructions

  • 2020-12-26 05:53:15
  • OfStack

How does Android enable data sharing between applications? An application can put your own data completely exposed, more this don't see the outside world, also need not see the application exposed how data is stored, or is the use of a database or using the file, or via Internet, cut the 1 is not important, it is important to the outside world can through this 1 set of standards and system interface and the data in this program, for example: add (insert), remove (delete), query (query), modified (update), need 1 set of permissions to, of course.

How do You expose your application's data? Android provides ContentProvider, where a program can fully expose its data by implementing an abstract interface to Content provider, and Content providers exposes data in a manner similar to tables in a database. Content providers stores and retrieves data that can be accessed by all applications and is the only way to share data between applications. There are two ways to make your application's data public: create your own Content provider or add your data to an existing Content provider, provided you have the same data type and have permission to write to Content provider.

How can I obtain data exposed by other applications through a set of standards and interface of Unified 1? Android provides ContentResolver, and external programs can access the data provided by ContentProvider through the ContentResolver interface.

The current installment focuses on getting data shared by other applications, such as information in the Android phone book.

What is URI?

Before you learn how to acquire ContentResolver, there is one noun you must know: URI. URI is the definition of network resources, which is given a broader meaning in Android.

It is divided into A, B, C and D:
A: Standard prefix used to indicate that 1 Content Provider controls these data and cannot be changed;
B: The logo of URI, which defines which Content Provider provides the data. For a third party application, to ensure that the URI identity is unique, it must be a full, lowercase class name. This sign is in the < provider > The authorities attribute of the element states:
< provider name= ".TransportationProvider "authorities=" com.example.transportationprovider ".. >
C: paths, Content Provider use these paths to determine what type of data needs to be generated currently. URI may not include paths or may include multiple paths.
D: If included in URI, ID represents the record to be obtained; If there is no ID, it means return all;
As URI is usually long and sometimes error-prone, it is difficult to understand. So, in Android, I have defined 1 helper class, and I have defined 1 constant to replace these long strings, such as People.CONTENT_URI

ContentResolver description

After reading these introductions, you will definitely understand that ContentResolver uses URI to query the data provided in ContentProvider. In addition to URI, you must know the name of the data segment you want to fetch, as well as the data type of this data segment. If you need to retrieve a specific record, you must know ID of the current record, which is the D part of URI.

As mentioned earlier, Content providers exposes data in a manner similar to tables in a database, so ContentResolver will also use database-like operations to obtain data from Content providers. Here is a brief overview of the main interfaces of ContentResolver, as follows:

返回值 函数声明
final Uri insert(Uri url, ContentValues values)Inserts a row into a table at the given URL.
final int delete(Uri url, String where, String[] selectionArgs)Deletes row(s) specified by a content URI.
final Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)Query the given URI, returning a Cursor over the result set.
final int update(Uri uri, ContentValues values, String where, String[] selectionArgs)Update row(s) in a content URI.

See here, does it feel like the database operation is basically 1? As such, please refer to the instructions in Android SQLite parsing for detailed analysis, and do not elaborate here.

Last question: How do I get ContentResolver? Call getContentResolver (), for example: ContentResolver cr = getContentResolver();

Knowing that ContentResolver uses ContentProvider to get other data shared with the application, the interface between ContentResolver and ContentProvider should be similar.

ContentProvider is responsible

* Organize application data;
* Provide data to other applications;

ContentResolver is responsible for

* Access to data provided by ContentProvider;
* Modify/add/delete updated data, etc.;

How does ContentProvider provide data to the outside world?

Android provides ContentProvider. A program can fully expose its data by implementing an abstract interface of ContentProvider, and ContentProviders exposes data in a manner similar to tables in a database. In other words, ContentProvider is like a "database". Then, the data obtained by the outside world should be the same as the operation of obtaining data from the database, except that URI is adopted to represent the "database" that the outside world needs to access. As for how to identify which "database" the outside world needs from URI, this is what the bottom line of Android needs to do, I won't go into details here. Briefly analyze the interface of ContentProvider to provide data operation to the outside world:

query(Uri, String[], String, String[], String) insert(Uri, ContentValues) update(Uri, ContentValues, String, String[]) delete(Uri, String, String[])

These operations are basically exactly the same as database operations, which are not detailed here, but detailed in Android Sqlite parse. Special instructions are required for URI:

The D section of URI may contain 1 _ID, which should appear in the SQL statement and can appear in a special way, requiring extra attention to this particular information when providing data. Android SDK recommends that you include one ID in the supplied table field and that INTEGER PRIMARY KEY AUTOINCREMENT identifies the ID field when the table is created.

How does ContentProvider organize data?

Organization data mainly includes: storing data, reading data, exposing data in the way of database. According to the design requirements, data storage needs to choose the appropriate storage structure, the preferred database, of course, you can choose other local files, even the data on the network. The reading of data exposes data in the form of a database. This requires that the data be finally accessed as data, regardless of how the data is stored.

There are probably two more issues that need to be addressed.

1. When and by whom was ContentProvider created? Do You need to start an application to access data shared by that application? This issue is not explicitly stated in Android SDK, but from the point of view of data sharing, ContentProvider should have been created when the system started, otherwise it would not have been shared. This requires use in ES193en.XML < provider > The element is clearly defined.
2. It is possible to have multiple programs accessing one ContentProvider at the same time through ContentResolver. Will this result in "dirty data" like a database? The first aspect of this problem requires synchronization of database access, especially of data writing, which needs to be considered when defining ContentProvider in ES201en.ES202en < provider > The value of the element multiprocess attribute; Another aspect of Android is to provide notifyChange() interface in ContentResolver, which will notify other ContentObserver when data changes. This place should use observer mode, and there should be one interface in ContentResolver similar to register, unregister.

At this point, ContentProvider has been thoroughly analyzed, and there are two ways to create ContentProvider: create your own ContentProvider or add your data to an existing ContentProvider, provided you have the same data type and have permission to write to Content provider. Look at the source code in Notepad SDK sample for specific examples of Notepad!

Make an instance of ContentResolver

The above fully describes how to get and use ContentResolver, start Eclipes, and make a complete example as follows:
Open showcontent. java and modify as follows:


package moandroid.showcontact;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.Phones;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
public class showcontact extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Cursor c = getContentResolver().query(Phones.CONTENT_URI, null, null, null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_2, c,
new String[] { Phones.NAME, Phones.NUMBER },
new int[] { android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
}
}

Then in ES240en.XML < application > Add the following license before the element:

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

Finally, run the program. After the simulator starts, click Menu to return to the Home interface, open Contacts to select Contacts TAB, and add 2 contact information. Go back to Home and select ES264en.showcontact to run. The two contacts just added will be displayed on the interface, as follows:

Conclusion shows that

The use of ContentResolver greatly facilitates the sharing of data between applications. How can the application's data be fully exposed to other applications

Use of ContentResolver in android

Use ContentResolver to add, delete, modify and check the phone book information. The detailed code is as follows:


import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.support.v4.widget.SimpleCursorAdapter;
import android.widget.ListAdapter;

public class MainActivity extends ListActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		insert("tester1");
		update("tester2", new String(People.NAME + "='tester1'"));
		delete(new String(People.NAME + "='tester2'"));
		select();
	}

	/*
	 *  Insert a new contact into the contact list 
	 * @param name The value of People.NAME
	 */
	public void insert(String name) {
		ContentValues ct = new ContentValues();
		ct.put(People.NAME, name);
		getContentResolver().insert(People.CONTENT_URI, ct);
	}
 
	/*
	 *  Updates the designated contact on the phone 
	 * @param name A new name for People.NAME
	 * @param where The update requirement.
	 */
	public void update(String name, String where) {
		ContentValues ct = new ContentValues();
		ct.put(People.NAME, name);
		getContentResolver().update(People.CONTENT_URI, ct, where, null);
	}

	/*
	 *  Delete the contacts specified on the phone 
	 * @param where The delete requirement.
	 */
	public void delete(String where) {
		getContentResolver().delete(People.CONTENT_URI, where, null);
	}

	//  Find all contacts 
	public void select() {
		Cursor cursor = getContentResolver().query(People.CONTENT_URI,
				new String[] { People._ID, People.NAME }, null, null, null);

		ListAdapter adapter = new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, cursor,
				new String[] { People.NAME }, new int[] { android.R.id.text1 });

		setListAdapter(adapter);
	}
}

AndroidManifest.xml add the following permissions:


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

Related articles: