android第一行代码-9.内容提供器

内容提供器(Content Provider)主要用于在不同的应用程序之间实现数据共享的功能, 内容提供器包括两部分:使用现有的内容提供器来读取和操作相应程序中的数据跟创建自己的内容提供器给我们程序的数据提供外部访问接口。

1.使用现有的内容提供器来读取和操作相应程序中的数据

想要访问内容提供器中共享的数据,就一定要借助ContentResolver。可以通过 Context 中的 getContentResolver()方法获取到该类的实例。ContentResolver 中提供了一系列的方法用于对数据进行 CRUD 操作,其中 insert()方法用于 添加数据,update()方法用于更新数据,delete()方法用于删除数据,query()方法用于查询数据。有区别的是,ContentResolve 接收的不是表名参数,而是Uri(Uri uri=Uri.parse("content://com.example.app.provider/table1")).

(1)获取uri

Uri uri = Uri.parse("content://com.example.app.provider/table1")

(2)数据操作

#查询
Cursor cursor = getContentResolver().query( uri, projection, selection, selectionArgs, sortOrder);
if (cursor != null) { while (cursor.moveToNext()) { String column1 = cursor.getString(cursor.getColumnIndex("column1")); int column2 = cursor.getInt(cursor.getColumnIndex("column2")); } cursor.close(); }

#插入数据
ContentValues values = new ContentValues();
values.put("column1", "text");
values.put("column2", 1);
getContentResolver().insert(uri, values);
 

2.创建自己的内容提供器给我们程序的数据提供外部访问接口 

原文地址:https://www.cnblogs.com/alexkn/p/5574969.html