寫此筆記原因
學習《第一行代碼》到第8章節實現provider時踩了一些坑,因此記錄下來給后來人和自己一個提示,僅此而已。
包含內容
- Sqlite數據庫CURD內容
- provider界面
- provider項目中書籍管理
- provider實現邏輯
- 用adb shell確認provider
- contentResolver接收項目
- contentProvider權限
- 生成Uri方法
Sqlite數據庫CURD內容
- Android studio 創建一個Empty的空項目
- 不需要等項目同步完成,直接取消同步。因為從官網下載Gradle和java庫太慢。
- 修改Gradle和java庫為國內鏡像后,再點擊同步。應當就能快速的實現依賴下載
# settings.gradle.kts pluginManagement {repositories {maven { setUrl("https://maven.aliyun.com/repository/central") }maven { setUrl("https://maven.aliyun.com/repository/jcenter") }maven { setUrl("https://maven.aliyun.com/repository/google") }maven { setUrl("https://maven.aliyun.com/repository/gradle-plugin") }maven { setUrl("https://maven.aliyun.com/repository/public") }maven { setUrl("https://jitpack.io") }google {content {includeGroupByRegex("com\\.android.*")includeGroupByRegex("com\\.google.*")includeGroupByRegex("androidx.*")}}mavenCentral()gradlePluginPortal()}}dependencyResolutionManagement {repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)repositories {maven { setUrl("https://maven.aliyun.com/repository/central") }maven { setUrl("https://maven.aliyun.com/repository/jcenter") }maven { setUrl("https://maven.aliyun.com/repository/google") }maven { setUrl("https://maven.aliyun.com/repository/gradle-plugin") }maven { setUrl("https://maven.aliyun.com/repository/public") }maven { setUrl("https://jitpack.io") }google()mavenCentral()}}rootProject.name = "BookProviderTest"include(":app")
gradle/wrapper/gradle-wrapper.propertiesdistributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/dists# 此處gradle版本可以根據android相應的java版本自行修改,移植android項目也可以修改此處版本distributionUrl=https://mirrors.cloud.tencent.com/gradle/gradle-8.11.1-all.zipzipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/dists
- 創建一個類BookDatabaseHelper
class BookDatabaseHelper(val context: Context, val name: String, version: Int) :SQLiteOpenHelper(context, name, null, version) {private val createBookCMD = "create table Book (" +" id integer primary key autoincrement, " +"author text not null," +"price real," +"pages integer," +"name text not null)"private val createCategoryCMD = "create table category (" +"id integer primary key autoincrement," +"category_name text not null," +"category_code integer)"override fun onCreate(db: SQLiteDatabase?) {db?.execSQL(createBookCMD)db?.execSQL(createCategoryCMD)
// Toast.makeText(context, "創建 $name 成功", Toast.LENGTH_SHORT).show()}override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {db?.execSQL("drop table if exists Book")db?.execSQL("drop table if exists category")onCreate(db)}
}
- app/src/main/java/com.example.databasetest中創建一個空的MainActivity,同時選中"Generate a Layout File"和"Launcher Activity",就同時創建了MainActivity和res/layout/
activity_main.xml
。 - 引入viewBinding
# build.gradle.kts文件android的大括號中加入,再次同步buildFeatures {viewBinding = true}
provider界面
# 切換到圖形界面,鼠標右鍵點擊main,選擇"Convert view",將布局換成LinearLayout
# 下面內容就是書籍管理界面
<?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:id="@+id/main"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="書名"android:id="@+id/BookNameLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:hint="書名"android:id="@+id/bookName" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="作者"android:id="@+id/BookAuthorLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:hint="作者"android:id="@+id/bookAuthor" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="頁數"android:id="@+id/BookPagesLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:inputType="number"android:hint="頁數"android:id="@+id/bookPages" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="售價"android:id="@+id/BookPriceLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:hint="售價"android:inputType="number"android:id="@+id/bookPrice" /></LinearLayout><LinearLayoutandroid:orientation="horizontal"android:layout_gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookSave"android:text="保存" /><Buttonandroid:layout_width="wrap_content"android:layout_height="match_parent"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookUpdate"android:text="更新" /></LinearLayout><LinearLayoutandroid:orientation="horizontal"android:layout_gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookDelete"android:text="刪除" /><Buttonandroid:layout_width="wrap_content"android:layout_height="match_parent"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookSearch"android:text="查詢" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:padding="20dp" ><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_weight="1"android:id="@+id/createDatabase"android:layout_gravity="center"android:text="創建數據庫" /><Buttonandroid:layout_width="wrap_content"android:layout_height="match_parent"android:layout_weight="1"android:id="@+id/transictionTest"android:layout_gravity="center"android:text="事務測試" /></LinearLayout>
</LinearLayout>
provider項目中書籍管理
# MainActivity
class MainActivity : AppCompatActivity() {private lateinit var binding : ActivityMainBindingoverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)val dbHelper = BookDatabaseHelper(this, "Books.db", 2)/* 創建數據庫 */binding.createDatabase.setOnClickListener {dbHelper.writableDatabase}/* 添加新書 */binding.bookSave.setOnClickListener {val db = dbHelper.writableDatabaseval values = ContentValues().apply {put("name", binding.bookName.text.toString())put("author", binding.bookAuthor.text.toString())put("pages", binding.bookPages.text.toString().toInt())put("price", binding.bookPrice.text.toString().toFloat())}db.insert("Book", null, values);binding.bookName.setText("")binding.bookAuthor.setText("")binding.bookPages.setText("")binding.bookPrice.setText("")}/* 更新書籍信息 */binding.bookUpdate.setOnClickListener {var db = dbHelper.writableDatabaseval values = ContentValues().apply{put("name", binding.bookName.text.toString())put("author", binding.bookAuthor.text.toString())put("pages", binding.bookPages.text.toString().toInt())put("price", binding.bookPrice.text.toString().toFloat())}db.update("Book", values, "name = ?", arrayOf("Book1"))binding.bookName.setText("")binding.bookAuthor.setText("")binding.bookPages.setText("")binding.bookPrice.setText("")}/* 按書名刪除書籍信息 */binding.bookDelete.setOnClickListener {var db = dbHelper.writableDatabasedb.delete("Book", "name = ?", arrayOf(binding.bookName.text.toString()))binding.bookName.setText("")binding.bookAuthor.setText("")binding.bookPages.setText("")binding.bookPrice.setText("")}binding.bookSearch.setOnClickListener {val db = dbHelper.writableDatabaseval queryBookName = binding.bookName.text.toString()
// val cursor = db.rawQuery("select name,author,pages,price from Book where name = ?" , arrayOf(queryBookName))val cursor = db.query("Book",arrayOf("name","author","pages","price"), "name = ?", arrayOf(queryBookName), null, null, null)if(cursor.count > 0){cursor.moveToFirst()binding.bookName.setText(cursor.getString(cursor.getColumnIndex("name") as Int))binding.bookAuthor.setText(cursor.getString(cursor.getColumnIndex("author") as Int))binding.bookPages.setText(cursor.getString(cursor.getColumnIndex("pages") as Int))binding.bookPrice.setText(cursor.getString(cursor.getColumnIndex("price") as Int))}}binding.transictionTest.setOnClickListener {val db = dbHelper.writableDatabasedb.beginTransaction()try{db.delete("Book", null, null)if(true){
// throw NullPointerException()}val values = ContentValues().apply {put("name", "Game Of Thrones")put("author", "George Martin")put("pages", 720)put("price", 20.85)}db.insert("Book", null, values)db.setTransactionSuccessful() // 事務完成提交}catch (e: Exception){e.printStackTrace()}finally {db.endTransaction()}}}
}
至此就可以向Books.db中加入書籍的內容了,保存是添加新書,查詢可以查出已經加入的書籍。《第一行代碼》第7章還推薦了一個"Database Navigator"可以查看導出的sqlite數據庫,可以試試。
provider實現邏輯
# 新建一個BookDatabaseProvider,最好使用File->New->Other->Content Provider,會自動在`AndroidManifest.xml`文件中自動加入新建的provider
class BookDatabaseProvider : ContentProvider() {/* 自定義uri編號 */private val bookDir = 0private val bookItem = 1private val categoryDir = 2private val categoryItem = 3private val authority = "com.example.databasetest.provider"private var dbHelper: BookDatabaseHelper? = nullprivate val uirMatcher by lazy {val matcher = UriMatcher(UriMatcher.NO_MATCH)matcher.addURI(authority, "book", bookDir)matcher.addURI(authority, "book/#", bookItem)matcher.addURI(authority,"category", categoryDir)matcher.addURI(authority, "category/#", categoryItem)matcher}override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?) = dbHelper?.let {val db = it.writableDatabaseval deleteRows = when(uirMatcher.match(uri)) {bookDir -> db.delete("Book", selection, selectionArgs)bookItem -> {/* uri 最后一個字段 */val bookId = uri.pathSegments[1]db.delete("Book", "id = ?", arrayOf(bookId))}categoryDir -> db.delete("Category", selection, selectionArgs)categoryItem -> {val categoryId = uri.pathSegments[1]db.delete("Category", "id = ?",arrayOf(categoryId))}else -> null}deleteRows} ?: 0override fun getType(uri: Uri) = when(uirMatcher.match(uri)) {bookDir -> "vnd.android.cursor.dir/vnd.$authority.book"bookItem -> "vnd.android.cursor.item/vnd.$authority.book"categoryDir -> "vnd.android.cursor.dir/vnd.$authority.category"categoryItem -> "vnd.android.cursor.item/vnd.$authority.category"else -> null}override fun insert(uri: Uri, values: ContentValues?) = dbHelper?.let {val db = it.writableDatabaseval uriReturn = when(uirMatcher.match(uri)) {bookDir, bookItem -> {val newBookId = db.insert("Book", null, values)Uri.parse("content://$authority/book/$newBookId")}categoryDir, categoryItem -> {val newCategoryId = db.insert("Category", null, values)Uri.parse("content://$authority/category/$newCategoryId")}else -> null}uriReturn}override fun onCreate() = context?.let {dbHelper = BookDatabaseHelper(it, "Books.db", 2)true} ?: falseoverride fun query(uri: Uri, projection: Array<String>?, selection: String?,selectionArgs: Array<String>?, sortOrder: String?) = dbHelper?.let{val db = it.readableDatabaseval cursor = when(uirMatcher.match(uri)){bookDir -> db.query("Book", projection, selection, selectionArgs, null, null, sortOrder)bookItem -> {val bookId = uri.pathSegments[1]db.query("Book", projection, "id = ?", arrayOf(bookId), null, null, sortOrder)}categoryDir -> db.query("Category", projection, selection, selectionArgs, null, null, sortOrder)categoryItem -> {val categoryId = uri.pathSegments[1]db.query("Category", projection, "id = ?", arrayOf(categoryId), null, null, sortOrder)}else -> null}cursor}override fun update(uri: Uri, values: ContentValues?, selection: String?,selectionArgs: Array<String>?) = dbHelper?.let {val db = it.writableDatabaseval updateRows = when(uirMatcher.match(uri)) {bookDir -> db.update("Book", values, selection, selectionArgs)bookItem -> {val bookId = uri.pathSegments[1]db.update("Book", values, "id = ?", arrayOf(bookId))}categoryDir -> db.update("Category", values, selection, selectionArgs)categoryItem -> {val categoryId = uri.pathSegments[1]db.update("Category", values, "id = ?", arrayOf(categoryId))}else -> null}updateRows} ?: 0
}
完成后就可以連接手機或模擬器點擊運行安裝了,加入些書籍信息
用adb shell確認provider
$ adb shell content query --uri content://com.example.databasetest.provider/book
Row: 0 id=1, author=Author1, price=1.0, pages=1, name=Book1
Row: 1 id=2, author=Author2, price=2.0, pages=2, name=Book2
# 可以看到輸出了2本剛加入的書籍信息,這里還沒有加入權限說明adb shell可以直接讀取書籍信息
adb shell content query --uri content://com.example.databasetest.provider/book --where "name=\'Book1\'"
# 這里如果要找特定行內容需要以\' xxx \'這樣的形式,什么name:s:xxx "name='xxx'" 都會報錯
contentResolver接收項目界面
同樣的方法再建立一個訪問provider的項目"BookProviderTest",建立一個新的Activity,和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:id="@+id/main"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="書名"android:id="@+id/BookNameLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:hint="書名"android:id="@+id/bookName" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="作者"android:id="@+id/BookAuthorLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:hint="作者"android:id="@+id/bookAuthor" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="頁數"android:id="@+id/BookPagesLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:inputType="number"android:hint="頁數"android:id="@+id/bookPages" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content" ><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="售價"android:id="@+id/BookPriceLabel"></TextView><EditTextandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="2"android:hint="售價"android:inputType="number"android:id="@+id/bookPrice" /></LinearLayout><LinearLayoutandroid:orientation="horizontal"android:layout_gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookSave"android:text="保存" /><Buttonandroid:layout_width="wrap_content"android:layout_height="match_parent"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookUpdate"android:text="更新" /></LinearLayout><LinearLayoutandroid:orientation="horizontal"android:layout_gravity="center"android:layout_width="match_parent"android:layout_height="wrap_content"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookDelete"android:text="刪除" /><Buttonandroid:layout_width="wrap_content"android:layout_height="match_parent"android:layout_margin="20dp"android:layout_weight="1"android:layout_gravity="center"android:id="@+id/bookSearch"android:text="查詢" /></LinearLayout>
</LinearLayout>
class MainActivity : AppCompatActivity() {private lateinit var binding: ActivityMainBindingvar bookId: String? = nullval providerUri = "content://com.example.databasetest.provider"override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)binding = ActivityMainBinding.inflate(layoutInflater)setContentView(binding.root)supportActionBar?.hide()binding.bookSave.setOnClickListener {var uri = Uri.parse("$providerUri/book")val values = contentValuesOf("name" to binding.bookName.text.toString(),"author" to binding.bookAuthor.text.toString(),"pages" to binding.bookPages.text.toString().toInt(),"price" to binding.bookPrice.text.toString().toDouble())val newUri = contentResolver.insert(uri, values)bookId = newUri?.pathSegments?.get(1)}binding.bookSearch.setOnClickListener {val uri = Uri.parse("content://com.example.databasetest.provider/book")val bookName = binding.bookName.text.toString()val cursor = contentResolver.query(uri, arrayOf("name","author","pages","price"), "name = ?", arrayOf(bookName), null)cursor?.apply{while(moveToNext()){val nameId = getColumnIndex("name")val name = getString(nameId)val authorId = getColumnIndex("author")val author = getString(authorId)val pagesId = getColumnIndex("pages")val pages = getInt(pagesId)val priceId = getColumnIndex("price")val price = getDouble(priceId)binding.bookName.setText(name)binding.bookAuthor.setText(author)binding.bookPages.setText(pages.toString())binding.bookPrice.setText(price.toString())}close()}}binding.bookUpdate.setOnClickListener {val uri = Uri.parse("$providerUri/book")val values = contentValuesOf("name" to binding.bookName.text.toString(),"author" to binding.bookAuthor.text.toString(),"pages" to binding.bookPages.text.toString().toInt(),"price" to binding.bookPrice.text.toString().toDouble())contentResolver.update(uri, values, "name = ?", arrayOf(binding.bookName.text.toString()))}binding.bookDelete.setOnClickListener {val uri = Uri.parse("$providerUri/book")contentResolver.delete(uri, "name = ?", arrayOf(binding.bookName.text.toString()))}}
}
此項目直接運行是不能獲取到provider項目的書籍信息的,因為provider沒有指定權限,此項目還沒有權限讀寫provider內容。因此接下來就是要給provider項目和本項目添加權限說明
contentProvider權限
- 打開第一個項目的AndroidManifest.xml
# 加入權限聲名<permission android:name="com.example.databasetest.READ_PERMISSION"android:protectionLevel="normal" / ><permission android:name="com.example.databasetest.WRITE_PERMISSION"android:protectionLevel="normal" />
# provider信息改成如下內容<providerandroid:name=".BookDatabaseProvider"android:authorities="com.example.databasetest.provider"android:enabled="true"android:readPermission="com.example.databasetest.READ_PERMISSION"android:writePermission="com.example.databasetest.WRITE_PERMISSION"android:exported="true"></provider>
# 刪除應用后重新安裝,安裝后就不能使用adb shell content獲取內容了
- 修改第二個項目的AndroidManifest.xml
<uses-permission android:name="com.example.databasetest.READ_PERMISSION" /><uses-permission android:name="com.example.databasetest.WRITE_PERMISSION" />
再次運行就可以在第二個項目中獲取和編輯第一個項目的provider內容了
生成Uri方法
剛開始沒有發現是權限問題,怎么都不能獲取到內容,還以為是因為Uri不正確。因此發現Uri生成方式有幾種,這里也記錄一下。
val uri = Uri.parse("content://authority/path")
# 發現此方法生成的Uri,authority和path沒有解析到相應字段中,但程序還是可以正常運行,獲取到內容
val uri = Uri.Builder().apply{scheme("content")authority("com.example.authority")path("path")
}.build()
# 使用此方法,authority和path都能正確解析到相應字段中,后者應當是比較推薦的方法,就是有點啰嗦
# 系統自帶的聯系人等provider的uri也和后者生成的uri基本一樣