JakeWharton/kotterknife

NPE for abstract View-class

orcchg opened this issue · 3 comments

Imagine, we have an abstract base view-class:

`

abstract class CollectionFragment {
    protected val emptyView: View by bindView(R.id.empty_view)

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

`

then we inherit, and we want to access some view:

`

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

        val rootView: View? = super.onCreateView(inflater, container, savedInstanceState)

        emptyDataButton.visibility = View.GONE  // hide empty data button

        return rootView

    }
}

`

But we get NPE while accessing this 'emptyView':

Caused by: kotlin.KotlinNullPointerException
                                                                              at butterknife.ButterKnifeKt$viewFinder$5.invoke(ButterKnife.kt:73)
                                                                              at butterknife.ButterKnifeKt$viewFinder$5.invoke(ButterKnife.kt)
                                                                              at butterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt:82)
                                                                              at butterknife.ButterKnifeKt$required$1.invoke(ButterKnife.kt)
                                                                              at butterknife.Lazy.getValue(ButterKnife.kt:103)
                                                                              at CollectionFragment.getEmptyDataButton(CollectionFragment.kt:0)
                                                                              at NewsFragment.onCreateView(NewsFragment.kt:50)
                                                                              at android.support.v4.app.Fragment.performCreateView(Fragment.java:2189)

When we rollback to classic ButterKnife:

@BindView(R.id.btn_empty_data) lateinit var emptyDataButton: Button

everything is OK

i also have this problem,especially in fragment.

I don't think it's related to being an abstract class, I think it's related to the view not being set on the fragment yet inside of onCreateView

The fix is to move your code into onViewCreated so the View is already set when the delegate tries to run.

Up. I have the same issue inside in fragment