privatefunreadContacts() { // Uri 封装好了 contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null)?.apply { while (moveToNext()) { val name = getString(getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) val number = getString(getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)) phoneList.add(Phone(name, number)) } adapter.notifyDataSetChanged() close() } }
insert
与 SQLite 类似
val values = contentValuesOf("column1" to "text", "column2" to 1) contentResolver.insert(uri, values)
update
val values = contentValuesOf("column1" to "") contentResolver.update(uri, values, "column1 = ? and column2 = ?", arrayOf("text", "1"))
query
用法与 SQLite 基本一致, 参数有所变化
1 2 3 4 5 6 7 8 9 10 11 12
val cursor = contentResolver.query( uri, // 指内容 URI 需要使用 Uri.parse(URI) 进行解析 projection, // 列名 selection, // where 约束 selectionArgs, // 占位符值 sortOrder // 排序方式 ) while (cursor.moveToNext()) { val column1 = cursor.getString(cursor.getColumnIndex("column1")) val column2 = cursor.getInt(cursor.getColumnIndex("column2")) } cursor.close()
R.id.addData -> { val uri = Uri.parse("content://com.example.a13databasetest.provider/book") val values = contentValuesOf("name" to "The day", "author" to "ZH", "pages" to 999, "price" to "9.98") val newUri = contentResolver.insert(uri, values) book_id = newUri?.pathSegments?.get(1) } R.id.queryData -> { val uri = Uri.parse("content://com.example.a13databasetest.provider/book") contentResolver.query(uri, null, null, null, null)?.apply { while(moveToNext()) { val name = getString(getColumnIndexOrThrow("name")) val author = getString(getColumnIndexOrThrow("author")) val pages = getInt(getColumnIndexOrThrow("pages")) val price = getDouble(getColumnIndexOrThrow("price")) } close() } } R.id.updateData -> { book_id?.let { val uri = Uri.parse("content://com.example.a13databasetest.provider/book/$it") val values = contentValuesOf("name" to "A Storm of Swords", "pages" to 1216, "price" to 24.05) contentResolver.update(uri, values, null, null) } } R.id.deleteData -> { book_id?.let { val uri = Uri.parse("content://com.example.a13databasetest.provider/book/$it") contentResolver.delete(uri, null, null) } }