I am trying to save received data to local storage using Room library. I have created a database class in which I define the parameters I need and define the context
And also I have a class in which I define the content I need for the database. But my problem is that I can't pass context. On the line
db = NetworkDatabase.getInstance(this)
I get a Type mismatch error: Required:Context Found:Pocket Scout Interceptor.
Please tell me how can I fix my mistake.
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)
}
}
CodePudding user response:
Your code to create db
requires context
as a param: NetworkDatabase.getInstance(this)
. So you can pass a context as a param to your interceptor, something like:
class PocketScoutInterceptor(val context: Context) : Interceptor {
...
NetworkDatabase.getInstance(context)
Pass application context, not activity to avoid memory leaks.