Rishabh Mehta
Rishabh Mehta

Reputation: 472

How can I use a Timer of 2 seconds inside a fragment?

This is my Fragment.kt

class SplashFragment : Fragment() {

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

        return inflater.inflate(R.layout.fragment_splash, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
            // My Timer
            Timer().schedule(object : TimerTask() {
                override fun run() {
                    findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
                }
            }, 2000)

    }
}

This is my Logcat error

2022-02-06 20:37:34.755 27478-27510/com.finite.livelocationtest E/AndroidRuntime: FATAL EXCEPTION: Timer-0
    Process: com.finite.livelocationtest, PID: 27478
    java.lang.NullPointerException: Can't toast on a thread that has not called Looper.prepare()
        at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:157)
        at android.widget.Toast.getLooper(Toast.java:179)
        at android.widget.Toast.<init>(Toast.java:164)
        at android.widget.Toast.makeText(Toast.java:492)
        at android.widget.Toast.makeText(Toast.java:480)
        at com.finite.livelocationtest.ui.fragment.SplashFragment$onViewCreated$1.run(SplashFragment.kt:31)
        at java.util.TimerThread.mainLoop(Timer.java:562)
        at java.util.TimerThread.run(Timer.java:512)

What do I want to achieve?

I want to go from this fragment to the next fragment after a time of 2 seconds time, please let me know any possible way to achieve this.

Upvotes: 0

Views: 1147

Answers (3)

Syed Rafaqat Hussain
Syed Rafaqat Hussain

Reputation: 1126

just use the Android Handler for 2-second delay. Here is the code sample

Handler(Looper.getMainLooper()).postDelayed({
   //this portion is run when the handler is completing 2 second of delay
}, 2000)

Works on both activity and fragment

Upvotes: 0

Rishabh Mehta
Rishabh Mehta

Reputation: 472

Instead of trying to use Timer class, we can use coroutines.

lifecycleScope.launch {
  delay(2000)
  findNavController().navigate(SplashFragmentDirections.actionSplashFragmentToHomeFragment()))
}

Using this solves the problem I was having, The reason why my app was crashing was that I was trying to Execute UI related things from a background thread, which doesn't work as it is a non-UI thread, so we need to do it on Main Thread.

Upvotes: 1

The exception that you have included tells me you are trying to display a Toast on a non-UI thread. I'm not seeing any toast call in your example, bud please note that you CANNOT show a Toast on non-UI thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread.

Upvotes: 0

Related Questions