小王裁缝 2021-08-20 19:29 采纳率: 0%
浏览 29

Kotlin使用Contex报错,初始化失败

代码如下:


private lateinit var context: Context
private fun getSharedPreferences(spFileName: String): SharedPreferences {
            return context.getSharedPreferences(spFileName, Context.MODE_PRIVATE)
        }
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.zego_wb, PID: 7324
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zego_wb/com.example.zego_wb.activity.LoginActivity}: kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
     Caused by: kotlin.UninitializedPropertyAccessException: lateinit property context has not been initialized
        at com.example.zego_wb.util.SharedPreferencesUtil$Companion.getSharedPreferences(SharedPreferencesUtil.kt:26)
        at com.example.zego_wb.util.SharedPreferencesUtil$Companion.getLastJoinID(SharedPreferencesUtil.kt:80)
        at com.example.zego_wb.activity.LoginActivity.initView(LoginActivity.kt:35)
        at com.example.zego_wb.activity.LoginActivity.onCreate(LoginActivity.kt:29)


  • 写回答

1条回答 默认 最新

  • 普通网友 2021-08-21 11:34
    关注

    application 这个类 不能使用kotlin的方法进行代码编写。要使用正常的java模式进行编写,否则你要把检查初始化这个钩去掉,不然会报错

    评论

报告相同问题?

问题事件

  • 创建了问题 8月20日

悬赏问题

  • ¥15 编辑cmake lists 明明写了project项目名,但是还是报错怎么回事
  • ¥15 关于#计算机视觉#的问题:求一份高质量桥梁多病害数据集
  • ¥15 特定网页无法访问,已排除网页问题
  • ¥50 如何将脑的图像投影到颅骨上
  • ¥15 提问一个关于vscode相关的环境配置问题,就是输入中文但是显示不出来,代码在idea可以显示中文,但在vscode不行,不知道怎么配置环境
  • ¥15 netcore使用PuppeteerSharp截图
  • ¥20 这张图页头,页脚具体代码该怎么写?
  • ¥15 关于#sql#的问题,请各位专家解答!
  • ¥20 WPF MVVM模式 handycontrol 框架, hc:SearchBar 控件 Text="{Binding NavMenusKeyWords}" 绑定取不到值
  • ¥15 需要手写数字信号处理Dsp三个简单题 不用太复杂