[英]How can I get context in Android Jetpack Compose using Kotlin?
我在 Kotlin 中有一个 Android Jetpack Compose 应用程序,其中 function 需要上下文。 function 如下所示。
fun copyDataBase(context: Context, OUTPUT_DB_PATH: String, DB_NAME: String) {
// Path to output database path (application database path).
var APP_DB_FILE_PATH = OUTPUT_DB_PATH + "/" + DB_NAME
// Path to input database file.
var INPUT_DB_PATH = "database/" + DB_NAME
// Open your local db as the input stream
val databaseInput: InputStream = context.getAssets().open(INPUT_DB_PATH)
// Open the empty db as the output stream
val databaseOutput: OutputStream = FileOutputStream(APP_DB_FILE_PATH)
// Transfer bytes from the inputfile to the outputfile
val buffer = ByteArray(1024)
var length: Int
while (databaseInput.read(buffer).also { length = it } > 0) {
databaseOutput.write(buffer, 0, length)
}
// Close the streams
databaseOutput.flush()
databaseOutput.close()
databaseInput.close()
}
然后在主要活动中我这样做。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// How can I get context to supply to the function?
copyDataBase(context, DB_PATH, DB_NAME)
setContent {
Column() {
TopAppBar(title = { Text(text = "Nyimbo") })
ScrollableColumn(Modifier.fillMaxWidth()
.padding(10.dp)) {
lyricsPageComposable(lyricsMap = songMap)
}
}
}
}
}
如何获取上下文以将其提供给主要活动中的 function? 它是从哪个 Jetpack Compose 命名空间导入的?
我试过import android.content.Context
但这需要初始化,我不知道该怎么做。
想法是在首次运行时将预填充的 SQLite 数据库从资产目录复制到应用程序中。
如何获取上下文以将其提供给主要活动中的 function?
在你有那个电话的地方,使用this
。 一个Activity
是一个Context
。
理想情况下,这段代码不会在活动中——它会在存储库中,或者最坏的情况是视图模型,实际的磁盘 I/O 在后台线程上执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.