簡體   English   中英

Kotlin Android擴展:java.lang.IllegalStateException:視圖不能為null

[英]Kotlin Android Extensions : java.lang.IllegalStateException: view must not be null

我在片段中使用Kotlin視圖綁定。 在某些情況下,應用程序崩潰且IllegalStateException &view為null,我在可運行對象中訪問它,該可運行對象使用具有1.5秒延遲的處理程序進行調用。

 numberRunnable = Runnable {
        if (mobileView.text.toString().isNotEmpty() && Utility.isMobileNumberValid(mobileView.text.toString())) {
            presenter.getCustomerDetails(Utility.getServerAcceptableContactNumber(mobileView.text.toString()))
        }
    }

mobileView為null

處理程序代碼: handler.postDelayed(numberRunnable, 1500)

我知道有一種可能性可以檢查片段中是否isAdded我的isAdded ,但是由於我無法復制該錯誤,因此不確定是否是問題所在。

您不能假設1.5秒后視圖仍附加到視圖層次結構。

在片段不再活動時,將numberRunnable handler.removeCallbacks(numberRunnable)添加到onStop()生命周期回調中,以刪除numberRunnable

還要問自己一個問題,為什么需要延誤。

用戶離開Fragment並調用onDestroy()后,該操作可能會運行。 在這種狀態下,片段中將沒有View實例。

一個簡單的解決方法是創建一個全局var來檢查Fragment的創建狀態。 在超級調用之前,在onViewCreated()其設置為true ,在onDestroyView() onViewCreated()其設置為false 然后在執行邏輯之前檢查Runnable內部的值。

更好的解決方案(盡管這受競爭條件的影響,並且需要將每個Runnable分配給全局變量)可能是使用Handler.removeCallbacks()方法並傳遞所有Runnable。

override fun onDestroyView() {
    handler.removeCallbacks(numberRunnable)
}

還有另一種可能性是簡單地說View是可為空的:

mobileView?.let {
    //Your stuff goes in here
    //You can reference mobileView using "it"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM