Hey guys, I'm using Butterknife in a mixed Java/Ko...
# android
m
Hey guys, I'm using Butterknife in a mixed Java/Kotlin project. I'm used to declare views as
lateinit var
ex.:
@BindView(R.id.swipe_refresh_layout) lateinit var swipeRefreshLayout: SwipeRefreshLayout
, that's fine right? To be able to show the loading animation of SwipeRefreshLayout programmatically, I use this method:
Copy code
fun showLoading() {
        <http://swipeRefreshLayout.post|swipeRefreshLayout.post>({ 
            swipeRefreshLayout.isRefreshing = true 
        })
    }
This is inside a fragment, inside a viewpager/tabs. Thing is, I have a case (I supposed that it's because I unbind in onDestroyView) where sometimes the swipeRefreshLayout variable is null once inside the post block. It seems it has to do with the tab/fragment not being visible so I thought I'd check inside post if (isAdded) but no luck there. Any idea?
g
Doesn’t look related to Kotlin. Maybe your function called before injection of views in some case
m
Yeah, one could argue it's semi related but at the same time, it is: It's more of a general question about the use of lateinit for views and if it's the right way in this case.
The thing is, even if I explicitly check for null here, the fact that the variable is lateinit, it will still throw an exception.
Also if some property can be null just use nullable type instead of lateinit
m
Interesting, I'll check the isInitialized method, thanks.
g
Actually in this case nullable is completely fine:
Copy code
swipeRefreshLayout?.isRefreshing = true
much better than isInitilized check.
what is your case here? Maybe easier to inject views onCreate to avoid such situation