1.Create 新增数据
ContentValues values = new ContentValues();
values.put("column1","content");
values.put("column2",1);
values.put("column3",true);
getContentResolver().insert(uri,values);
2.Retrieve 查询数据
Cursor cursor = getContentResolver().query(uri,projection,selection,selectionArgs,sortOrder);
查询方法所使用的五个参数,接下来对其逐一解释:
uri:Uri类型,对应于SQL中的“from table_name”,用于指定查询哪个程序下的哪一张表
project:String[]类型,对应去SQL中的“select column1,column2,……”,用于指定查询的列名
selection:String类型,对应于SQL中的“where column = value”,用于指定查询的约束条件
selectionArgs:String[]类型,为where语句中的占位符提供具体值
sortOder:String类型,对应于SQL中的“oder by column1,column2,……”,用于指定查询结果的排序方式
查询结果是一个Cursor对象,我们通过它逐个地将数据读取出来:
if(cursor!=null){
while(cursor.moveToNext()){
String column1= cursor.getString(cursor.getColumnIndex("column1"));
int column2= cursor.getInt(cursor.getColumnIndex("column2"));
}
cursor.close();
}
3.Update 更新数据
ContentValues values = new ContentValues();
values.put("column1","");
getContentResolver().update(uri,values,"column1 = ? and column2 = ? and column3 = ?",new String[]{"content","1","true"});
4.Delete 删除数据
getContentResolver().delete(uri,"column1 = ?",new String[]{"content"});
1.在AndroidManifest.xml文件中添加权限声明
2.处理运行时权限
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_CONTACTS},READ_CONTACTS_REQUEST_CODE);
} else {
readContacts();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case READ_CONTACTS_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
readContacts();
} else {
Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
}
break;
default:
}
}
3.完善读取手机联系人的方法
/**
* 读取手机联系人
* */
private void readContacts(){
Cursor cursor = null;
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,null);
if(cursor!=null){
while(cursor.moveToNext()){
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(new Contact(contactName,contactPhone));
}
adapter.notifyDataSetChanged();
cursor.close();
}
}