'What to send as Content

In my application, I save data to Firebase and to local storage using the Room library. With Firebase, everything is clear to me. But with Rom I had questions. I can't figure out what to pass to the class parameter.

PacketsLocalDataSource.kt

class PacketsLocalDataSource(val context: Context) {
    lateinit var db: PacketsDatabase
    lateinit var dao: PacketDao

    fun saveLocal(packet: Packet) {
        db = PacketsDatabase.getInstance(context)
        dao = db.packetDao()
        dao.add(packet)
    }
}

And further, in the code below, I want to save the data. But there is an error on the fifth line of the code: No value passed for parameter 'context'. Please let me know what I need to send here.

class PocketScoutContainer {
    private val firebaseRealtimeDatabase = Firebase.database

    private val packetsRemoteDataSource = PacketsRemoteDataSource(firebaseRealtimeDatabase)
    private val packetsLocalDataSource = PacketsLocalDataSource()

    val packetsRepository = PacketsRepository(packetsRemoteDataSource, packetsLocalDataSource)
}


Solution 1:[1]

You need to pass Context to PacketsLocalDataSource constructor. In turn, the context must be passed when creating an instance of the class PocketScoutContainer. So:

class PocketScoutContainer(context: Context) {
    //...
    private val packetsLocalDataSource = PacketsLocalDataSource(context)
    //...

And when creating PocketScoutContainer instanse in some Activity:

val pocketScoutContainer = PocketScoutContainer(this.applicationContext)

If PocketScoutContainer instantiated somewhere outside an activity or a fragment, you will need to pass Context there.

This may help further: Dependency Injection

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bylazy