传递上下文以在 Room 中存储数据

Pass context to store data in Room

我正在尝试使用 Room 库将接收到的数据保存到本地存储。 我创建了一个数据库 class,我在其中定义了我需要的参数并定义了上下文

我还有一个 class,我在其中定义了数据库所需的内容。但我的问题是我无法传递上下文。在线上 db = NetworkDatabase.getInstance(this) 我得到一个 Type mismatch error: Required:Context Found:Pocket Scout Interceptor.

请告诉我如何改正我的错误。

    class PocketScoutInterceptor() : Interceptor {
    lateinit var db: NetworkDatabase
    lateinit var dao: PacketDao

    fun buildPacket(timestamp: Long, duration: Double, request: Request, response: Response, ) {

        val reqBody = request.body
        val respBody = response.body?.string()

        db = NetworkDatabase.getInstance(this)
        dao = db.packetDao()

        val packet = Packet(
            id = 0,
            userId = PocketScoutConfig.userId,
            deviceId = PocketScoutConfig.deviceId,
            sessionId = PocketScoutConfig.sessionId,
            timestamp = timestamp,
            duration = duration.roundToInt(),
            protocol = "http",
            request = room.entities.Request(
                request_method = request.method,
                request_url = request.url.toUrl().toString(),
                request_headers = request.headers.toString(),
                request_body = (reqBody?.toString() ?: ""),
                request_size = (reqBody?.toString()?.length ?: 0),
            ),
            room.entities.Response(
                response_code = response.code,
                response_headers = response.headers.toString(),
                response_body = (respBody ?: ""),
                response_size = (respBody?.length ?: 0),
            )
        )
        dao.add(packet)
    }
}

您创建 db 的代码需要 context 作为参数:NetworkDatabase.getInstance(this)。因此,您可以将上下文作为参数传递给拦截器,例如:

class PocketScoutInterceptor(val context: Context) : Interceptor {
    ...
    NetworkDatabase.getInstance(context)

传递应用程序上下文,而不是activity以避免内存泄漏。