您将获得什么
实时编辑的工作方式类似于 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 钩子,或重新打开该界面。