SQLite介紹:小型關係數據庫,佔用空間很小。
我們可以使用SQLiteOpenHelper類來創建數據庫對象。這個類有以下方法:
getReadableDatabase():獲得一個可讀的數據庫。
getWritableDatabase():獲得一個可寫的數據庫。
下面是三個回調函數:
onCreate(SQLiteDatabase db):當創建數據庫的時候會自動調用此方法。
onOpen(SQLiteDatabase db):當打開數據庫的時候會自動調用此方法。
onUpgrade(SQLiteDatabse db , int oldVersion , int newVersion):
當更新數據庫的時候會自動調用此方法。
當我們創建完畢數據庫對象以後 就可以用數據庫對象來進行增刪改查等工作、
我們寫一個類繼承這個SQLiteOpenHelper類 重寫裏面的構造方法和onCreate以及onUpgrade方法。然後可以通過我們寫的這個類獲通過getReadableDatabase()或者getWritableDatabase()方法獲得一個操作數據庫的對象對數據庫進行增刪改查等操作。
public class DBOpenHelper extends SQLiteOpenHelper {
public DBOpenHelper(Context context) {
super(context, "itcast.db", null, 3);
}
@Override
public void onCreate(SQLiteDatabase db) {//在數據庫第一次被創建時調用
db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20), phone VARCHAR(12) NULL)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("ALTER TABLE person ADD amount integer");
}
}
package cn.itcast.service;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.itcast.db.DBOpenHelper;
import cn.itcast.domain.Person;
public class PersonService {
private DBOpenHelper dbOpenHelper;
public PersonService(Context context){
dbOpenHelper = new DBOpenHelper(context);
}
public void payment(){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.beginTransaction();
try{
db.execSQL("update person set amount=amount-10 where personid=1");
db.execSQL("update person set amount=amount+10 where personid=2");
db.setTransactionSuccessful();
}finally{
//事務標誌的默認值爲false
db.endTransaction();//提交、回滾,由事務標誌決定,如果事務標誌爲True(成功),提交,否則回滾
}
}
public void save(Person person){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("insert into person(name,phone,amount) values(?,?,?)",
new Object[]{person.getName(), person.getPhone(), person.getAmount()});
//db.close();
}
public void update(Person person){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("update person set name=?,phone=?,amount=? where personid=?",
new Object[]{person.getName(), person.getPhone(), person.getAmount(), person.getId()});
}
public Person find(Integer id){
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from person where personid=?", new String[]{id.toString()});
if(cursor.moveToFirst()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
int amount = cursor.getInt(cursor.getColumnIndex("amount"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
cursor.close();
return new Person(personid, name, phone, amount);
}
return null;
}
public void delete(Integer id){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("delete from person where personid=?", new Object[]{id});
}
public List<Person> getScrollData(int offset, int maxResult){
List<Person> persons = new ArrayList<Person>();
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from person order by personid asc limit ?,?",
new String[]{String.valueOf(offset), String.valueOf(maxResult)});
while(cursor.moveToNext()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
int amount = cursor.getInt(cursor.getColumnIndex("amount"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
persons.add(new Person(personid, name, phone, amount));
}
cursor.close();
return persons;
}
public long getCount(){
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select count(*) from person", null);
cursor.moveToFirst();
return cursor.getLong(0);
}
}
-------------------------------------------------------------------------
SQLite 基本上符合 SQL-92 標準,和其他的主要 SQL 數據庫沒什麼區別。它的優點就是高效,Android 運行時環境包含了完整的 SQLite。
SQLite 和其他數據庫最大的不同就是對數據類型的支持,創建一個表時,可以在 CREATE TABLE 語句中指定某列的數據類型,但是你可以把任何數據類型放入任何列中。當某個值插入數據庫時,SQLite 將檢查它的類型。如果該類型與關聯的列不匹配,則 SQLite 會嘗試將該值轉換成該列的類型。如果不能轉換,則該值將作爲其本身具有的類型存儲。比如可以把一個字符串(String)放入 INTEGER 列。SQLite 稱這爲“弱類型”(manifest typing.)。
此外,SQLite 不支持一些標準的 SQL 功能,特別是外鍵約束(FOREIGN KEY constrains),嵌套 transcaction 和 RIGHT OUTER JOIN 和 FULL OUTER JOIN, 還有一些 ALTER TABLE 功能。
除了上述功能外,SQLite 是一個完整的 SQL 系統,擁有完整的觸發器,交易等等。
Android 集成了 SQLite 數據庫
Android 在運行時(run-time)集成了 SQLite,所以每個 Android 應用程序都可以使用 SQLite 數據庫。對於熟悉 SQL 的開發人員來時,在 Android 開發中使用 SQLite 相當簡單。但是,由於 JDBC 會消耗太多的系統資源,所以 JDBC 對於手機這種內存受限設備來說並不合適。因此,Android 提供了一些新的 API 來使用 SQLite 數據庫,Android 開發中,程序員需要學使用這些 API。
數據庫存儲在 data/< 項目文件夾 >/databases/ 下。
Android 開發中使用 SQLite 數據庫
Activites 可以通過 Content Provider 或者 Service 訪問一個數據庫。下面會詳細講解如果創建數據庫,添加數據和查詢數據庫。
創建數據庫
Android 不自動提供數據庫。在 Android 應用程序中使用 SQLite,必須自己創建數據庫,然後創建表、索引,填充數據。Android 提供了 SQLiteOpenHelper 幫助你創建一個數據庫,你只要繼承 SQLiteOpenHelper 類,就可以輕鬆的創建數據庫。SQLiteOpenHelper 類根據開發應用程序的需要,封裝了創建和更新數據庫使用的邏輯。SQLiteOpenHelper 的子類,至少需要實現三個方法:
?構造函數,調用父類 SQLiteOpenHelper 的構造函數。這個方法需要四個參數:上下文環境(例如,一個 Activity),數據庫名字,一個可選的遊標工廠(通常是 Null),一個代表你正在使用的數據庫模型版本的整數。
?onCreate()方法,它需要一個 SQLiteDatabase 對象作爲參數,根據需要對這個對象填充表和初始化數據。
?onUpgrage() 方法,它需要三個參數,一個 SQLiteDatabase 對象,一箇舊的版本號和一個新的版本號,這樣你就可以清楚如何把一個數據庫從舊的模型轉變到新的模型。
下面示例代碼展示瞭如何繼承 SQLiteOpenHelper 創建數據庫:
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version)
{
super(context, name, cursorFactory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO 創建數據庫後,對數據庫的操作
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO 更改數據庫版本的操作
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
// TODO 每次成功打開數據庫後首先被執行
}
}
接下來討論具體如何創建表、插入數據、刪除表等等。調用 getReadableDatabase() 或 getWriteableDatabase() 方法,你可以得到 SQLiteDatabase 實例,具體調用那個方法,取決於你是否需要改變數據庫的內容:
db=(new DatabaseHelper(getContext())).getWritableDatabase();
return (db == null) ? false : true;
上面這段代碼會返回一個 SQLiteDatabase 類的實例,使用這個對象,你就可以查詢或者修改數據庫。
當你完成了對數據庫的操作(例如你的 Activity 已經關閉),需要調用 SQLiteDatabase 的 Close() 方法來釋放掉數據庫連接。
創建表和索引
爲了創建表和索引,需要調用 SQLiteDatabase 的 execSQL() 方法來執行 DDL 語句。如果沒有異常,這個方法沒有返回值。
例如,你可以執行如下代碼:
db.execSQL("CREATE TABLE mytable (_id INTEGER PRIMARY KEY
AUTOINCREMENT, title TEXT, value REAL);");
這條語句會創建一個名爲 mytable 的表,表有一個列名爲 _id,並且是主鍵,這列的值是會自動增長的整數(例如,當你插入一行時,SQLite 會給這列自動賦值),另外還有兩列:title( 字符 ) 和 value( 浮點數 )。 SQLite 會自動爲主鍵列創建索引。
通常情況下,第一次創建數據庫時創建了表和索引。如果你不需要改變表的 schema,不需要刪除表和索引 . 刪除表和索引,需要使用 execSQL() 方法調用 DROP INDEX 和 DROP TABLE 語句。
給表添加數據
上面的代碼,已經創建了數據庫和表,現在需要給表添加數據。有兩種方法可以給表添加數據。
像上面創建表一樣,你可以使用 execSQL() 方法執行 INSERT, UPDATE, DELETE 等語句來更新表的數據。execSQL() 方法適用於所有不返回結果的 SQL 語句。例如:
db.execSQL("INSERT INTO widgets (name, inventory)"+
"VALUES ('Sprocket', 5)");
另一種方法是使用 SQLiteDatabase 對象的 insert(), update(), delete() 方法。這些方法把 SQL 語句的一部分作爲參數。示例如下:
ContentValues cv=new ContentValues();
cv.put(Constants.TITLE, "example title");
cv.put(Constants.VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
db.insert("mytable", getNullColumnHack(), cv);
update()方法有四個參數,分別是表名,表示列名和值的 ContentValues 對象,可選的 WHERE 條件和可選的填充 WHERE 語句的字符串,這些字符串會替換 WHERE 條件中的“?”標記。update() 根據條件,更新指定列的值,所以用 execSQL() 方法可以達到同樣的目的。
WHERE 條件和其參數和用過的其他 SQL APIs 類似。例如:
String[] parms=new String[] {"this is a string"};
db.update("widgets", replacements, "name=?", parms);
delete() 方法的使用和 update() 類似,使用表名,可選的 WHERE 條件和相應的填充 WHERE 條件的字符串。
查詢數據庫
類似 INSERT, UPDATE, DELETE,有兩種方法使用 SELECT 從 SQLite 數據庫檢索數據。
1 .使用 rawQuery() 直接調用 SELECT 語句;
使用 query() 方法構建一個查詢。
?Raw Queries
正如 API 名字,rawQuery() 是最簡單的解決方法。通過這個方法你就可以調用 SQL SELECT 語句。例如:
Cursor c=db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table' AND name='mytable'", null);
在上面例子中,我們查詢 SQLite 系統表(sqlite_master)檢查 table 表是否存在。返回值是一個 cursor 對象,這個對象的方法可以迭代查詢結果。
如果查詢是動態的,使用這個方法就會非常複雜。例如,當你需要查詢的列在程序編譯的時候不能確定,這時候使用 query() 方法會方便很多。
?Regular Queries
query() 方法用 SELECT 語句段構建查詢。SELECT 語句內容作爲 query() 方法的參數,比如:要查詢的表名,要獲取的字段名,WHERE 條件,包含可選的位置參數,去替代 WHERE 條件中位置參數的值,GROUP BY 條件,HAVING 條件。
除了表名,其他參數可以是 null。所以,以前的代碼段可以可寫成:
String[] columns={"ID", "inventory"};
String[] parms={"snicklefritz"};
Cursor result=db.query("widgets", columns, "name=?",parms, null, null, null);
使用遊標
不管你如何執行查詢,都會返回一個 Cursor,這是 Android 的 SQLite 數據庫遊標,使用遊標,你可以:
通過使用 getCount() 方法得到結果集中有多少記錄;
通過 moveToFirst(), moveToNext(), 和 isAfterLast() 方法遍歷所有記錄;
通過 getColumnNames() 得到字段名;
通過 getColumnIndex() 轉換成字段號;
通過 getString(),getInt() 等方法得到給定字段當前記錄的值;
通過 requery() 方法重新執行查詢得到遊標;
通過 close() 方法釋放遊標資源;
例如,下面代碼遍歷 mytable 表
Cursor result=db.rawQuery("SELECT ID, name, inventory FROM mytable");
result.moveToFirst();
while (!result.isAfterLast()) {
int id=result.getInt(0);
String name=result.getString(1);
int inventory=result.getInt(2);
// do something useful with these
result.moveToNext();
}
result.close();
在 Android 中使用 SQLite 數據庫管理工具
在其他數據庫上作開發,一般都使用工具來檢查和處理數據庫的內容,而不是僅僅使用數據庫的 API。使用 Android 模擬器,有兩種可供選擇的方法來管理數據庫。
首先,模擬器綁定了 sqlite3 控制檯程序,可以使用 adb shell 命令來調用他。只要你進入了模擬器的 shell,在數據庫的路徑執行 sqlite3 命令就可以了。數據庫文件一般存放在:
/data/data/your.app.package/databases/your-db-name
如果你喜歡使用更友好的工具,你可以把數據庫拷貝到你的開發機上,使用 SQLite-aware 客戶端來操作它。這樣的話,你在一個數據庫的拷貝上操作,如果你想要你的修改能反映到設備上,你需要把數據庫備份回去。
把數據庫從設備上考出來,你可以使用 adb pull 命令(或者在 IDE 上做相應操作)。存儲一個修改過的數據庫到設備上,使用 adb push 命令。
一個最方便的 SQLite 客戶端是 FireFox SQLite Manager 擴展,它可以跨所有平臺使用。
contentprovider的學習實例總結
工作中遇到了contentprovider數據共享機制,下面來總結一下:
一、ContentProvider簡介
當應用繼承ContentProvider類,並重寫該類用於提供數據和存儲數據的方法,就可以向其他應用共享其數據。雖然使用其他方法也可以對外共享數據,但數據訪問方式會因數據存儲的方式而不同,如:採用文件方式對外共享數據,需要進行文件操作讀寫數據;採用sharedpreferences共享數據,需要使用sharedpreferences API讀寫數據。而使用ContentProvider共享數據的好處是統一了數據訪問方式。
二、Uri類簡介
Uri代表了要操作的數據,Uri主要包含了兩部分信息:1.需要操作的ContentProvider ,2.對ContentProvider中的什麼數據進行操作,一個Uri由以下幾部分組成:
1.scheme:ContentProvider(內容提供者)的scheme已經由Android所規定爲:content://。
2.主機名(或Authority):用於唯一標識這個ContentProvider,外部調用者可以根據這個標識來找到它。
3.路徑(path):可以用來表示我們要操作的數據,路徑的構建應根據業務而定,如下:
? 要操作contact表中id爲10的記錄,可以構建這樣的路徑:/contact/10
? 要操作contact表中id爲10的記錄的name字段, contact/10/name
? 要操作contact表中的所有記錄,可以構建這樣的路徑:/contact
要操作的數據不一定來自數據庫,也可以是文件等他存儲方式,如下:
要操作xml文件中contact節點下的name節點,可以構建這樣的路徑:/contact/name
如果要把一個字符串轉換成Uri,可以使用Uri類中的parse()方法,如下:
Uri uri = Uri.parse("content://com.changcheng.provider.contactprovider/contact")
三、UriMatcher、ContentUrist和ContentResolver簡介
因爲Uri代表了要操作的數據,所以我們很經常需要解析Uri,並從Uri中獲取數據。Android系統提供了兩個用於操作Uri的工具類,分別爲UriMatcher 和ContentUris 。掌握它們的使用,會便於我們的開發工作。
UriMatcher:用於匹配Uri,它的用法如下:
1.首先把你需要匹配Uri路徑全部給註冊上,如下:
//常量UriMatcher.NO_MATCH表示不匹配任何路徑的返回碼(-1)。
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//如果match()方法匹配content://com.changcheng.sqlite.provider.contactprovider/contact路徑,返回匹配碼爲1
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact”, 1);//添加需要匹配uri,如果匹配就會返回匹配碼
//如果match()方法匹配 content://com.changcheng.sqlite.provider.contactprovider/contact/230路徑,返回匹配碼爲2
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact/#”, 2);//#號爲通配符
2.註冊完需要匹配的Uri後,就可以使用uriMatcher.match(uri)方法對輸入的Uri進行匹配,如果匹配就返回匹配碼,匹配碼是調用addURI()方法傳入的第三個參數,假設匹配content://com.changcheng.sqlite.provider.contactprovider/contact路徑,返回的匹配碼爲1。
ContentUris:用於獲取Uri路徑後面的ID部分,它有兩個比較實用的方法:
? withAppendedId(uri, id)用於爲路徑加上ID部分
? parseId(uri)方法用於從路徑中獲取ID部分
ContentResolver:當外部應用需要對ContentProvider中的數據進行添加、刪除、修改和查詢操作時,可以使用ContentResolver 類來完成,要獲取ContentResolver 對象,可以使用Activity提供的getContentResolver()方法。 ContentResolver使用insert、delete、update、query方法,來操作數據。
四、ContentProvider示例程序
Manifest.xml中的代碼:
?
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestWebviewDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<data android:mimeType="vnd.android.cursor.dir/vnd.ruixin.login" />
</intent-filter>
<intent-filter>
<data android:mimeType="vnd.android.cursor.item/vnd.ruixin.login" />
</intent-filter>
</activity>
<provider android:name="MyProvider" android:authorities="com.ruixin.login" />
</application>
需要在<application></application>中爲provider進行註冊!!!!
首先定義一個數據庫的工具類:
?
public class RuiXin {
public static final String DBNAME = "ruixinonlinedb";
public static final String TNAME = "ruixinonline";
public static final int VERSION = 3;
public static String TID = "tid";
public static final String EMAIL = "email";
public static final String USERNAME = "username";
public static final String DATE = "date";
public static final String SEX = "sex";
public static final String AUTOHORITY = "com.ruixin.login";
public static final int ITEM = 1;
public static final int ITEM_ID = 2;
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ruixin.login";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ruixin.login";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/ruixinonline");
}
1. 然後創建一個數據庫:
?
public class DBlite extends SQLiteOpenHelper {
public DBlite(Context context) {
super(context, RuiXin.DBNAME, null, RuiXin.VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table "+RuiXin.TNAME+"(" +
RuiXin.TID+" integer primary key autoincrement not null,"+
RuiXin.EMAIL+" text not null," +
RuiXin.USERNAME+" text not null," +
RuiXin.DATE+" interger not null,"+
RuiXin.SEX+" text not null);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public void add(String email,String username,String date,String sex){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(RuiXin.EMAIL, email);
values.put(RuiXin.USERNAME, username);
values.put(RuiXin.DATE, date);
values.put(RuiXin.SEX, sex);
db.insert(RuiXin.TNAME,"",values);
}
}
1. 接着創建一個Myprovider.java對數據庫的接口進行包裝:
?
public class MyProvider extends ContentProvider{
DBlite dBlite;
SQLiteDatabase db;
private static final UriMatcher sMatcher;
static{
sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
sMatcher.addURI(RuiXin.AUTOHORITY,RuiXin.TNAME, RuiXin.ITEM);
sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME+"/#", RuiXin.ITEM_ID);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
db = dBlite.getWritableDatabase();
int count = 0;
switch (sMatcher.match(uri)) {
case RuiXin.ITEM:
count = db.delete(RuiXin.TNAME,selection, selectionArgs);
break;
case RuiXin.ITEM_ID:
String id = uri.getPathSegments().get(1);
count = db.delete(RuiXin.TID, RuiXin.TID+"="+id+(!TextUtils.isEmpty(RuiXin.TID="?")?"AND("+selection+')':""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI"+uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public String getType(Uri uri) {
// TODO Auto-generated method stub
switch (sMatcher.match(uri)) {
case RuiXin.ITEM:
return RuiXin.CONTENT_TYPE;
case RuiXin.ITEM_ID:
return RuiXin.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unknown URI"+uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
db = dBlite.getWritableDatabase();
long rowId;
if(sMatcher.match(uri)!=RuiXin.ITEM){
throw new IllegalArgumentException("Unknown URI"+uri);
}
rowId = db.insert(RuiXin.TNAME,RuiXin.TID,values);
if(rowId>0){
Uri noteUri=ContentUris.withAppendedId(RuiXin.CONTENT_URI, rowId);
getContext().getContentResolver().notifyChange(noteUri, null);
return noteUri;
}
throw new IllegalArgumentException("Unknown URI"+uri);
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
this.dBlite = new DBlite(this.getContext());
// db = dBlite.getWritableDatabase();
// return (db == null)?false:true;
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
db = dBlite.getWritableDatabase();
Cursor c;
Log.d("-------", String.valueOf(sMatcher.match(uri)));
switch (sMatcher.match(uri)) {
case RuiXin.ITEM:
c = db.query(RuiXin.TNAME, projection, selection, selectionArgs, null, null, null);
break;
case RuiXin.ITEM_ID:
String id = uri.getPathSegments().get(1);
c = db.query(RuiXin.TNAME, projection, RuiXin.TID+"="+id+(!TextUtils.isEmpty(selection)?"AND("+selection+')':""),selectionArgs, null, null, sortOrder);
break;
default:
Log.d("!!!!!!", "Unknown URI"+uri);
throw new IllegalArgumentException("Unknown URI"+uri);
}
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
}
最後創建測試類:
?
public class Test extends Activity {
/** Called when the activity is first created. */
private DBlite dBlite1 = new DBlite(this);;
private ContentResolver contentResolver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//先對數據庫進行添加數據
dBlite1.add(email,username,date,sex);
//通過contentResolver進行查找
contentResolver = TestWebviewDemo.this.getContentResolver();
Cursor cursor = contentResolver.query(
RuiXin.CONTENT_URI, new String[] {
RuiXin.EMAIL, RuiXin.USERNAME,
RuiXin.DATE,RuiXin.SEX }, null, null, null);
while (cursor.moveToNext()) {
Toast.makeText(
TestWebviewDemo.this,
cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL))
+ " "
+ cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME))
+ " "
+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE))
+ " "
+ cursor.getString(cursor.getColumnIndex(RuiXin.SEX)),
Toast.LENGTH_SHORT).show();
}
startManagingCursor(cursor); //查找後關閉遊標
}
}
注:上面是在一個程序中進行的測試,也可以再新建一個工程來模擬一個新的程序,然後將上面查詢的代碼加到新的程序當中!這樣就模擬了contentprovider的數據共享功能了!
新建個工程:TestProvider
創建一個測試的activity
?
public class Test extends Activity {
/** Called when the activity is first created. */
private ContentResolver contentResolver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//通過contentResolver進行查找
contentResolver = TestWebviewDemo.this.getContentResolver();
Cursor cursor = contentResolver.query(
RuiXin.CONTENT_URI, new String[] {
RuiXin.EMAIL, RuiXin.USERNAME,
RuiXin.DATE,RuiXin.SEX }, null, null, null);
while (cursor.moveToNext()) {
Toast.makeText(TestWebviewDemo.this,
cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL))
+ " "
+ cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME))
+ " "
+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE))
+ " "
+ cursor.getString(cursor.getColumnIndex(RuiXin.SEX)),
Toast.LENGTH_SHORT).show();
}
startManagingCursor(cursor); //查找後關閉遊標
}
}