文章目录
Uri
介绍
统一资源标识符(URI)是一种用于标识资源的字符串。它可以是一个网址、文件路径、或其他形式的资源定位符。在Android中,URI通常用于访问内容提供者(Content Provider)提供的数据。
举例:
-
获取设备上存储的所有图片
content://media/internal/images
-
获取设备上所有联系人信息
content://contacts/people/
-
获取ID为45的单个联系人信息
content://contacts/people/45
在Java中,可以通过Uri.parse
方法将字符串URI转换为Uri对象。
Uri uri = Uri.parse("content://contacts/people/45");
组成
- Scheme:
- 采用前缀
content://
,表示这是一个内容提供者的Uri
。 - 例如:
content://
- 采用前缀
- Authority:
- 通常采用应用程序的包名,这样可以确保其唯一性。
- 例如:
com.example.provider
- Path:
- 指定数据或资源的路径,可以包含具体的表名、资源名以及其他标识符。
- 例如:
/student/1
ContentResolver
ContentResolver
是 Android 框架提供的一个类,用于与内容提供者(Content Provider)交互,提供了一系列增删改查的方法对数据进行操作,这些方法以Uri
的形式对外提供数据
用法
ContentResolver
为应用程序提供了统一的接口来访问不同的ContentProvider
获取对象
使用getContentResolver()
方法获取ContentResolver
对象:
ContentResolver contentResolver = getContentResolver();
增删改查
-
增
Uri insert(Uri uri, ContentValues values);
插入新数据,并返回新插入数据的URI。
ContentValues
对象,包含了要插入的数据键值对
-
删
int delete(Uri uri, String selection, String[] selectionArgs);
删除匹配条件的数据,并返回删除的行数。
selection
: SQLWHERE
子句的筛选条件(不包括WHERE
关键字)。用来确定哪些行会被删除。selectionArgs
: 选择条件的参数数组。用于替代selection
中占位符(?
)
-
改
int update(Uri uri, ContentValues values, String selection, String[] selectionArgs);
更新匹配条件的数据,并返回更新的行数。
-
查
Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
查询数据,并返回一个
Cursor
对象。projection
: 指定你要返回的列。如果你想返回所有列,可以传入null
。sortOrder
: 指定排序的方式。
读取联系人
获取通讯录的数据
使用 ContentResolver
来访问系统通讯录中的数据
获取权限
在AndroidMainfest获取权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
配置ListView
在MainActivity中配置ListView
public class MainActivity extends AppCompatActivity {
// ArrayAdapter用于在ListView中显示联系人列表
ArrayAdapter<String> adapter;
// 存储联系人名称和电话号码的列表
List<String> contactsList = new ArrayList<>();
// 获取ListView
private ListView listView;
// 设置布局,请求权限,初始化ListView和Adapter。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.contacts_view)<