实验十二 SQL + content Provider实验
一、实验目的
熟悉Content Provider的使用;
二、实验内容
1、实现ContentProvider和ContentResolver通过URI的调用; 2、实现ContentProvider对数据库SQLite的功能:增、删、改、查; 3、数据库的表结构自行设计;
三、实验要求
1、配置SQLite 数据库的运行环境 2、熟悉ContentProvider对数据库SQLite增、删、改、查的具体操作和流程 3、充分理解SQLite数据库的使用原理和方式
参考: https://blog.csdn.net/alovelypeach/article/details/112250226 对原博主表示感谢! 原博主(alovelypeach)并未提到应用程序清单文件AndroidManifest.xml,导致copy代码并不能正常运行,本文将对原博主的实验内容进行完善
四、实验过程
①创建项目
②编写布局文件
③编写MainActivity类
实验需要读取通讯录,如果没有给予读取通讯录权限,应用将不能正常运行 需要使用
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED
判断是否有读取通讯录权限 如没有权限,则使用
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
弹出Android的请求权限对话框。 有权限才启动ContentActivity,进行下一步操作 代码如下:
public void toOne(View view) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
Toast.makeText(this,"未允许读取通讯录权限!",Toast.LENGTH_SHORT).show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
{
Intent intent = new Intent(MainActivity.this,ContentActivity.class);
startActivity(intent);
}
}
效果如下:
④编写ContentActivity类
想要获取到通讯录中的号码,需要先获取LOOKUP_KEY,再根据LOOKUP_KEY到ContactsContract.CommonDataKinds.Phone中查询NUMBER
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},ContactsContract.Data.LOOKUP_KEY+"=?", new String[]{lookUp_Key},null);
获取通讯录姓名、号码代码如下:
public String getAllPhoneNumbers(String lookUp_Key){
StringBuilder allPhoneNo = new StringBuilder();
String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
String[] selectionArgs = {lookUp_Key};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
while(cursor.moveToNext()){
allPhoneNo.append(cursor.getString(0)).append(" ");
}
return allPhoneNo.toString();
}
private CharSequence getQueryData() {
StringBuilder stringBuilder = new StringBuilder();
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
String name = ContactsContract.Contacts.DISPLAY_NAME;
String key = ContactsContract.Contacts.LOOKUP_KEY;
int displayNameIndex = cursor.getColumnIndex(name);
int KeyIndex = cursor.getColumnIndex(key);
for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
String displayName = cursor.getString(displayNameIndex);
String Key = cursor.getString(KeyIndex);
String displayPhone = getAllPhoneNumbers(Key);
stringBuilder.append(displayName).append(" ").append(displayPhone).append("\n");
}
cursor.close();
return stringBuilder.toString();
}
⑤编写SQLActivity、PersionProvider、PersonDBOpenHelper类
将通讯录插入到数据库的代码如下:
public void btnCreate(View view) {
PersonDBOpenHelper helper = new PersonDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
resolver = getContentResolver();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
Toast.makeText(this,"未允许读取通讯录权限!",Toast.LENGTH_SHORT).show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
{
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
String name = ContactsContract.Contacts.DISPLAY_NAME;
String key = ContactsContract.Contacts.LOOKUP_KEY;
int displayNameIndex = cursor.getColumnIndex(name);
int KeyIndex = cursor.getColumnIndex(key);
for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
String displayName = cursor.getString(displayNameIndex);
String Key = cursor.getString(KeyIndex);
String displayPhone = getAllPhoneNumbers(Key);
values = new ContentValues();
values.put("name",displayName);
values.put("phone",displayPhone);
db.insert("info",null,values);
}
cursor.close();
db.close();
btnQueryAll(view);
Toast.makeText(this,"插入成功!",Toast.LENGTH_SHORT).show();
}
}
使用
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(50),phone varchar(20),UNIQUE(phone))");
创建含有_id、name、phone字段的SQLite数据库,其中_id为主键,自增,phone不可重复。
⑥修改应用程序清单文件AndroidManifest.xml
需要加入
<uses-permission android:name="android.permission.READ_CONTACTS" />
声明需要读取通讯录权限 需要加入
<provider
android:authorities="com.example.test05_contentprovider.PersonProvider"
android:name="PersonProvider"
android:exported="false" />
以包含内容提供者 android:authorities的书写方式为Provider的包名+Provider的类名
五、完整源码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/toOne"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/toOne"
android:onClick="toOne" />
<Button
android:id="@+id/toTwo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/toTwo"
android:onClick="toTwo" />
</LinearLayout>
contentlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ContentActivity">
<TextView
android:id="@+id/hint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hint"
android:textSize="30sp" />
<TextView
android:id="@+id/callName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp" />
</LinearLayout>
sqllayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SQLActivity">
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="@string/id" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="@string/name" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:hint="@string/phone" />
<Button
android:id="@+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/add"
android:onClick="btnAdd" />
<Button
android:id="@+id/delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/delete"
android:onClick="btnDelete" />
<Button
android:id="@+id/update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/update"
android:onClick="btnUpdate" />
<Button
android:id="@+id/query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/query"
android:onClick="btnQuery" />
<Button
android:id="@+id/addContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/addContent"
android:onClick="btnCreate" />
<Button
android:id="@+id/queryAll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/queryAll"
android:onClick="btnQueryAll" />
<EditText
android:id="@+id/eT"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="15dp"
android:layout_weight="1"
android:gravity="start|top"
android:inputType="textMultiLine" />
</LinearLayout>
strings.xml
<resources>
<string name="app_name">test05_contentprovider</string>
<string name="id">id</string>
<string name="name">姓名</string>
<string name="phone">号码</string>
<string name="add">增加</string>
<string name="delete">删除</string>
<string name="update">修改</string>
<string name="query">查询</string>
<string name="addContent">插入通讯录数据</string>
<string name="queryAll">查看所有数据</string>
<string name="toOne">访问通讯录</string>
<string name="toTwo">数据库</string>
<string name="hint">读取到的联系人姓名 号码:</string>
</resources>
MainActivity.java
package com.example.test05_contentprovider;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void toOne(View view) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
Toast.makeText(this,"未允许读取通讯录权限!",Toast.LENGTH_SHORT).show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
{
Intent intent = new Intent(MainActivity.this,ContentActivity.class);
startActivity(intent);
}
}
public void toTwo(View view) {
Intent intent = new Intent(MainActivity.this,SQLActivity.class);
startActivity(intent);
}
}
ContentActivity.java
package com.example.test05_contentprovider;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class ContentActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contentlayout);
TextView textView = (TextView) findViewById(R.id.callName);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
textView.setText("未允许读取通讯录权限!");
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
{
textView.setText(getQueryData());
}
}
public String getAllPhoneNumbers(String lookUp_Key){
StringBuilder allPhoneNo = new StringBuilder();
String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
String[] selectionArgs = {lookUp_Key};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
while(cursor.moveToNext()){
allPhoneNo.append(cursor.getString(0)).append(" ");
}
return allPhoneNo.toString();
}
private CharSequence getQueryData() {
StringBuilder stringBuilder = new StringBuilder();
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
String name = ContactsContract.Contacts.DISPLAY_NAME;
String key = ContactsContract.Contacts.LOOKUP_KEY;
int displayNameIndex = cursor.getColumnIndex(name);
int KeyIndex = cursor.getColumnIndex(key);
for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
String displayName = cursor.getString(displayNameIndex);
String Key = cursor.getString(KeyIndex);
String displayPhone = getAllPhoneNumbers(Key);
stringBuilder.append(displayName).append(" ").append(displayPhone).append("\n");
}
cursor.close();
return stringBuilder.toString();
}
}
SQLActivity.java
package com.example.test05_contentprovider;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SQLActivity extends Activity {
private final Uri uri = Uri.parse("content://com.example.test05_contentprovider.PersonProvider/info");
private ContentValues values;
private ContentResolver resolver;
private EditText et_id;
private EditText et_name;
private EditText et_phone;
private EditText et_queryAll;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllayout);
et_id = (EditText) findViewById(R.id.editText1);
et_name = (EditText) findViewById(R.id.editText2);
et_phone = (EditText) findViewById(R.id.editText3);
et_queryAll = (EditText) findViewById(R.id.eT);
}
public String getAllPhoneNumbers(String lookUp_Key){
StringBuilder allPhoneNo = new StringBuilder();
String[] proj2 = {ContactsContract.CommonDataKinds.Phone.NUMBER};
String selection = ContactsContract.Data.LOOKUP_KEY+"=?";
String[] selectionArgs = {lookUp_Key};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,proj2,selection,selectionArgs,null);
while(cursor.moveToNext()){
allPhoneNo.append(cursor.getString(0)).append(" ");
}
return allPhoneNo.toString();
}
public void btnCreate(View view) {
PersonDBOpenHelper helper = new PersonDBOpenHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();
resolver = getContentResolver();
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
Toast.makeText(this,"未允许读取通讯录权限!",Toast.LENGTH_SHORT).show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)== PackageManager.PERMISSION_GRANTED)
{
Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,null,null,null);
String name = ContactsContract.Contacts.DISPLAY_NAME;
String key = ContactsContract.Contacts.LOOKUP_KEY;
int displayNameIndex = cursor.getColumnIndex(name);
int KeyIndex = cursor.getColumnIndex(key);
for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) {
String displayName = cursor.getString(displayNameIndex);
String Key = cursor.getString(KeyIndex);
String displayPhone = getAllPhoneNumbers(Key);
values = new ContentValues();
values.put("name",displayName);
values.put("phone",displayPhone);
db.insert("info",null,values);
}
cursor.close();
db.close();
btnQueryAll(view);
Toast.makeText(this,"插入成功!",Toast.LENGTH_SHORT).show();
}
}
public void btnAdd(View view) {
resolver = getContentResolver();
values = new ContentValues();
if (et_name.length() != 0 && et_phone.length() != 0){
values.put("name",et_name.getText().toString());
values.put("phone",et_phone.getText().toString());
Uri newUri = resolver.insert(uri,values);
Toast.makeText(this,"增加成功",Toast.LENGTH_SHORT).show();
btnQueryAll(view);
} else {
et_name.setHint("请在此输入需增加的姓名");
et_phone.setHint("请在此输入需增加的号码");
}
}
public void btnQuery(View view) {
resolver = getContentResolver();
if (et_name.length() != 0){
Cursor cursor = resolver.query(uri,new String[]{"_id","name","phone"},"name=?",new String[]{et_name.getText().toString()},null);
if (cursor.getCount() != 0){
cursor.moveToFirst();
et_id.setText(cursor.getString(0));
et_name.setText(cursor.getString(1));
et_phone.setText(cursor.getString(2));
cursor.close();
}
else {
Toast.makeText(this,"未查询到结果!",Toast.LENGTH_SHORT).show();
}
}
else {
et_name.setHint("请在此输入需查询的姓名");
et_phone.setHint("号码");
}
}
public void btnQueryAll(View view) {
resolver = getContentResolver();
List<Map<String,String>> data = new ArrayList<Map<String,String>>();
Cursor cursor = resolver.query(uri,new String[]{"_id","name","phone"},null,null,null);
while (cursor.moveToNext()){
Map<String,String> map = new HashMap<String,String>();
map.put("_id",cursor.getString(0));
map.put("name",cursor.getString(1));
map.put("phone",cursor.getString(2));
data.add(map);
}
cursor.close();
et_queryAll.setText(new String(data.toString()));
}
public void btnUpdate(View view) {
resolver = getContentResolver();
values = new ContentValues();
if (et_name.length() != 0 && et_phone.length() != 0){
values.put("phone",et_phone.getText().toString());
int updateCount = resolver.update(uri,values,"name=?",new String[]{et_name.getText().toString()});
Toast.makeText(this,"成功更新了" + updateCount + "条记录",Toast.LENGTH_SHORT).show();
btnQueryAll(view);
} else {
et_name.setHint("请在此输入需修改的姓名");
et_phone.setHint("请在此输入修改后的号码");
}
}
public void btnDelete(View view) {
resolver = getContentResolver();
if (et_name.length() != 0){
int deleteCount = resolver.delete(uri,"name=?",new String[]{et_name.getText().toString()});
Toast.makeText(this,"成功删除了" + deleteCount + "条记录",Toast.LENGTH_SHORT).show();
btnQueryAll(view);
} else {
et_name.setHint("请在此输入需删除的姓名");
et_phone.setHint("号码");
}
}
}
PersionProvider.java
package com.example.test05_contentprovider;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class PersonProvider extends ContentProvider {
private static UriMatcher mUriMatcher = new UriMatcher(-1);
private static final int SUCCESS = 1;
private PersonDBOpenHelper helper;
static {
mUriMatcher.addURI("com.example.test05_contentprovider.PersonProvider","info",SUCCESS);
}
@Override
public boolean onCreate() {
helper = new PersonDBOpenHelper(getContext());
return false;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
int code = mUriMatcher.match(uri);
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();
long rowId = db.insert("info",null,values);
if (rowId>0) {
Uri insertedUri = ContentUris.withAppendedId(uri,rowId);
getContext().getContentResolver().notifyChange(insertedUri,null);
return insertedUri;
}
db.close();
return uri;
}else {
try {
throw new IllegalAccessException("插入失败,路径不正确!");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] strings, @Nullable String s, @Nullable String[] strings1, @Nullable String s1) {
int code = mUriMatcher.match(uri);
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();
return db.query("info",strings,s,strings1,null,null,s1);
}else {
try {
throw new IllegalAccessException("查询失败,路径不正确!");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues contentValues, @Nullable String s, @Nullable String[] strings) {
int code = mUriMatcher.match(uri);
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();
int count = db.update("info",contentValues,s,strings);
if (count>0) {
getContext().getContentResolver().notifyChange(uri,null);
}
db.close();
return count;
}else {
try {
throw new IllegalAccessException("更新失败,路径不正确!");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String s, @Nullable String[] strings) {
int code = mUriMatcher.match(uri);
if (code == SUCCESS) {
SQLiteDatabase db = helper.getReadableDatabase();
int count = db.delete("info",s,strings);
if (count>0) {
getContext().getContentResolver().notifyChange(uri,null);
}
db.close();
return count;
}else {
try {
throw new IllegalAccessException("删除失败,路径不正确!");
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return code;
}
}
PersonDBOpenHelper.java
package com.example.test05_contentprovider;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class PersonDBOpenHelper extends SQLiteOpenHelper {
public PersonDBOpenHelper(Context context) {
super(context,"person.db",null,1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table info(_id integer primary key autoincrement,name varchar(50),phone varchar(20),UNIQUE(phone))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test05_contentprovider">
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Test05_contentprovider">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ContentActivity" />
<activity android:name=".SQLActivity" />
<provider
android:authorities="com.example.test05_contentprovider.PersonProvider"
android:name="PersonProvider"
android:exported="false" />
</application>
</manifest>
六、最终效果
需要手机或模拟器中的通讯录有内容 打开应用,点击“访问通讯录”,将会询问读取通讯录权限 允许后,再次点击,成功读取到通讯录姓名及电话号码。 点击“数据库”,点击“插入通讯录数据”,即可把通讯录数据插入到数据库中,同时将所有数据显示。 在姓名和号码框中输入数据,点击“增加”(id会自动递增,无需输入),添加成功,即可显示出添加后的记录
在姓名框中输入想删除的姓名,点击“删除”,删除成功,即可显示出删除后的结果
在姓名框中输入需修改的姓名,在号码框中输入修改后的号码,点击“修改”,修改成功,即可显示出修改后的结果 在姓名框中输入姓名,点击“查询”,即可显示id、号码 如果在姓名或号码输入框中没有输入内容,就点击了增加、删除、修改、查询,将会在输入框中显示相应提示信息
|