You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Kotlin读取Json文件时Context引用异常问题求助

解决Android Kotlin读取Json文件时Context找不到的问题

问题出在readJsonFile()方法里的context.openFileInput("User.json")这一行——你直接使用了未定义的context变量,而Launcher作为AppCompatActivity的子类,本身就继承了Context的能力,直接用this或者applicationContext替代即可。

修正后的完整代码:

class Launcher : AppCompatActivity() {

    lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launcher)
        textView = findViewById(R.id.textView)
        readJsonFile()
    }

    fun readJsonFile() {
        val json: String?
        try {
            // 用this替代context,当前Activity本身就是Context实例
            val inputStream = this.openFileInput("User.json")

            json = inputStream.bufferedReader().use { it.readText() }
            val gson = Gson()
            val user = gson.fromJson(json, User::class.java)

            CurrentUser.initUser(user.id,user.name)

            startActivity(Intent(this, MainActivity::class.java))
        } catch (e: FileNotFoundException) {
            startActivity(Intent(this, ChooseLoginActivity::class.java))
        }
    }
}

额外优化建议:

  • 将readJsonFile()标记为private,因为它仅在当前类内部调用
  • 把文件读取操作放到协程中执行,避免阻塞主线程:
private fun readJsonFile() = lifecycleScope.launch {
    withContext(Dispatchers.IO) {
        try {
            val inputStream = openFileInput("User.json")
            val json = inputStream.bufferedReader().use { it.readText() }
            val user = Gson().fromJson(json, User::class.java)

            CurrentUser.initUser(user.id,user.name)

            withContext(Dispatchers.Main) {
                startActivity(Intent(this@Launcher, MainActivity::class.java))
            }
        } catch (e: FileNotFoundException) {
            withContext(Dispatchers.Main) {
                startActivity(Intent(this@Launcher, ChooseLoginActivity::class.java))
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Pantastix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:25:23