[Android] Fragment InstantiationException 해결

hegleB·2023년 6월 30일
0
post-thumbnail

문제

could not find Fragment constructor

회전하기 전에는 문제가 없었지만, 회전 후에는 InstantiationException이 발생하는 문제가 발생하였다.

원인

InstantiationException은 프래그먼트가 재생성되는 동안 발생하는 오류이다. 회전과 같은 상황에서 프래그먼트가 재생성되면서 이 오류가 발생하게 된다.

오류 발생 코드

private var listener: RegionPositionCallback
private var arealistener: AreaNameCallback


init {
	this.listener = listener
	this.arealistener = arealistener
}

해결 방안

private var listener: RegionPositionCallback? = null
private var arealistener: AreaNameCallback? = null


init {
	this.listener = listener
	this.arealistener = arealistener
}

listener와 arealistener 인수를 초기화하지 않고 사용하였다. listener와 arealistener 변수를 nullable로 선언하고 기본값으로 null을 할당하여 문제를 해결하였다.

All subclasses of Fragment must include a public no-argument constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the no-argument constructor is not available, a runtime exception will occur in some cases during state restore. - Google Developers

구글 공식 문서에 보면 안드로이드 프래그먼트는 프래그먼트의 인스턴스화와 상태 복원을 위해 기본적으로 생성자가 필요하다. 따라서 프래그먼트 클래스를 생성할 때는 생성자를 반드시 포함시켜야 한다. 이렇게 함으로써 앱이 실행 중에 예외가 발생하는 상황을 방지할 수 있다.

AndroidX

AndroidX 라이브러리 및 Fragment 버전 1.2.0부터는 FragmentFactory를 사용하여 문제를 해결할 수 있다고 한다.

profile
성장하는 개발자

0개의 댓글

관련 채용 정보