gpt4 book ai didi

android - 在 Activity 的初始化 block 中使用 'this' 作为上下文?

转载 作者:行者123 更新时间:2023-12-02 12:37:58 25 4
gpt4 key购买 nike

我正在用 kotlin 开发一个 android 应用程序。

我有一个 DereDatabaseHelper具有 init 的类使用 context 的 block 通过类参数(?)
DereDatabaseHelper是这样的。

class DereDatabaseHelper(context: Context) {
val manifestFile: File
val fumensDBFile: File
val fumenFolder: File

val musicIDToInfo: MutableMap<Int, MusicInfo> = HashMap()
val fumenIDToMusicID: SparseIntArray = SparseIntArray()

init {
val datadir = context.getExternalFilesDir(null).parentFile.parentFile
DereDatabaseHelper类在 SongListActivity 中被实例化像这样。
class SongListActivity : AppCompatActivity() {
var dereDatabaseHelper : DereDatabaseHelper
init {
dereDatabaseHelper = DereDatabaseHelper(this)
}

我认为这段代码是正确的,但是这段代码抛出 NullPointerException .

java.lang.NullPointerException: Attempt to invoke virtual method

'java.io.File android.content.Context.getExternalFilesDir(java.lang.String)'

on a null object reference at

android.content.ContextWrapper.getExternalFilesDir(ContextWrapper.java:253) at com.kyhsgeekcode.dereinfo.model.DereDatabaseHelper.<init>(DereDatabaseHelper.kt:21) at com.kyhsgeekcode.dereinfo.SongListActivity.<init>(SongListActivity.kt:31)



this执行在 init 时为 null block ,我应该使用什么初始化样式来解决这个问题?

最佳答案

永远不要使用 Activity 的构造函数来做任何涉及 Context 的事情。 Android 使用其唯一的空构造函数(通过反射)实例化 Activity ,然后在 Activity 调用 onCreate() 之前设置 Activity 的各个字段。 .您在 Activity 中执行任何操作的第一个安全入口点位于 onCreate() .

您也不能在构造函数中调用 Activity(它本身就是一个 Context)的方法。

您也不能以任何方式使用上下文来设置属性,因为它们会尝试在 onCreate 之前访问上下文。 :

class MyActivity: AppCompatActivity() {
val assets: AssetManager = getAssets() // This will cause a crash
}

为避免使您的属性可以为空,您可以执行以下任一操作,这样您就可以避免在 onCreate() 之后实例化您的类。叫做:
class SongListActivity : AppCompatActivity() {
lateinit var dereDatabaseHelper : DereDatabaseHelper

override fun onCreate() {
super.onCreate
dereDatabaseHelper = DereDatabaseHelper(this)
}

或者
class SongListActivity : AppCompatActivity() {
val dereDatabaseHelper by lazy { DereDatabaseHelper(this) }
}

关于android - 在 Activity 的初始化 block 中使用 'this' 作为上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com