当前位置:网站首页>四大组件之ContentProvider
四大组件之ContentProvider
2022-07-27 17:02:00 【Ashurol】
首先来理解什么是ContentProvider,简单来说,有时候android应用需要把内部数据共享给其他数据时,这时ContentProvider以某种Uri的形式对外提供数据,允许其他应用访问或修改数据,此时其他应用就要使用ContentResolver根据Uri去访问操作指定的数据。也就是说ContentProvider的作用是暴露可供操作的数据。
//我们先来定义一个ContentProvider的子类,这个类并没有对底层数据进行访问,仅提供理解用
public class MyContentProvider extends ContentProvider{
//在ContetnProvider创建后被调用
public boolean onCreate() {
// TODO Auto-generated method stub
return false;
}
//返回当前uri的MIME类型,如果该URI对应的数据可能包括多条记录
//那么MIME类型字符串 就是以vnd.android.dir/开头
// 如果该URI对应的数据只有一条记录 该MIME类型字符串 就是以vnd.android.cursor.item/开头
public String getType(Uri uri) {
// TODO Auto-generated method stub
return null;
}
//下面方法可根据开发需要进行构建,比如你实现了增和删
//根据Uri插入Values对应的数据
public Uri insert(Uri uri, ContentValues values) {
// TODO Auto-generated method stub
return null;
}
//根据Uri删除selection指定 的条件所匹配的全部记录
public int delete(Uri uri, String selection, String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
//根据uri修改selection指定的条件所匹配的全部记录
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
}
//根据uri查询出selection指定的条件所匹配的全部记录,并且可以指定查询哪些列 以什么方式(order)排序
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO Auto-generated method stub
return null;
}
}//在ContentProvider供其他程序调用前,需要在manifest文件里配置该ContentProvider //在application里配置
<provider
android:name=".MyContentProvider"
android:authorities="org.crazyit.provider.firstprovider"
android:exported="true" />//现在我们继续创建一个其他应用程序的一个类,来模拟如何访问ContentProvider的Uri对应的数据
public class FirstResolver extends Activity{
//定义一个ContentResolver对象
ContentResolver cr;
//将字符串转化为Uri
Uri uri=Uri.parse("content://org.crazyit.provider.firstprovider/");
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取一个ContentResolver对象
cr=getContentResolver();
}
//监听方法
public void query(View source)
{
//调用ContentResolver的query()方法
//实际返回的是该Uri对应的ContentProvider的query的返回值
Cursor c=cr.query(uri, null, "query_where", null, null);
Toast.makeText(this, "远程ContentProvider返回的Cursor为:"+c, Toast.LENGTH_SHORT).show();
}
public void insert(View Source)
{
ContentValues va=new ContentValues();
va.put("name", "hahaha");
//调用ContentResolver的insert()方法
//实际返回的是该Uri对应的ContentProvider的insert()的返回值
Uri newUri=cr.insert(uri, va);
Toast.makeText(this, "远程ContentProvider新插入记录的Uri为:"+newUri, Toast.LENGTH_SHORT).show();
}
public void update(View source)
{
ContentValues va=new ContentValues();
va.put("name", "hahaha");
//调用ContentResolver的update()方法
//实际返回的是该Uri对应的ContentProvider的update()的返回值
int count=cr.update(uri, va, "update_where", null);
Toast.makeText(this, "远程ContentProvider更新记录数为:"+count, Toast.LENGTH_SHORT).show();
}
public void delete(View source)
{
//调用ContentResolver的delete()方法
//实际返回的是该Uri对应的ContentProvider的delete()的返回值
int count=cr.delete(uri, "delete_where", null);
Toast.makeText(this, "远程ContentProvider删除记录数为:"+count, Toast.LENGTH_SHORT).show();
}
}Android本身提供了大量的ContentProvider,例如联系人信息,系统多媒体,开发者也可以通过ContentResolver来调用系统ContentProvider提供的query(),insert(),update(),和delete()等方法。
//创建工程,对Android系统自带的通讯录进行操作
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver cr = getContentResolver();
Cursor c = cr.query(Contacts.CONTENT_URI, new String[] { Contacts._ID,
Contacts.DISPLAY_NAME }, null, null, null);
if (c != null) {
while (c.moveToNext()) {
int id = c.getInt(c.getColumnIndex("_id"));
Log.i("info", "_id:" + id);
Log.i("info",
"name:" + c.getString(c.getColumnIndex("display_name")));
Cursor c1 = cr.query(Phone.CONTENT_URI, new String[] {
Phone.NUMBER, Phone.TYPE },
Phone.CONTACT_ID + "=" + id, null, null);
// 根据联系人ID查询出联系人的电话号码
if (c1 != null) {
while (c1.moveToNext()) {
int type = c1.getInt(c1.getColumnIndex(Phone.TYPE));
if (type == Phone.TYPE_HOME) {
Log.i("info",
"家庭电话:"
+ c1.getString(c1
.getColumnIndex(Phone.NUMBER)));
} else if (type == Phone.TYPE_MOBILE) {
Log.i("info",
"手机:"
+ c1.getString(c1
.getColumnIndex(Phone.NUMBER)));
}
}
c1.close();
}
// 根据联系人的ID去查询出联系人的邮箱地址
Cursor c2 = cr.query(Email.CONTENT_URI, new String[] {
Email.DATA, Email.TYPE }, Email.CONTACT_ID + "=" + id,
null, null);
if (c2 != null) {
while (c2.moveToNext()) {
int type = c2.getInt(c2.getColumnIndex(Email.DATA));
if (type == Email.TYPE_WORK) {
Log.i("info",
"工作1邮箱:"
+ c2.getString(c2
.getColumnIndex(Email.DATA)));
}
}
c2.close();
}
}
c.close();
}
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver cr = getContentResolver();
//向联系人中 插入一行数据
ContentValues values = new ContentValues();
Uri uri = cr.insert(RawContacts.CONTENT_URI, values);
Long raw_contact_id = ContentUris.parseId(uri);
values.clear();
//插入人名
values.put(StructuredName.RAW_CONTACT_ID, raw_contact_id);
values.put(StructuredName.DISPLAY_NAME, "张三三");
values.put(StructuredName.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
uri = cr.insert(Data.CONTENT_URI, values);
//插入电话信息
values.clear();
values.put(Phone.RAW_CONTACT_ID,raw_contact_id);
values.put(Phone.NUMBER,"13333333333");
values.put(Phone.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
uri = cr.insert(Data.CONTENT_URI, values);}


边栏推荐
- 一种比读写锁更快的锁,还不赶紧认识一下
- 估值超156亿元!华勤通讯完成10亿元B轮融资!高通创投、英特尔资本领投
- Incluxdb series (III) detailed explanation of incluxdb configuration file
- I want to consult. Our maxcompute spark program needs to access redis, development environment and production environment redis
- Chinese character search Pinyin wechat applet project source code
- 【深度学习基础知识 - 44】逻辑回归实现多分类的方法
- To create a MySQL data source resource group, you must choose to create a new exclusive data integration resource group? Or use a common resource group? thank you
- rxbinding
- High cost, difficult to implement, slow to take effect, what about open source security?
- 【深度学习基础知识 - 43】优势比的概念
猜你喜欢

C language: 11. Pipeline

c语言:10、输入流,输出流,错误流

c语言:clion调试方法

GestureOverlayView(手势识别2)

Complete source code of E-commerce mall applet project (wechat applet)

High cost, difficult to implement, slow to take effect, what about open source security?
Dry goods of technical practice | preliminary exploration of large-scale gbdt training

5W bonus pool / for colleges and universities, 2022 legal science and technology innovation competition is in progress

rxbinding

Low code implementation exploration (45) business parameters
随机推荐
【深度学习基础知识 - 47】贝叶斯网络与朴素贝叶斯
The first Xiaolong 765G! Redmi K30 5g release: support 5g dual-mode 120Hz screen, priced from 1999 yuan
Summary of APP launch in vivo application market
一种比读写锁更快的锁,还不赶紧认识一下
Hardware acceleration of zero knowledge proof
英特尔推出全球最小的高分辨率激光雷达,售价仅349美元
The valuation exceeds 15.6 billion yuan! Huaqin communication completed the round B financing of 1billion yuan! Qualcomm venture capital, Intel Capital led investment
Golang sets the domestic image, vscode configures the golang development environment, and vscode debugs the golang code
Release Samsung 3J1 sensor: the code implies that the safety of pixel 7 face recognition will be greatly increased
The first in the field of mobile phone chip design in the world! Ziguang zhanrui won the international certification of tmmi4
Pytorch reports CUDA error: no kernel image is available for execution on the device error
【深度学习基础知识 - 37】解决正负样本不均衡 Focal Loss
Introduction to several wireless protocols
GestureDetector(手势识别)
GestureOverlayView(手势识别2)
估值超156亿元!华勤通讯完成10亿元B轮融资!高通创投、英特尔资本领投
Under the heat wave of Web3.0, the ecological shock of Mensa struck
[basic knowledge of deep learning - 48] characteristics of Bayesian network
【日常积累 - 06】查看cuda和cudnn版本
电商商城小程序项目完整源码(微信小程序)