Closed6

画面遷移できない | 明示的にUIスレッドを呼び出す

tkttkt

実装していたら、「あれ?画面遷移しないぞ?」となった

tkttkt
findNavController().navigate(direction)

実行すると

I/NavController: Ignoring popBackStack to destination com.example:id/mainFragment as it was not found on the current back stack
W/System.err: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.application.presenter.fragment.ExampleFragment: calling Fragment constructor caused an exception
W/System.err:     at androidx.fragment.app.Fragment.instantiate(Fragment.java:566)
W/System.err:     at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
W/System.err:     at androidx.fragment.app.FragmentManager$3.instantiate(FragmentManager.java:390)
W/System.err:     at androidx.navigation.fragment.FragmentNavigator.instantiateFragment(FragmentNavigator.java:132)
W/System.err:     at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:162)
        at androidx.navigation.fragment.FragmentNavigator.navigate(FragmentNavigator.java:58)
W/System.err:     at androidx.navigation.NavController.navigate(NavController.java:979)
        at androidx.navigation.NavController.navigate(NavController.java:913)
        at androidx.navigation.NavController.navigate(NavController.java:850)
W/System.err:     at androidx.navigation.NavController.navigate(NavController.java:836)
        at androidx.navigation.NavController.navigate(NavController.java:1031)
        at com.example.application.presenter.fragment.ContainerBaseFragment.navigate(ContainerBaseFragment.kt:21)
        at java.lang.Thread.run(Thread.java:761)
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
W/System.err:     at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
        at androidx.fragment.app.Fragment.instantiate(Fragment.java:548)
        ... 16 more
    Caused by: java.lang.IllegalStateException: Method addObserver must be called on the main thread
        at androidx.lifecycle.LifecycleRegistry.enforceMainThreadIfNeeded(LifecycleRegistry.java:317)
        at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:172)
        at androidx.fragment.app.Fragment.initLifecycle(Fragment.java:496)
        at androidx.fragment.app.Fragment.<init>(Fragment.java:476)
        at com.example.application.presenter.fragment.ContainerBaseFragment.<init>(ContainerBaseFragment.kt:11)
        ... 19 more
D/EventNotifyStatusIO: Error Stop
    Termination
tkttkt

どうやら別スレッドで動いているらしい
ので明示的にUIスレッドを呼び出したい

tkttkt
override fun onThreading() {
    // 別スレッド処理
    something()
    // UIスレッド指定
    view?.post {
         findNavController().navigate(direction)
    }
}

これで動いた
かんたん

このスクラップは2021/04/23にクローズされました