null cannot be cast to non-null type android.support.v4.view.ViewPager - KOTLIN

578 Views Asked by At

I know that these question has been already answered, but I think it's a different deal. So, I have the following code:

viewPager = findViewById<View>(R.id.viewPagerGaleria) as ViewPager
val adapter = ViewPageAdapter(this)
viewPager.adapter = adapter
//dots
val pageIndicatorView = findViewById<View>(R.id.pageIndicatorView) as PageIndicatorView
pageIndicatorView.setViewPager(viewPager)

And when I run it this occurs: ... kotlin.TypeCastException: null cannot be cast to non-null type android.support.v4.view.ViewPager. Normal till here, right? No, because when I do this, the error is the same:

val viewPager = findViewById<View>(R.id.viewPagerGaleria) as? ViewPager
val adapter = ViewPageAdapter(this)
viewPager?.adapter = adapter
//dots
val pageIndicatorView = findViewById<View>(R.id.pageIndicatorView) as? PageIndicatorView
pageIndicatorView?.setViewPager(viewPager)

Can you help me? Thank you.

2

There are 2 best solutions below

0
Boukharist On BEST ANSWER

I agree with @TheWanderer, your problem is here :findViewById**** .

So to fix this you can remove the type and replace it by and get rid of the cast "as? ViewPager" as it is not needed in this case

val viewPager = findViewById<ViewPager?>(R.id.viewPagerGaleria) 

Or omit the target class type definitely and keep the cast

val viewPager = view.findViewById(R.id.viewpager) as? ViewPager

PS : And you probably don't have the required viewPager id in your layout.

0
Pedro Relvas On

Sorry mates, i was putting that code in the wrong class! My bad!