본문 바로가기

소소한 코딩 이야기/Android

Fragment에서 RecyclerView 사용 시 Null Point Exception 발생 시 해결방법(Kotlin)

Fragment에서 RecyclerView를 이용하여 체크리스트를 구현해 보았습니다.

그런데 Activity에서 구현할 때와 다르게 계속 Null Point Exception이 발생되면서 어플이 강제종료 되는 현상이 발생 되었습니다.

 

분명 Adapter, ViewHolder, ViewModel 그리고 로컬 DB까지 모두 코드 상 오류가 없음을 확인하였고,

DB에는 데이터가 정상적으로 INSERT 되는 것 까지 확인하였습니다.

 

그렇게 약 이틀 간 같은 에러와 싸우며 다양한 방법을 적용해 보던 중, 드디어.. 해결방법을 찾아내었습니다ㅠㅠ

 

처음에는 아래 코드와 같이 Activity에서 RecyclerView를 생성할 때 처럼 Fragment에서 Activity의 onCreate( )와 같은 onCreateView( )에서 adapter를 초기화 했었습니다.

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
		...

        //RecyclerView Initialize
        val checkListRecyclerViewAdapter = CheckListRecyclerViewAdapter()
        check_list_recycler_view.adapter = checkListRecyclerViewAdapter
        check_list_recycler_view.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)

        //ViewModel Initialize
        checkListViewModel =
            ViewModelProvider(this, CheckListViewModel.Factory(activity!!.application))
                .get(CheckListViewModel::class.java)

        checkListViewModel
            .getAllData(campNum)
            .observe(this) {
                    checkList -> checkListRecyclerViewAdapter.setList(checkList)
            }

        val view: View = inflater.inflate(R.layout.fragment_check_list, container, false)
        ...
        // Inflate the layout for this fragment
        return view
    }

그리고 계속되는 에러와 강제종료....ㅠㅠ

 

그렇게 코드 수정과 구글 검색을 계속 해보던 중 찾아낸 해결방법!!!

바로 뷰가 생성된 후에 생성되는 onViewCreated( ) 메소드에 RecyeclerView 호출해야지만 에러가 발생되지 않는 것 이었습니다.

 

View도 생성되지 않은 상태에서 RecyclerView를 호출하다보니 당연히 null point exception이 발생되었던 것이었습니다.

    //onCreateView 에서 뷰가 생성 된 후에 onViewCreate 로 RecyclerView 를 불러와야지만
    //Null Point Exception 을 피할 수 있다.
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        //RecyclerView Initialize
        val checkListRecyclerViewAdapter = CheckListRecyclerViewAdapter()
        check_list_recycler_view.adapter = checkListRecyclerViewAdapter
        check_list_recycler_view.layoutManager = 
        		LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)

        //ViewModel Initialize
        checkListViewModel =
            ViewModelProvider(this, CheckListViewModel.Factory(activity!!.application))
                .get(CheckListViewModel::class.java)

        checkListViewModel
            .getAllData(campNum)
            .observe(this) {
                    checkList -> checkListRecyclerViewAdapter.setList(checkList)
            }

    }

 

코드를 적용한 후 다시 Run을 해보면!

 

정상적으로 RecyclerView가 적용되는것을 확인 할 수 있습니다!

 

 

 

※참고사이트※

https://stackoverflow.com/questions/52186550/recyclerviewcalendar-must-not-be-null/52187152

 

RecyclerViewCalendar must not be null

I am currently creating a custom Dialog to show hours from 00:00 to 23:59, I am using kotlin as language of development. My problem is that when I open the dialog there is an error on the recycler ...

stackoverflow.com