본문 바로가기

IT/안드로이드 관련

[안드로이드] getContext와 requireContext 차이

안녕하세요 남갯입니다


오늘은 getContext와 requireContext의 차이에 대해 포스팅 해보려고 합니다.


참고링크 : https://medium.com/@shafran/fragment-getcontext-vs-requirecontext-ffc9157d6bbe


getContext & requireContext 의 차이



@Nullable
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}

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



requireContext는 fragment가 확실히 이것의 호스트에 붙어있을때만 사용해야 합니다.

아닐경우(null일 경우) error가 발생합니다.  (사용처 onResume, onViewCreated)


따라서 NonNull일때만 동작해야하는 경우에는 getContext에서 requireContext() 로 변경해서 사용해라. 하지만 혹시나 host에 붙지 않았을 경우에 사용하게 된다면 exception thorw을 통해 사용해야한다.


코틀린의 경우 Fragment의 Context? 를 반환하기 때문에 requireContext를 통해 Context를 반환 가능하다.


또한 

getActivity와 requireActivity 동일하다.