Android内容提供器(二)——其他应用的数据

内容提供器的用法一般有两种,一种是使用现有的内容提供其读取操作相应应用程序的数据【比如系统电话簿,短信等】,另一种是创建自己的内容提供器提供外部访问接口

一、基本用法

Context.getContentResolver() 获取到ContentResolver类,再通过这个类进行增删改查。其中的增删改查方法不接收表名参数,而是接收内容URI做参数。URIauthoritypath组成,一般authority由程序包名+.provider组成。

内容URI字符串写法举例:

content://com.example.app.provider/table

内容URI做参数必须先用Uri.parse()解析为URI对象,才能传递进去。

1、查

举例,查询table表的数据:

Uri uri = Uri.parse("content://包名.provider/table")
Cursor cursor = getContentResolver().query(
	uri,
	列名,
	where 约束条件,
	占位参数,
	排序方式
)
if(cursor != null){
	while (cursor.moveToNext()){
		String 列1 = cursor.getString(cursor.getColumnIndex(列名1));
		int2 = cursor.getInt(cursor.getColumnIndex(列名2));
		}
	cursor.close();
}

2、增

ContentValues values = new ContentValues();
values.put(列名1,1);
values.put(列名2,2);
getContetnResolver().insert(uri, values);

删和改就不用介绍了,自己推吧,参考资料:
《Android数据存储(三)——SQLiteDatabase 操作 SQLite》

二、读取系统联系人

新建一个day13_ContactsTest空项目

1、模拟数据

在这里插入图片描述

2、主布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/contacts_view"/>

</LinearLayout>

3、主活动

这里query()内容URI对象已经被解析出来了

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> adapter;
    List<String> contactList = new ArrayList<>();

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    readContacts();
                } else {
                    Toast.makeText(this, "权限被拒绝,无法显示通讯录", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 【ListView的用法】https://blog.csdn.net/qq_41205771/article/details/103922607
        ListView listView_contacts = findViewById(R.id.contacts_view);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactList);
        listView_contacts.setAdapter(adapter);
        // 【危险权限处理逻辑】https://blog.csdn.net/qq_41205771/article/details/104198836
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, 1);
        }else{
            readContacts();
        }

    }

    private void readContacts() {
        Cursor cursor = null;
        try{
            // 查询联系人数据
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            if(cursor != null){
                while (cursor.moveToNext()){
                    // 获取联系人姓名
                    String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    // 获取手机号
                    String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    contactList.add(displayName+"\n"+number);
                }
                // 刷新并显示
                adapter.notifyDataSetChanged();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (cursor != null){
                cursor.close();
            }
        }
    }
}

4、别忘了权限声明!

<uses-permission android:name="android.permission.READ_CONTACTS"/>

5、运行

在这里插入图片描述

发布了156 篇原创文章 · 获赞 13 · 访问量 7216

猜你喜欢

转载自blog.csdn.net/qq_41205771/article/details/104203659