1

I am using viewpager for a carousel in my application. it works fine when the app open for the first time, but when coming back from another fragment am getting an error as NullPointerException, I have tried diffrent method for this but none works. Below is my code and error log from firebase.

   private fun initCarousal() {
        carousal.adapter = TransactCarousalAdapter {
            when (it) {
                0 -> {
                    Case1()
                }
                1 -> {
                    Case2()
                }
                2 -> {
                    case3()
              

            }
        }
        dots_indicator.setViewPager(carousal)

        val handler = Handler()

        val update = Runnable {
            var currentPage = carousal.currentItem // Here am getting error LINE NO. : 87
            if (currentPage == 1) {
                currentPage = 0
            } else {
                currentPage++
            }
            carousal.setCurrentItem(currentPage, true)
        }


        timer.schedule(object : TimerTask() {
            override fun run() {
                handler.post(update)
            }
        }, 7000, 7000)
    }


    override fun onResume() {
        super.onResume()
        timer = Timer()
        initCarousal()
    }
    override fun onStop() {
        super.onStop()
        timer.cancel()
    }

Error log

java.lang.NullPointerException: Attempt to invoke virtual method 'int androidx.viewpager.widget.ViewPager.getCurrentItem()' on a null object reference
    com.bslamc.fingo.ui.dashboard.transact.TransactFragment.initCarousal$lambda-0(TransactFragment.kt:87)
    android.os.Handler.handleCallback(Handler.java:938)
    android.os.Handler.dispatchMessage(Handler.java:99)
    android.os.Looper.loop(Looper.java:255)
    android.app.ActivityThread.main(ActivityThread.java:8212)
    java.lang.reflect.Method.invoke(Method.java:0)
    com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:632)
    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1049)
Anees Ani
  • 23
  • 2
  • check [this](https://stackoverflow.com/questions/1409116/how-to-stop-the-task-scheduled-in-java-util-timer-class) you need to cancel also your `object : TimerTask()` – anatoli Aug 29 '23 at 09:33

1 Answers1

0

carousal is null - and it looks like it is not being initialized anywhere.

Do you have a line like this that you can add to initialize it:

       carousal = findViewById(R.id.carousal)
ryankuck
  • 320
  • 3
  • 15