NPE在安全中称为Kotlin中的变量。它背后的原因是什么?如何解决?

时间:2019-03-08 11:36:11

标签: android kotlin nullpointerexception

我有以下一段代码。

    var date1: Date? = null

    try {
        date1 = df1.parse(startDate)
    } catch (e: ParseException) {
        e.printStackTrace()
    }
    val cal1: Calendar? = Calendar.getInstance()
    cal1?.time = date1

我在最后一行收到了NPE。这是堆栈跟踪。它不是很频繁,但有时会发生。

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
       at java.util.Calendar.setTime(Calendar.java:1749)
       at ui.interviewslot.InterviewSlotActivity.getDates(InterviewSlotActivity.kt:443)
       at ui.interviewslot.InterviewSlotActivity.setUI(InterviewSlotActivity.kt:125)
       at ui.interviewslot.InterviewSlotActivity$onCreate$1.onChanged(InterviewSlotActivity.kt:78)
       at ui.interviewslot.InterviewSlotActivity$onCreate$1.onChanged(InterviewSlotActivity.kt:33)
       at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
       at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:131)
       at androidx.lifecycle.LiveData.setValue(LiveData.java:289)
       at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:33)
       at androidx.lifecycle.LiveData$1.run(LiveData.java:91)
       at android.os.Handler.handleCallback(Handler.java:808)
       at android.os.Handler.dispatchMessage(Handler.java:101)
       at android.os.Looper.loop(Looper.java:166)
       at android.app.ActivityThread.main(ActivityThread.java:7425)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

设备:HUAWEI P20 Lite Android版本:8.0.0

1 个答案:

答案 0 :(得分:4)

calendar.setTime方法在其参数上调用getTime。如果参数为null,这将导致NPE。我的猜测是您的date1变量为空,因为解析失败。您可以通过执行以下操作来解决它:

val date1: Date? = try {
    df1.parse(startDate)
} catch (e: ParseException) {
    e.printStackTrace()
    null
}

if (date1 != null) {
    val cal1: Calendar? = Calendar.getInstance()
    cal1?.time = date1
}