內容提供器的用法一般有兩種:
1.使用現有的內容提供器來讀取和操作相應程式中的資料。
2。建立自己的內容提供器給我們程式的資料提供外部訪問介面。
contentresolver的基本用法
要想訪問內容提供器中共享的資料:就一定要借助contentresolver類。
可以通過context中的getcontentresolver()方法獲取到該類的例項。
contentresolver中提供了一系列的方法用於對資料進行crud操作。
public uri insert
(uri uri, contentvalues values)
//該方法用於往contentprovider新增資料。
public
intdelete
(uri uri, string selection, string[
] selectionargs)
//該方法用於從contentprovider刪除資料。
public
intupdate
(uri uri, contentvalues values, string selection, string[
] selectionargs)
//該方法用於更新contentprovider中的資料。
public cursor query
(uri uri, string[
] projection, string selection, string[
] selectionargs, string sortorder)
//該方法用於從contentprovider中獲取資料。
可能發現了,contentresolver中的增刪改查方法都是不接收表名引數的,而是使用乙個uri引數代替,這個引數被稱為內容uri。內容uri給內容提供器中的資料建立了唯一識別符號,它主要由兩部分組成:
1:authority:用於對不同的應用程式做區分的,一般為了避免衝突,都會採用程式包名的方式來進行命名。
2:path:用於對同一應用程式中不同的表做區分的,通常都會新增到authority的後面。
3:最後我們還需要在字串的頭部加上協議宣告。
例如:
content:
/content:
/
在得到了內容uri字串之後,我們還需要將它解析成uri物件才可以作為引數傳入。**如下:
uri uri = uri.
parse()
;
只需要呼叫uri.parse()方法,就可以將內容uri字串解析成uri物件。
cursor cursor =
getcontentresolver()
.query
( uri,
//指定查詢某個應用程式下的某一張表
projection,
//指定查詢的列名
selection,
//指定where的約束條件
selectionargs,
//為where中的佔位符提供具體的值
sortorder)
;//指定查詢結果的排序方式
if
(cursor != null)
cursor.
close()
;}
contentvalues values =
newcontentvalues()
;values.
put(
"column1"
,"text");
values.
put(
"column2"
,"1");
getcontentresolver()
.insert
(uri,values)
;
可以看到,仍然是將待新增的資料組裝到contentvalues中,然後呼叫contentresolver的insert()方法,將uri和contentvalues作為引數傳入即可。
contentvalues values=
newcontentvalues()
;values.
put(
"column1",""
);getcontentresolver()
.update
(uri,values,
"column1 = ? and column2 = ?"
,new
string
);
注意上述**使用了selection和selectionargs引數來對想要更新的資料進行約束,以防止所有的行都會受影響。
getcontentresolver()
.delete
(uri,
"column2 = ?"
,new
string
);
Android基礎之內容提供者
應用程式建立的資料庫預設都是私有的,別的應用程式不可以訪問裡面的資料。如果有需求把自己應用程式私有的資料庫暴露給別的使用者,就需要使用內容提供者 a應用中 1,建立資料庫bankdbopenhelper public class bankdbopenhelper extends sqliteopen...
android 內容提供器簡介
我們學了 android 資料持久化的技術,包括檔案儲存 sharedpreferences 存 儲 以及資料庫儲存。不知道你有沒有發現,使用這些持久化技術所儲存的資料都只能在當 前應用程式中訪問。雖然檔案和 sharedpreferences 儲存中提供了 mode world readable ...
Android四大元件之 內容提供者
內容提供者說簡單了就是像外提供乙個uri,然後別人去匹配這個uri就可以使用你定義好的一些方法 下面寫個例項來介紹一下contentprodvider 寫乙個內容提供者的類 personcontentprovider 類 package com.example.sqlitedemo.provider...