英文:
Get Context in Android Room Migration
问题
Sure, here is the translated content:
在Android Room迁移中获取上下文:
在我的迁移中,我想获取上下文以从资产中读取一些文件:
@Module
@InstallIn(SingletonComponent::class)
object
PersistenceModule : Application() {
@Provides
@Singleton
fun provideAppDatabase(
@ApplicationContext context: Context,
): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app")
.addMigrations(MIGRATION_3_4)
.build()
}
val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
//...
val txt = context.resources.assets.open("example.txt").bufferedReader().use { it.readText() }
}
}
Please note that the code remains in Kotlin, and I've translated the comments and string literals.
英文:
Get Context in Android Room Migration:
In my Migration i want to get context to read some files from assets:
@Module
@InstallIn(SingletonComponent::class)
object
PersistenceModule : Application() {
@Provides
@Singleton
fun provideAppDatabase(
@ApplicationContext context: Context,
): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app")
.addMigrations(MIGRATION_3_4)
.build()
}
val MIGRATION_3_4 = object : Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
//...
val txt = context.resources.assets.open("example.txt").bufferedReader().use { it.readText() }
}
}
答案1
得分: 1
Create a class extending Migration
which takes context
as parameter in constructor
class Migration3to4(@ApplicationContext val context: Context): Migration(3, 4) {
override fun migrate(database: SupportSQLiteDatabase) {
// access context here
val txt = context.resources.assets.open("example.txt").bufferedReader().use { it.readText() }
}
}
Callsite
@Module
@InstallIn(SingletonComponent::class)
object PersistenceModule {
@Provides
@Singleton
fun provideAppDatabase(
@ApplicationContext context: Context,
): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app")
.addMigrations(Migration3to4(context))
.build()
}
英文:
Create a class extending Migration
which takes context
as parameter in constructor
class Migration3to4(@ApplicationContext val context: Context): Migration(3.4) {
override fun migrate(database: SupportSQLiteDatabase) {
// access context here
val txt = context.resources.assets.open("example.txt").bufferedReader().use { it.readText() }
}
}
Callsite
@Module
@InstallIn(SingletonComponent::class)
object
PersistenceModule : Application() {
@Provides
@Singleton
fun provideAppDatabase(
@ApplicationContext context: Context,
): AppDatabase = Room.databaseBuilder(context, AppDatabase::class.java, "app")
.addMigrations(Migration3to4(context))
.build()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论