




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
第6單元ContentProviderAndroid移動開發(fā)基礎(chǔ)教程6.1ContentProvider和URI簡介無論數(shù)據(jù)的存儲方式是什么,ContentProvider以表的形式組織數(shù)據(jù),并將其呈現(xiàn)給其他應(yīng)用程序。例如Android系統(tǒng)內(nèi)置的用戶字典,它會存儲用戶想要保存的非標(biāo)準(zhǔn)字詞的拼寫,其數(shù)據(jù)的組織形式如表6.1所示。每一行表示一條數(shù)據(jù)記錄,每一列表示數(shù)據(jù)的一個字段。表6.1用戶字典的數(shù)據(jù)示例單詞用戶ID出現(xiàn)次數(shù)語言區(qū)域IDMapReduceuser1100en_US1precompileruser14200fr_FR2Appletuser2225fr_CA3constuser1255pt_BR4intuser5100en_UK56.1ContentProvider和URI簡介開發(fā)者如果想將自己的應(yīng)用程序中的數(shù)據(jù)暴露給其他應(yīng)用,必須繼承ContentProvider基類實(shí)現(xiàn)數(shù)據(jù)的增、刪、改、查。基類ContentProvider提供了相關(guān)的方法供子類實(shí)現(xiàn),具體如表6.2所示。表6.2ContentProvider提供的方法方法abstractbooleanonCreate()其他應(yīng)用程序第一次訪問ContentProvider時會回調(diào)該方法,可以在其中做一些初始化操作abstractUriinsert(Uriuri,ContentValuesvalues)子類實(shí)現(xiàn)該方法以處理插入請求abstractintdelete(Uriuri,Stringselection,String[]selectionArgs)子類實(shí)現(xiàn)該方法以處理刪除請求abstractintupdate(Uriuri,ContentValuesvalues,Stringselection,String[]selectionArgs)子類實(shí)現(xiàn)該方法以處理更新請求abstractCursorquery(Uriuri,String[]projection,Stringselection,String[]selectionArgs,StringsortOrder)子類實(shí)現(xiàn)該方法以處理查詢請求abstractStringgetType(Uriuri)獲取數(shù)據(jù)的MIME類型6.1ContentProvider和URI簡介Android中URI的形式一般如下:content://authority/XXX。其中content://是固定的格式,類似于網(wǎng)絡(luò)請求中的http://。authority唯一標(biāo)識了一個ContentProvider,系統(tǒng)就是根據(jù)authority部分找到對應(yīng)的ContentProvider的。×××部分指向了ContentProvider中的數(shù)據(jù),這部分是可以動態(tài)改變的。另外,許多內(nèi)容提供者都允許通過將ID值追加到URI的末尾來準(zhǔn)確訪問數(shù)據(jù)表中的某一行記錄,例如對于content://user_dictionary/words/4,user_dictionary就是URI的authority部分,words/4表示訪問words數(shù)據(jù)的第4條記錄。6.2創(chuàng)建ContentProvider一般在開發(fā)過程中,很少需要實(shí)現(xiàn)自定義的ContentProvider,因?yàn)楹苌儆袘?yīng)用程序需要對外暴露自己的數(shù)據(jù)。但是,了解ContentProvider的創(chuàng)建過程可以幫助我們更好地理解如何使用ContentResovler訪問系統(tǒng)已經(jīng)提供的ContentProvider。在AndroidManifest.xml中配置該ContentProvider定義一個類,它繼承自ContentProvider類,并實(shí)現(xiàn)父類的onCreate()、insert()、delete()、update()、query()和getType()方法定義一個名為CONTENT_URI的URI對象,用作該ContentProvider的標(biāo)識6.2創(chuàng)建ContentProvider任務(wù)6.1創(chuàng)建ContentProvider,對外提供學(xué)生信息【任務(wù)代碼】publicclassConstantsimplementsBaseColumns{//URI的authority部分
publicstaticfinalStringAUTHORITY="vider";//ContentProvider的CONTENT_URIpublicstaticfinalUriCONTENT_URI=Uri.parse("content://"+AUTHORITY+"/students");//定義數(shù)據(jù)的MIME類型(多行數(shù)據(jù))
publicstaticfinalStringDATA_TYPE="vnd.android.cursor.dir/.vider.student";//定義數(shù)據(jù)的MIME類型(單行數(shù)據(jù))
publicstaticfinalStringDATA_TYPE_ITEM="vnd.android.cursor.item/vider.student";//數(shù)據(jù)表的字段
publicstaticfinalString_ID="_id";publicstaticfinalStringSNO="sno";publicstaticfinalStringSNAME="sname";publicstaticfinalStringSAGE="sage";}創(chuàng)建一個工具類用于保存ContentProvider需要用到的常量,示例代碼如下6.2創(chuàng)建ContentProviderpublicclassCustomProviderextendsContentProvider{privatestaticfinalUriMatchermatcher=newUriMatcher(UriMatcher.NO_MATCH);privatestaticfinalintSTUDENT_ALL=0;privatestaticfinalintSTUDENT_ITEM=1;privateDBOpenHelpermDBHelper;static{matcher.addURI(Constants.AUTHORITY,"students",STUDENT_ALL);matcher.addURI(Constants.AUTHORITY,"students/#",STUDENT_ITEM);}@OverridepublicbooleanonCreate(){mDBHelper=newDBOpenHelper(getContext(),"students.db",1);returntrue;}@Overridepublicintdelete(Uriuri,Stringselection,String[]selectionArgs){SQLiteDatabasedb=mDBHelper.getWritableDatabase();intnum=0;實(shí)現(xiàn)一個類,它繼承自ContentProvider類,其中數(shù)據(jù)的存儲方式可以有多種,示例代碼采用SQLite進(jìn)行數(shù)據(jù)的存取6.2創(chuàng)建ContentProviderswitch(matcher.match(uri))//解析URI{caseSTUDENT_ALL://刪除多條記錄
{num=db.delete("student",selection,selectionArgs);break;}caseSTUDENT_ITEM://刪除單條記錄
{longid=ContentUris.parseId(uri);//解析URI中的IDStringstr=Constants._ID+"="+id;//根據(jù)ID組成查詢條件
if(!TextUtils.isEmpty(selection)){//加上傳遞過來的查詢條件
selection=selection+"and"+str;}num=db.delete("student",selection,selectionArgs);break;}default:num=0;break;}6.2創(chuàng)建ContentProvider
//通知數(shù)據(jù)發(fā)生改變
getContext().getContentResolver().notifyChange(uri,null);returnnum;}@OverridepublicUriinsert(Uriuri,ContentValuesvalues){SQLiteDatabasedb=mDBHelper.getWritableDatabase();//向數(shù)據(jù)庫中插入一條數(shù)據(jù)
longrowId=db.insert("student",Constants._ID,values);if(rowId>0)//如果插入成功
{//向數(shù)據(jù)表的URI追加新行的ID值
UrinewRowUri=ContentUris.withAppendedId(uri,rowId);//通知數(shù)據(jù)發(fā)生改變
getContext().getContentResolver().notifyChange(newRowUri,null);returnnewRowUri;//返回新行數(shù)據(jù)的URI}returnnull;}6.2創(chuàng)建ContentProvider
@OverridepublicCursorquery(Uriuri,String[]projection,Stringselection,String[]selectionArgs,StringsortOrder){SQLiteDatabasedb=mDBHelper.getReadableDatabase();switch(matcher.match(uri))//解析URI{caseSTUDENT_ALL://訪問多條記錄
{returndb.query("student",projection,selection,selectionArgs,null,null,sortOrder);}caseSTUDENT_ITEM://訪問單條記錄
{longid=ContentUris.parseId(uri);//從URI中解析出IDStringstr=Constants._ID+"="+id;//根據(jù)ID組成查詢條件
if(!TextUtils.isEmpty(selection)){//加上傳遞過來的查詢條件
selection=selection+"and"+str;}returndb.query("student",projection,selection,selectionArgs,null,null,sortOrder);}default:returnnull;}}6.2創(chuàng)建ContentProvider@Overridepublicintupdate(Uriuri,ContentValuesvalues,Stringselection,String[]selectionArgs){SQLiteDatabasedb=mDBHelper.getWritableDatabase();intnum=0;switch(matcher.match(uri))//解析URI{caseSTUDENT_ALL://更新多條記錄
{num=db.update("student",values,selection,selectionArgs);break;}caseSTUDENT_ITEM://更新單條記錄
{longid=ContentUris.parseId(uri);//解析URI中的IDStringstr=Constants._ID+"="+id;//根據(jù)ID組成查詢條件
if(!TextUtils.isEmpty(selection)){//加上傳遞過來的查詢條件
selection=selection+"and"+str;}num=db.update("student",values,selection,selectionArgs);break;}6.2創(chuàng)建ContentProviderdefault:num=0;break;}//通知數(shù)據(jù)發(fā)生改變
getContext().getContentResolver().notifyChange(uri,null);returnnum;}@OverridepublicStringgetType(Uriuri){switch(matcher.match(uri)){caseSTUDENT_ALL://多行數(shù)據(jù)
returnConstants.DATA_TYPE;caseSTUDENT_ITEM://單行數(shù)據(jù)
returnConstants.DATA_TYPE_ITEM;default:returnnull;}}}6.2創(chuàng)建ContentProvider<providerandroid:name="com.demo.contentprovider.CustomProvider"android:authorities="vider"/>在AndroidManifest.xml中配置,具體如下6.3使用ContentResovler操作數(shù)據(jù)使用ContentResovler類可以訪問別的應(yīng)用程序通過ContentProvider提供的數(shù)據(jù),ContentResovler類常見的方法如表6.3所示。方法說明insert(Uriurl,ContentValuesvalues)向URI對應(yīng)的ContentProvider中插入數(shù)據(jù)delete(Uriurl,Stringwhere,String[]selectionArgs)刪除數(shù)據(jù)update(Uriuri,ContentValuesvalues,Stringwhere,String[]selectionArgs)更新數(shù)據(jù)query(Uriuri,String[]projection,Stringselection,String[]selectionArgs,StringsortOrder)查詢數(shù)據(jù)表6.3ContentResovler類常見的方法6.3使用ContentResovler操作數(shù)據(jù)任務(wù)6.2使用ContentResovler添加、查詢聯(lián)系人【任務(wù)代碼】Activity代碼:publicclassMainActivityextendsActivityimplementsOnClickListener{protectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ButtonbtnAdd=(Button)findViewById(R.id.btn_add);//獲取按鈕控件
ButtonbtnQuery=(Button)findViewById(R.id.btn_query);btnAdd.setOnClickListener(this);//設(shè)置監(jiān)聽器
btnQuery.setOnClickListener(this);}publicvoidonClick(Viewv){//處理單擊事件
switch(v.getId()){caseR.id.btn_add://添加數(shù)據(jù)
{add();break;}caseR.id.btn_query://查詢數(shù)據(jù)
{6.3使用ContentResovler操作數(shù)據(jù)query();break;}default:break;}}privatevoidadd(){ContentValuesvalues=newContentValues();//先插入一條空數(shù)據(jù),獲取當(dāng)前通訊錄中的IDUrirawContactUri=getContentResolver().insert(RawContacts.CONTENT_URI,values);longrawContactId=ContentUris.parseId(rawContactUri);//添加聯(lián)系人的姓名
values.put(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE);//插入單條數(shù)據(jù)
values.put(Data.RAW_CONTACT_ID,rawContactId);//設(shè)置IDvalues.put(StructuredName.GIVEN_NAME,"zhangsan");//設(shè)置姓名
getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);//插入數(shù)據(jù)6.3使用ContentResovler操作數(shù)據(jù)
//添加聯(lián)系人的電話號碼
values.put(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE);values.put(Data.RAW_CONTACT_ID,rawContactId);//設(shè)置IDvalues.put(Phone.NUMBER,"12340678910");//設(shè)置電話號碼
values.put(Phone.TYPE,Phone.TYPE_MOBILE);//設(shè)置電話號碼的類型
getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);}privatevoidquery(){ Cursorcursor=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);//查詢聯(lián)系人的數(shù)據(jù)
while(cursor.moveToNext())//遍歷
{//獲取數(shù)據(jù)的IDStringid=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));6.3使用ContentResovler操作數(shù)據(jù)String//獲取聯(lián)系人的姓名
name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));Cursor//根據(jù)ID查詢聯(lián)系人的電話號碼c=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone._ID+"="+id,null,null);while(c.moveToNext())//遍歷取出聯(lián)系人的電話號碼
{Stringphone=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));Log.i("contact","name:"+name+";phone:"+phone);}}}}6.4項(xiàng)目實(shí)戰(zhàn)——聯(lián)系人的相關(guān)操作通過一個項(xiàng)目來了解一下ContentResolver的使用場景。本項(xiàng)目會訪問系統(tǒng)中所有的聯(lián)系人并將其用列表展示出來,如圖6.1所示。長按聯(lián)系人姓名會彈出菜單,利用其中的命令可執(zhí)行相關(guān)操作,如圖6.2所示。選擇“刪除”命令會刪除當(dāng)前聯(lián)系人,選擇“撥號”命令會撥打該號碼。圖6.1聯(lián)系人列表圖6.2菜單6.4項(xiàng)目實(shí)戰(zhàn)——聯(lián)系人的相關(guān)操作【任務(wù)代碼】Activity代碼:publicclassMainActivityextendsActivity{privateListViewAdaptermAdapter;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mAdapter=newListViewAdapter(this);init();ListViewlistView=(ListView)findViewById(R.id.list_view);listView.setAdapter(mAdapter);listView.setOnCreateContextMenuListener(newOnCreateContextMenuListener(){@OverridepublicvoidonCreateContextMenu(ContextMenumenu,Viewv,ContextMenuInfomenuInfo){menu.setHeaderTitle("選擇操作");menu.add(0,0,0,"添加");menu.add(0,1,0,"刪除");menu.add(0,2,0,"撥號");}});}6.4項(xiàng)目實(shí)戰(zhàn)——聯(lián)系人的相關(guān)操作privatevoidinit(){List<Contact>contacts=newArrayList<Contact>();Cursorcursor=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,null);//查詢聯(lián)系人的數(shù)據(jù)
while(cursor.moveToNext())//遍歷
{//獲取數(shù)據(jù)的IDStringid=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));//獲取聯(lián)系人的姓名
Stringname=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));//根據(jù)ID查詢聯(lián)系人的電話號碼
Cursorc=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone._ID+"="+id,null,null);List<String>phones=newArrayList<String>();while(c.moveToNext())//遍歷取出聯(lián)系人的電話號碼
{Stringphone=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));phones.add(phone);}6.4項(xiàng)目實(shí)戰(zhàn)——聯(lián)系人的相關(guān)操作contacts.add(newContact(id,name,phones));}mAdapter.updateContacts(contacts);}@OverridepublicbooleanonContextItemSelected(MenuItemitem){AdapterContextMenuInfomenuInfo=(AdapterContextMenuInfo)item.getMenuInfo();//使用info.id得到ListView中選擇的子項(xiàng)綁定的IDintposition=menuInfo.position;Contactcontact=mAdapter.getItem(position);switch(item.getItemId()){case0:Toast.makeText(this,"add:"+contact.getContactName(),Toast.LENGTH_SHORT).show();returntrue;case1:deleteContact(contact);returntrue;case2:6.4項(xiàng)目實(shí)戰(zhàn)——聯(lián)系人的相關(guān)操作Intentintent=newIntent(Intent.ACTION_CALL);Uridata=Uri.parse("tel:"+contact.getPhone().get(0));
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 護(hù)理應(yīng)急演練方案制定與實(shí)施
- 孩子演講培訓(xùn)體系構(gòu)建
- 吊車安全課件
- 2025年北京教育融媒體中心招聘工作人員(17人)模擬試卷及答案詳解一套
- 2025企業(yè)內(nèi)部培訓(xùn)資料:03 股權(quán)激勵
- 2025年均四甲苯項(xiàng)目立項(xiàng)申請報(bào)告
- tpo聽力題目及答案pdf
- ai技術(shù)政治題目及答案
- 回盲部腫瘤診療規(guī)范與進(jìn)展
- 吉林省白城市前郭爾羅斯蒙古族自治縣蒙古族中學(xué)2021-2022學(xué)年高二上學(xué)期第二次月考生物試題(原卷版)
- 2025年中考英語作文話題終極預(yù)測
- 2025遼寧大連長興控股集團(tuán)有限公司及所屬公司招聘9人筆試參考題庫附帶答案詳解
- 門窗鋼副框施工方案
- 家園社協(xié)同育人中的矛盾與解決策略
- 出租車租車合同樣板
- 《測繪生產(chǎn)成本費(fèi)用定額》(2025版)
- 帶狀皰疹的護(hù)理-課件
- 慈善晚會籌備流程
- 統(tǒng)計(jì)學(xué)-形考任務(wù)4-國開-參考資料
- 肘管綜合癥護(hù)理查房
- 幼教培訓(xùn)課件:《幼兒園思維共享的組織與實(shí)施》
評論
0/150
提交評論