0

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.

Pedro Relvas
  • 678
  • 7
  • 19
  • 1
    Are you sure that ID is actually in your layout? Also, the type that's inside the `<>` is there so you can specify which View that ID is. `findViewById(R.id.viewPagerGaleria) as ViewPager` can be shortened to `findViewById – TheWanderer Oct 29 '18 at 16:45
  • @TheWanderer yes sir, it is... – Pedro Relvas Oct 29 '18 at 16:49
  • Are you sure? If `findViewById()` returns null it means it can't find any View by that name. Where are these methods being called and where is `setContentView()` being called? Are you sure you're setting the right layout? – TheWanderer Oct 29 '18 at 16:55

2 Answers2

0

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.

Boukharist
  • 1,219
  • 11
  • 19
0

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

Pedro Relvas
  • 678
  • 7
  • 19