Home > Enterprise >  What to send as Content
What to send as Content

Time:05-12

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)
    }
}

db.kt

@TypeConverters(value = [RoomTypeConverters::class])
@Database(entities = [Packet::class], version = 1, exportSchema = false)
abstract class PacketsDatabase: RoomDatabase() {

    abstract fun packetDao(): PacketDao

    companion object {
        @Volatile
        private var instance: PacketsDatabase? = null;
        fun getInstance(context: Context): PacketsDatabase {
            if (instance == null) {
                instance = Room.databaseBuilder(
                    context,PacketsDatabase::class.java,"packets.db")
                    .allowMainThreadQueries()
                    .build()
            }
            return instance as PacketsDatabase
        }
    }
}

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)
}

CodePudding user response:

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

  • Related