android error 有關舊程式碼改成mvvm架構


Posted by Limon on 2022-01-18

最近firebase一直收到用戶的crash

Fatal Exception: java.lang.IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()
       at androidx.fragment.app.Fragment.getViewLifecycleOwner(Fragment.java:328)
       at com.android.yungching.fragment.MapFragment.requestBuyListCoordinateData(MapFragment.java:1395)
       at com.android.yungching.fragment.MapFragment.startRequestData(MapFragment.java:857)
       at com.android.yungching.fragment.MapFragment.lambda$onActivityCreated$1(MapFragment.java:444)
       at com.android.yungching.fragment.-$$Lambda$MapFragment$h1Yip61McjPKUFCH6xYXeHz00CI.onClick(-.java:4)
       at android.view.View.performClick(View.java:6597)

看了一下code,原來是因為舊程式碼為了改成mvvm,在call.enqueue裡面放入參數getViewLifecycleOwner()

但是

觀看了一下getViewLifecycleOwner()的source code

 @MainThread
    @NonNull
    public LifecycleOwner getViewLifecycleOwner() {
        if (mViewLifecycleOwner == null) {
            throw new IllegalStateException("Can't access the Fragment View's LifecycleOwner when "
                    + "getView() is null i.e., before onCreateView() or after onDestroyView()");
        }
        return mViewLifecycleOwner;
    }

不知道為什麼明明呼叫這行的程式碼已經放在onActivityCreated裡面(代表它必定會在onCreateView之後執行)
getView()卻還是null

而該Fragment頁面並沒有用到與onDestroy相關的地方
完全不知道該如何重現bug
我們自己內部測試都不會有crash

最後只好放棄用getViewLifecycleOwner()
換成使用getViewLifecycleOwnerLiveData().getValue()
再將傳入的父類object中檢查owner是否為null在執行後面的程式碼
讓使用者不會crash最重要

本來以為會需要改很多東西
觀看父類object才發現,裡面已經有偵測owner是否為null的code了
因此幾乎不需要增加任何code
可喜可賀~可喜可賀!


#Android #Firebase







Related Posts

Leetcode 刷題 pattern - Merge Intervals

Leetcode 刷題 pattern - Merge Intervals

SQL-injection lab(9)

SQL-injection lab(9)

Lecture 1 Introduction to Radar Systems and Applications

Lecture 1 Introduction to Radar Systems and Applications


Comments