You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中Room数据库事务删除多表数据的实现方法求助

Android Room 清空指定表数据实现方案

1. Dao层定义删除方法

Room操作数据库必须通过Dao接口,给每个需要清空的表对应的Dao添加删除全表数据的方法,直接用@Query执行SQL删除语句最直接:

// UserLocations表对应的Dao
@Dao
interface UserLocationsDao {
    @Query("DELETE FROM UserLocations")
    suspend fun deleteAll()
}

// LineLayoutEquipment表对应的Dao
@Dao
interface LineLayoutEquipmentDao {
    @Query("DELETE FROM LineLayoutEquipment")
    suspend fun deleteAll()
}

// 其他需要清空的表,按上述格式给对应Dao添加deleteAll方法

2. 编写数据清除管理类(对应iOS的ApplicationResetManager)

创建单例管理类,处理事务(保证所有删除操作原子性)、同步状态检查,以及SharedPreferences(对应iOS的UserDefaults)的配置重置:

object ApplicationResetManager {
    // 替换为你项目中实际的同步状态检查逻辑
    private val isSyncGoingOn: Boolean
        get() = ApplicationManager.isSyncGoingOn

    fun clearAllData(completion: (Boolean) -> Unit) {
        val currentUser = ApplicationManager.currentUser
        // 校验用户状态与同步状态
        if (currentUser != null && currentUser.id > 0 && !isSyncGoingOn) {
            // 用协程在IO线程执行数据库操作(Room禁止主线程操作)
            CoroutineScope(Dispatchers.IO).launch {
                var success = false
                val db = AppDatabase.getInstance() // 替换为你项目的Room数据库单例
                try {
                    // 开启事务:所有操作要么全成功,要么全回滚
                    db.runInTransaction {
                        // 依次调用各表Dao的删除方法
                        db.userLocationsDao().deleteAll()
                        db.lineLayoutEquipmentDao().deleteAll()
                        db.lineLayoutDao().deleteAll()
                        db.surveyDao().deleteAll()
                        // 继续添加你需要清空的其他表的删除调用...

                        // 重置SharedPreferences配置(对应iOS的UserDefaults)
                        val sharedPref = PreferenceManager.getDefaultSharedPreferences(AppContext)
                        sharedPref.edit().putStringSet("arr_selected_company", emptySet()).apply()
                        // 更新当前用户的默认公司ID
                        currentUser.defaultCompanyId = null
                        db.userDao().updateUser(currentUser) // 若User是Room实体,需同步到数据库

                        success = true
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    success = false
                } finally {
                    // 切回主线程回调结果
                    withContext(Dispatchers.Main) {
                        completion(success)
                    }
                }
            }
        } else {
            Log.d("ResetManager", "Sync is already in progress")
            completion(false)
        }
    }
}

3. 按钮点击时调用

在Activity/Fragment中给按钮绑定点击事件,调用管理类的清除方法:

clearDataBtn.setOnClickListener {
    ApplicationResetManager.clearAllData { isSuccess ->
        if (isSuccess) {
            Toast.makeText(this, "数据清除成功", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "数据清除失败", Toast.LENGTH_SHORT).show()
        }
    }
}

核心要点说明

  • Dao层位置:每个Room实体对应一个Dao接口,通常放在com.yourpackage.data.dao包下,数据库类(继承RoomDatabase)需包含所有Dao的抽象get方法。
  • 事务机制:Room的runInTransaction会自动处理事务的开启、提交与回滚,对应iOS的inTransaction,保证数据一致性。
  • 线程要求:Room默认禁止主线程执行数据库操作,必须用协程(Kotlin)或ExecutorService(Java)在后台线程执行,执行完成后切回主线程更新UI。
  • SharedPreferences:对应iOS的UserDefaults,用于存储轻量配置数据,操作需在主线程或用apply()异步提交。

内容的提问来源于stack exchange,提问作者kartheeki j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:35:42