[Android] okhttp onResponse에서 java.lang.IllegalStateException 발생

안드로이드 어플에서 간헐적으로 java.lang.IllegalStateException이 발생했습니다.

 

플레이콘솔에서 제공되는 원인은 위와 같았지만 좀 애매했습니다. 정확히 뭐가 문제라는 것인지..

그래서 코드를 좀 더 살펴봤습니다.

 

java.lang.IllegalStateException:

at androidx.fragment.app.Fragment.requireContext (Fragment.java:805)

at androidx.fragment.app.Fragment.getResources (Fragment.java:869)

at com.xxx.yyy.zzz$11.onResponse (FragmentA.java:1152)

at okhttp3.RealCall$AsyncCall.run (RealCall.kt:140)

at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1167)

at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:641)

at java.lang.Thread.run (Thread.java:764)

 

okhttp3의 onResponse에서 시작되어.. 결구은

Fragment.java의 requireContext함수의 805 라인에서 exception이 발생했습니다.

 

    public final Context requireContext() {
        Context context = getContext();
        if (context == null) {
            throw new IllegalStateException("Fragment " + this + " not attached to a context.");
        }
        return context;
    }

코드를 보면.. requireContext()가 불릴 당시에 context가 null이라서 발생한 것입니다.

 

이미 비슷한 문제를 겪어봤기에.. 테스트를 해봤습니다.

문제가 발생한 FragmentA의 onResponse의 코드 초반에 Thread.sleep(2000)으로.. 2초의 딜레이를 추가했습니다.

그리고 onResponse콜백이 오기 전에 FragmentA를 종료 시켰습니다.

okhttp3의 onResponse 콜백은 당연히 async하게 동작하므로.. FragmentA 종료 이후에 불립니다.

 

그리고.. FragmentA가 사라진 시점에선.. getContext()가 null을 리턴하기에 문제가 생겼던 것입니다.

 

각자의 상황이 다르긴 하겠지만..

보통 FragmentA가 사라진 시점에서 onResponse가 불릴 때는.. 그냥 getContext를 체크하여 null이면

아무동작도 안하게 하면 될 것입니다.

작성자

Posted by 드리머즈

관련 글

댓글 영역