【问题标题】:I'm trying to take bundles on my HomeFragment but when i enter first, i got error我正在尝试在我的 HomeFragment 上打包,但是当我第一次输入时,出现错误
【发布时间】:2023-02-01 02:13:02
【问题描述】:

我正在将捆绑包发送到我的另一个片段的 Home Fragment。但是当应用程序第一次打开时,给我一个错误,因为应用程序一开始没有接受任何捆绑包。顺便说一句,我正在发送和接收这样的捆绑包;

//Sending
            val fragment = Notlar()
            val bundle = Bundle()
            bundle.putInt("categoryId", -99)
            fragment.arguments = bundle
            findNavController().navigate(R.id.action_kategoriler_to_notlar, bundle)

//Getting (On Home Fragment)
            categoryIdBundle = requireArguments().getInt("categoryId",-1)

我试过类似的东西;

try {
    categoryIdBundle = requireArguments().getInt("categoryId",-1)
} catch (e : Exception) {
    categoryIdBundle = -1
}

但是即使它在一开始就打开了,我发送的包从来没有来过,所以 catch 块总是有效。此时我能做什么?

【问题讨论】:

    标签: kotlin bundle


    【解决方案1】:

    你可以试试安全呼叫运营商在 Kotlin .? 中确保数据是否不为空,并尝试使用此代码在片段之间使用 bundle 发送数据

    // in the first fragment
    
    findNavController().navigate(
        R.id.action_kategoriler_to_notlar,
        Bundle().apply {
            putInt("categoryId", -99)
        }
    )
    
    // in destination fragment
    arguments?.getInt("categoryId", -1)?.let {
        // handle the result here ...
    }
    

    你可以阅读更多关于安全呼叫here,以及关于在导航here发送捆绑包

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 2019-05-23
      • 2012-11-25
      • 1970-01-01
      • 2022-11-13
      • 2019-03-23
      相关资源
      最近更新 更多