学习ContentProvider---之一:查询数据库

来源:互联网 发布:文字编辑软件app 编辑:程序博客网 时间:2024/05/16 10:22

今天看了android的官方文档中ContentProvider的那部分,因为数据库使用我一直很晕乎,我想要完成自己写一个provider,再写一个工程来使用它读数据,建数据,所以今天先学习了如何查询的这部分知识,首先是一些从官方文档中总结出来的几点:

1.查询必备的三个条件:

1.TheURI that identifies the provider-->URI

2.The names of the data fields you want toreceive-->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()

例如:

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 — _IDNUMBERNUMBER_KEYNAME, 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.)

括号里面的这个功能很方便哟,我有试成功

 

 

具备了以上的基础之后,我写了一个例子来实现排序和模糊查找(需要使用正则表达式),不过我一直很想做的多表查询始终无果,有高手知道的麻烦告诉我一下吧。

代码如下:

最后附上一些我参考的网址:

Content Provider基础之SQL  http://notfatboy.javaeye.com/blog/653357

模糊查找 再深入 http://griffinshi.javaeye.com/blog/666875

Android 数据存取之Databases http://hi.baidu.com/_java/blog/item/f59a921cb633ec8387d6b6ed.html

还有SQLite的官方网站http://www.sqlite.org/optoverview.html#where_clause