今天看了android的官方文档中ContentProvider的那部分,因为数据库使用我一直很晕乎,我想要完成自己写一个provider,再写一个工程来使用它读数据,建数据,所以今天先学习了如何查询的这部分知识,首先是一些从官方文档中总结出来的几点:
1.查询必备的三个条件:
1.The URI that identifies the provider-->URI
2.The names of the data fields you want to receive-->data fields
3.The data types for those fields-->data types
所以写Provider的时候也必须要提供一个类,来把这些数据暴露给使用者们
2.查询有两种方法:
1. ContentResolver.query()
2. Activity.managedQuery():unloading itself when the activity pauses, and requerying itself when the activity restarts,可以使用Activity.startManagingCursor()来控制开始manage和使用stopManagingCursor(Cursor c)结束manage
当然查询数据库的方法肯定不止这两个,比如使用SQLiteDatabase的query方法,可以有更多复杂的查法。
3.如果你已知ID的情况下,可以这么查数据库
使用ContentUris.withAppendedId() 或 Uri.withAppendedPath()
例如:
view plaincopy to clipboardprint?
1. import android.provider.Contacts.People;
2. import android.content.ContentUris;
3. import android.net.Uri;
4. import android.database.Cursor;
5.
6. // Use the ContentUris method to produce the base URI for the contact with _ID == 23.
7. Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
8.
9. // Alternatively, use the Uri method to produce the base URI.
10. // It takes a string rather than an integer.
11. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
12.
13. // Then query for this specific record:
14. Cursor cur = managedQuery(myPerson, null, null, null, null);
4.其他参数说明
• The names of the data columns that should be returned. A null value returns all columns. Otherwise, only columns that are listed by name are returned. All the content providers that come with the platform define constants for their columns. For example, the android.provider.Contacts.Phones class defines constants for the names of the columns in the phone table illustrated earlier — _ID, NUMBER, NUMBER_KEY, NAME, and so on.
• A filter detailing which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). A null value returns all rows (unless the URI limits the query to a single record).
• Selection arguments.
• A sorting order for the rows that are returned, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). A null value returns the records in the default order for the table, which may be unordered
5.取得查询结果
1. The Cursor lets you request the column name from the index of the column, or the index number from the column name.
(可以从从column name拿到column index,反之也可以从column index拿到column name)
2. Cursor object has a separate method for reading each type of data — such as getString(), getInt(), and getFloat().
(However, for most types, if you call the method for reading strings, the Cursor object will give you the String representation of the data.)
括号里面的这个功能很方便哟,我有试成功
具备了以上的基础之后,我写了一个例子来实现排序和模糊查找(需要使用正则表达式),不过我一直很想做的多表查询始终无果,有高手知道的麻烦告诉我一下吧。
代码如下:
view plaincopy to clipboardprint?
1. package com.ianc.querycontact;
2.
3. import android.app.Activity;
4. import android.content.ContentResolver;
5. import android.content.ContentUris;
6. import android.database.Cursor;
7. import android.net.Uri;
8. import android.os.Bundle;
9. import android.provider.Contacts;
10. import android.util.Log;
11.
12. public class QueryContact extends Activity {
13. /** Called when the activity is first created. */
14. @Override
15. public void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.main);
18. Uri uri = Contacts.People.CONTENT_URI;
19. String[] projection = {Contacts.People._ID, Contacts.People.PRIMARY_PHONE_ID, Contacts.PeopleColumns.NAME, Contacts.PeopleColumns.TIMES_CONTACTED};
20. String selection = Contacts.PeopleColumns.NAME + " like ?";
21. String[] selectionArgs = {"%li,%"};
22. String sortOrder = Contacts.PeopleColumns.NAME+" ASC";
23. Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
24. int nColumnIndex;
25. String id;
26. int phoneID;
27. String name;
28. String times;
29. ContentResolver cr = getContentResolver();
30. if(cursor.moveToFirst()){
31.
32. Log.i("lily", "total "+cursor.getCount()+" records.");
33.
34. do {
35. Log.i("lily", "***************************************");
36.
37. nColumnIndex = cursor.getColumnIndex(Contacts.People._ID);
38. id = cursor.getString(nColumnIndex);
39. Log.i("lily", "id = " + id);
40.
41. nColumnIndex = cursor.getColumnIndex(Contacts.People.PRIMARY_PHONE_ID);
42. phoneID = cursor.getInt(nColumnIndex);
43. Log.i("lily", "phoneID = " + phoneID);
44. Uri phoneuri = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, phoneID);
45. String[] phoneprojection = {Contacts.Phones._ID, Contacts.PhonesColumns.NUMBER};
46. Cursor phonecursor = cr.query(phoneuri, phoneprojection, null, null, null);
47. if (phonecursor.moveToFirst()){
48. String phoneNumber = phonecursor.getString(phonecursor.getColumnIndex(Contacts.PhonesColumns.NUMBER));
49. Log.i("lily", "phoneNumber = " + phoneNumber);
50. }else{
51. Log.i("lily", "no phone number");
52. }
53. phonecursor.close();
54.
55.
56. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.NAME);
57. name = cursor.getString(nColumnIndex);
58. Log.i("lily", "name = "+ name);
59.
60. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.TIMES_CONTACTED);
61. times = cursor.getString(nColumnIndex);
62. Log.i("lily", "contact times = "+times);
63.
64. Log.i("lily", "***************************************");
65. }while(cursor.moveToNext());
66. }else{
67. Log.i("lily", "no result");
68. }
69. cursor.close();
70. }
71.
72. @Override
73. protected void onResume() {
74.
75. super.onResume();
76. }
77.
78. }
1.查询必备的三个条件:
1.The URI that identifies the provider-->URI
2.The names of the data fields you want to receive-->data fields
3.The data types for those fields-->data types
所以写Provider的时候也必须要提供一个类,来把这些数据暴露给使用者们
2.查询有两种方法:
1. ContentResolver.query()
2. Activity.managedQuery():unloading itself when the activity pauses, and requerying itself when the activity restarts,可以使用Activity.startManagingCursor()来控制开始manage和使用stopManagingCursor(Cursor c)结束manage
当然查询数据库的方法肯定不止这两个,比如使用SQLiteDatabase的query方法,可以有更多复杂的查法。
3.如果你已知ID的情况下,可以这么查数据库
使用ContentUris.withAppendedId() 或 Uri.withAppendedPath()
例如:
view plaincopy to clipboardprint?
1. import android.provider.Contacts.People;
2. import android.content.ContentUris;
3. import android.net.Uri;
4. import android.database.Cursor;
5.
6. // Use the ContentUris method to produce the base URI for the contact with _ID == 23.
7. Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);
8.
9. // Alternatively, use the Uri method to produce the base URI.
10. // It takes a string rather than an integer.
11. Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");
12.
13. // Then query for this specific record:
14. Cursor cur = managedQuery(myPerson, null, null, null, null);
4.其他参数说明
• The names of the data columns that should be returned. A null value returns all columns. Otherwise, only columns that are listed by name are returned. All the content providers that come with the platform define constants for their columns. For example, the android.provider.Contacts.Phones class defines constants for the names of the columns in the phone table illustrated earlier — _ID, NUMBER, NUMBER_KEY, NAME, and so on.
• A filter detailing which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). A null value returns all rows (unless the URI limits the query to a single record).
• Selection arguments.
• A sorting order for the rows that are returned, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). A null value returns the records in the default order for the table, which may be unordered
5.取得查询结果
1. The Cursor lets you request the column name from the index of the column, or the index number from the column name.
(可以从从column name拿到column index,反之也可以从column index拿到column name)
2. Cursor object has a separate method for reading each type of data — such as getString(), getInt(), and getFloat().
(However, for most types, if you call the method for reading strings, the Cursor object will give you the String representation of the data.)
括号里面的这个功能很方便哟,我有试成功
具备了以上的基础之后,我写了一个例子来实现排序和模糊查找(需要使用正则表达式),不过我一直很想做的多表查询始终无果,有高手知道的麻烦告诉我一下吧。
代码如下:
view plaincopy to clipboardprint?
1. package com.ianc.querycontact;
2.
3. import android.app.Activity;
4. import android.content.ContentResolver;
5. import android.content.ContentUris;
6. import android.database.Cursor;
7. import android.net.Uri;
8. import android.os.Bundle;
9. import android.provider.Contacts;
10. import android.util.Log;
11.
12. public class QueryContact extends Activity {
13. /** Called when the activity is first created. */
14. @Override
15. public void onCreate(Bundle savedInstanceState) {
16. super.onCreate(savedInstanceState);
17. setContentView(R.layout.main);
18. Uri uri = Contacts.People.CONTENT_URI;
19. String[] projection = {Contacts.People._ID, Contacts.People.PRIMARY_PHONE_ID, Contacts.PeopleColumns.NAME, Contacts.PeopleColumns.TIMES_CONTACTED};
20. String selection = Contacts.PeopleColumns.NAME + " like ?";
21. String[] selectionArgs = {"%li,%"};
22. String sortOrder = Contacts.PeopleColumns.NAME+" ASC";
23. Cursor cursor = managedQuery(uri, projection, selection, selectionArgs, sortOrder);
24. int nColumnIndex;
25. String id;
26. int phoneID;
27. String name;
28. String times;
29. ContentResolver cr = getContentResolver();
30. if(cursor.moveToFirst()){
31.
32. Log.i("lily", "total "+cursor.getCount()+" records.");
33.
34. do {
35. Log.i("lily", "***************************************");
36.
37. nColumnIndex = cursor.getColumnIndex(Contacts.People._ID);
38. id = cursor.getString(nColumnIndex);
39. Log.i("lily", "id = " + id);
40.
41. nColumnIndex = cursor.getColumnIndex(Contacts.People.PRIMARY_PHONE_ID);
42. phoneID = cursor.getInt(nColumnIndex);
43. Log.i("lily", "phoneID = " + phoneID);
44. Uri phoneuri = ContentUris.withAppendedId(Contacts.Phones.CONTENT_URI, phoneID);
45. String[] phoneprojection = {Contacts.Phones._ID, Contacts.PhonesColumns.NUMBER};
46. Cursor phonecursor = cr.query(phoneuri, phoneprojection, null, null, null);
47. if (phonecursor.moveToFirst()){
48. String phoneNumber = phonecursor.getString(phonecursor.getColumnIndex(Contacts.PhonesColumns.NUMBER));
49. Log.i("lily", "phoneNumber = " + phoneNumber);
50. }else{
51. Log.i("lily", "no phone number");
52. }
53. phonecursor.close();
54.
55.
56. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.NAME);
57. name = cursor.getString(nColumnIndex);
58. Log.i("lily", "name = "+ name);
59.
60. nColumnIndex = cursor.getColumnIndex(Contacts.PeopleColumns.TIMES_CONTACTED);
61. times = cursor.getString(nColumnIndex);
62. Log.i("lily", "contact times = "+times);
63.
64. Log.i("lily", "***************************************");
65. }while(cursor.moveToNext());
66. }else{
67. Log.i("lily", "no result");
68. }
69. cursor.close();
70. }
71.
72. @Override
73. protected void onResume() {
74.
75. super.onResume();
76. }
77.
78. }
发表评论
-
startActivityForResult 简介
2011-03-29 15:55 1284依次打开Activity A1--A2--A3--A4 这时 ... -
startActivityForResult
2011-03-29 15:49 1146startActivityForResult 方法-- ... -
史上最全的Android的Tab与TabHost讲解
2011-03-28 11:22 1591Tab与TabHost 这就是Tab,而盛放Tab的 ... -
Android对话框
2011-03-25 11:21 1125Android 对话框(Dialog)大全 ... -
PreferenceActivity详解
2011-03-25 11:15 1442为了引入这个概率 首先从需求说起 即:现有某Activity专 ... -
TCP/UDP/HTTP
2011-03-25 11:09 1125先来一个讲TCP、UDP和HTTP ... -
9png
2011-03-25 11:08 1914今天学习了用9png图来优化横屏竖屏的UI,使用sdk自带的工 ... -
Notification
2011-03-25 11:07 939Android系统的状态栏(Status Bar)中有一个创新 ... -
一些技巧
2011-03-25 11:03 7861:查看是否有存储卡插入 String status=Envi ... -
布局像素单位
2011-03-25 11:03 826Android的layout文件中有时候可能会指定具体的单位, ... -
使用ActivityGroup来切换Activity和Layout
2011-03-25 11:02 1134在一个主界面中做Activity切换一般都会用TabActiv ... -
activitygroup
2011-03-25 11:01 1730说说tabhost和activitygroup 最近 ... -
线程
2011-03-25 11:01 1013今天在论坛上看到一些关于线程的帖子,我觉得与我理解的有些差异, ... -
类级框架
2011-03-25 11:00 744类集框架:Collection,Map,Iterator,En ... -
Intent打电话
2011-03-25 11:00 1217intent英文意思是意图,pending表示即将发生或来临的 ... -
Intent Uri
2011-03-25 10:59 1068进入联系人页面 1.Intent intent = new I ... -
Service
2011-03-25 10:59 939一、Service的概念 Service是Android程序中 ... -
Broadcast Receiver
2011-03-25 10:56 1948一、Broadcast Receiver简介 Android中 ... -
ContentProvider MIME类型
2011-03-25 10:55 1237Android程序的主要4部分 ... -
ContentProvider-2modify data:insert,update,delete
2011-03-25 10:54 1200今天补充关于modify data ...
相关推荐
1. **ContentProvider基础** - ContentProvider的结构:ContentProvider由一系列的类方法组成,包括`query()`, `insert()`, `update()`, `delete()`和`getType()`,分别对应数据的查询、插入、更新、删除和获取数据...
1. **继承自ContentProvider的自定义类**:这是ContentProvider的核心,你需要在这个类中实现各种操作数据的方法,如insert、delete、update和query。 2. **UriMatcher**:这是一个工具类,用于匹配不同的URI,根据...
#### 1. SQLite 数据库 **SQLite** 是一种轻量级的数据库,适用于移动设备。它被集成到Android中,允许应用存储结构化数据。SQLite使用SQL语法进行数据操作,支持事务处理、多种索引类型以及用户自定义函数等特性。...
1. **Provider类**:这是ContentProvider的基类,你需要继承这个类并实现其中的一些关键方法。例如: - `onCreate()`: 这是ContentProvider初始化的地方,通常在这里进行数据库的初始化或其他准备工作。 - `query...
5. **使用ContentResolver**:在其他应用中,通过ContentResolver与ContentProvider交互,传递Uri和CursorLoader(用于异步加载数据)来执行查询、插入、更新和删除操作。 ContentProvider的优势在于,它不仅限于...
1. **异步查询过程**: - 当需要执行异步查询时,开发者首先创建一个`AsyncQueryHandler`实例,并关联到当前的`Context`。 - 使用`startQuery()`方法发起查询请求,该方法接受查询所需的参数,如`uri`(数据标识)...
下面我们将深入探讨ContentProvider的使用,并结合"ContentProviderApp1"和"ContentProviderApp2"这两个示例项目来阐述其核心概念。 1. **ContentProvider的基本结构** - `ContentProvider`是一个抽象类,你需要...
1. 创建ContentProvider: - 首先,需要创建一个继承自 `android.content.ContentProvider` 的子类,并实现其基本方法,如 `onCreate()`、`query()`、`insert()`、`update()`、`delete()` 和 `getType()`。 - `...
为了允许应用程序访问`ContentProvider`,在应用程序的`AndroidManifest.xml`文件中还需要添加对`ContentProvider`的查询权限。这通常是在`<queries>`标签内指定`<provider>`元素,如: ```xml ``` 这是Android...
1. 创建一个继承自`ContentProvider`的类。 2. 在这个类中重写`onCreate()`方法,初始化必要的资源。 3. 实现`query()`、`insert()`、`update()`、`delete()`等方法,这些方法分别对应于对数据的查询、插入、更新和...
1. **定义Uri匹配规则**:ContentProvider通过Uri(统一资源标识符)来识别和操作数据。在`AndroidManifest.xml`文件中声明`<provider>`标签,并在对应的ContentProvider类中创建一个内部类继承自`UriMatcher`,用于...
1. **创建自定义的ContentProvider子类**:如`MyContentProvider`,它实现了上述的CRUD方法。 2. **UriMatcher配置**:在`onCreate()`方法中初始化UriMatcher,为每个Uri模式添加相应的匹配规则。 3. **数据库操作...
1. 在AndroidManifest.xml中注册ContentProvider,设置标签,指定name(ContentProvider的全限定类名)、authorities(唯一标识符,通常为应用包名+表名)以及exported(是否允许其他应用访问)属性。 2. 定义URI...
1. **定义 ContentProvider 类**:继承自 ContentProvider 类,并重写必要的方法,如 `onCreate()`、`query()`、`insert()`、`update()` 和 `delete()`。 2. **声明 URI**:定义 URI 架构,用于区分不同的数据集和...
查询结果是一个`Cursor`对象,其中包含了所有联系人的信息。 2. 添加联系人 添加联系人涉及多个表,包括`Data`、`RawContacts`和`Accounts`等。首先创建一个`ContentValues`对象,填充联系人信息,然后使用`...
1. **ContentProvider基础** - ContentProvider是Android四大组件之一,它提供了统一的数据访问接口,可以处理不同类型的存储数据(如SQLite数据库、文件系统等)。 - 自定义ContentProvider需要继承`android....
1. **创建Provider类**:继承自Android的`android.content.ContentProvider`类,并重写其中的关键方法,如`onCreate()`、`query()`、`insert()`、`update()`、`delete()`等。`onCreate()`方法在ContentProvider启动...
1. **ContentProvider基本概念** ContentProvider是Android系统提供的一种数据存储和访问机制,它允许应用程序之间进行数据交换,而无需暴露底层数据库或文件系统。通过ContentProvider,应用的数据可以被其他应用...
1. **创建ContentProvider类**:首先,你需要继承`android.content.ContentProvider`类,并重写其中的关键方法,如`onCreate()`、`query()`、`insert()`、`update()`和`delete()`等。这些方法分别对应对数据进行查询...
ContentProvider基于URI(统一资源标识符)的工作机制,使得数据可以被其他应用查询、插入、更新或删除,从而打破了应用之间的数据隔离。本Demo将深入讲解如何创建和使用ContentProvider。 首先,创建...