您將獲得什麼
即時編輯的運作方式類似於 Android Studio 的 Database Inspector,但在瀏覽器中進行。SQLite Viewer 會將每次變更傳送到您偵錯應用程式內的一個小型 ContentProvider,由它在應用程式自己的資料庫上執行。應用程式保持執行,無需停止、複製或重新啟動任何東西。
僅限偵錯版本。該輔助程式允許任何擁有 USB 偵錯權限的人在資料庫上執行寫入陳述式,因此請只在
src/debug 中註冊它,切勿將其包含在發行版本中。設定步驟
- 加入輔助類別。將 SqliteViewerProvider.kt(或下方程式碼)下載或複製到您的應用程式模組中,例如
app/src/main/java/com/example/debughelper/。將package行修改為與資料夾一致。 - 僅為偵錯版本註冊。建立
app/src/debug/AndroidManifest.xml,並加入下方的 provider 項目。由於它位於debug原始碼集中,發行版本永遠不會包含該項目,也不會公開任何內容。 - 選用:重新整理 Room 畫面。Room 只會注意到透過它自己的連線所做的變更。請設定一次
afterWrite掛鉤,讓使用LiveData和Flow的畫面在即時編輯後立即更新。 - 執行偵錯版本。將偵錯版本安裝到手機上,並開啟一次應用程式,讓 Android 註冊該 provider。
- 開啟即時編輯。在 SQLite Viewer 中選擇 Android,連接手機,開啟應用程式資料庫並勾選即時編輯。此時會出現綠色的即時編輯徽章。從現在起,您執行的每一次列編輯、插入、刪除和 SQL 陳述式也會套用到正在執行的應用程式。
偵錯資訊清單
<?xml version="1.0" encoding="utf-8"?>
<!-- src/debug/AndroidManifest.xml (debug builds only) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application>
<provider
android:name="com.example.debughelper.SqliteViewerProvider"
android:authorities="${applicationId}.sqliteviewer"
android:exported="true" />
</application>
</manifest>選用的 Room 掛鉤
// In your Application class (optional, only if you use Room LiveData / Flow)
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
SqliteViewerProvider.afterWrite = {
AppDatabase.getInstance(this).invalidationTracker.refreshVersionsAsync()
}
}
}輔助程式 (SqliteViewerProvider.kt)
package com.example.debughelper // use any package, for example your app's own
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import org.json.JSONArray
/**
* DEBUG BUILDS ONLY.
*
* Lets SQLite Viewer (https://sqliteviewer.codemasterlk.com) edit this app's databases
* while the app keeps running. The class can live in src/main, but it is only registered
* in src/debug/AndroidManifest.xml, so release builds never expose it.
*/
class SqliteViewerProvider : ContentProvider() {
companion object {
/** Optional: called after every successful live edit, e.g. to refresh Room observers. */
@JvmStatic
var afterWrite: (() -> Unit)? = null
private val allowedStatement = Regex("""^(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER)\b""", RegexOption.IGNORE_CASE)
private val leadingNoise = Regex("""^(\s|--[^\n]*\n|/\*.*?\*/)*""", RegexOption.DOT_MATCHES_ALL)
private val safeName = Regex("""^[A-Za-z0-9._-]+$""")
}
private val handles = HashMap<String, SQLiteDatabase>()
override fun onCreate(): Boolean = true
override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
val answer = try {
when (method) {
"ping" -> "OK:1"
"batch" -> "OK:" + runBatch(extras?.getString("db"), arg)
else -> "ERR:unknown method $method"
}
} catch (e: Throwable) {
"ERR:" + (e.message ?: e.javaClass.simpleName).replace('\n', ' ')
}
return Bundle().apply { putString("r", answer) }
}
@Synchronized
private fun database(name: String): SQLiteDatabase {
handles[name]?.let { if (it.isOpen) return it }
val file = context!!.getDatabasePath(name)
require(file.exists()) { "database not found: $name" }
return SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READWRITE)
.also { handles[name] = it }
}
private fun runBatch(name: String?, base64: String?): Int {
require(name != null && safeName.matches(name)) { "invalid database name" }
require(!base64.isNullOrEmpty()) { "no statements" }
val statements = JSONArray(String(Base64.decode(base64, Base64.DEFAULT), Charsets.UTF_8))
val db = database(name)
db.beginTransaction()
try {
for (i in 0 until statements.length()) {
val sql = statements.getString(i)
require(allowedStatement.containsMatchIn(sql.replaceFirst(leadingNoise, ""))) {
"statement type not allowed"
}
db.execSQL(sql)
}
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
afterWrite?.invoke()
return statements.length()
}
// Not used: the viewer talks to this provider only through call().
override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
override fun getType(uri: Uri): String? = null
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
}
它能做什麼,不能做什麼
- 它會執行
INSERT、UPDATE、DELETE、REPLACE、CREATE、DROP和ALTER陳述式。讀取、PRAGMA 和VACUUM會被拒絕。 - 每次編輯都在一個交易中套用。如果應用程式拒絕,SQLite Viewer 會顯示錯誤並從手機重新載入資料,使兩邊保持同步。
- 非常大的編輯(約 75 KB 的 SQL)不會即時傳送。這種情況請使用推送到手機。它會取代整個資料庫檔案並重新啟動應用程式。
- 資料庫名稱必須與應用程式
databases資料夾中的檔案一致。輔助程式使用偵錯應用程式的套件名稱,因此也適用於applicationIdSuffix。 - 當您使用 Android 面板的 ADB 伺服器模式時,可與 Android Studio 同時執行(橋接設定指南)。
疑難排解
- 「找不到即時編輯輔助程式」:偵錯資訊清單中缺少該項目、應用程式未重新安裝,或套件名稱不同。provider 的 authority 必須是
<您的套件名稱>.sqliteviewer。 - 「找不到資料庫」:請先開啟一次應用程式讓它建立資料庫,然後再試一次。
- 畫面不更新:請加入上面的選用 Room 掛鉤,或重新開啟該畫面。