代码之家  ›  专栏  ›  技术社区  ›  Zar E Ahmer

kotlin中的getParcelable无法正确解析对象模型Android

  •  0
  • Zar E Ahmer  · 技术社区  · 6 年前

    @Parcelize
    data class QuestionBO(val title: String, val options: List<String>, val correctOptionIndex: Int,
                          val dateCreated: Date, val tags: List<String>, val questionType: Int,
                          val userID: String, val userName: String, val totalLikes: Int,
                          val imageUrl: String) : Parcelable {
        constructor() : this("", emptyList(), 1, Date(), emptyList(), 3, ""
                , "", 34, "")
    }
    

    调用并将数据传递给片段

    supportFragmentManager.beginTransaction().add(
                    QuestionFragment.newInstance(singleQuestion), "QuestionFragment").commit()
    

    newInstance方法

    companion object {
            private const val KEY_QUESTION_BO = "key_question_bo"
    
            fun newInstance(aQuestion: QuestionBO) = QuestionFragment().apply {
                arguments = Bundle(2).apply {
                    putParcelable(KEY_QUESTION_BO, aQuestion)
                }
            }
        }
    

    OnView已创建 我是用像

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            if(arguments != null){
                mQuestionBO = arguments!!.getParcelable<QuestionBO>(KEY_QUESTION_BO) as Nothing?
    
                /*var bundle = arguments!!.getBundle("bundle")
                bundle.getParcelable<QuestionBO>(KEY_QUESTION_BO)*/
            }
        }
    

    我调试参数它在onViewCreated中显示数据,但不将其转换为QuestionBO

    enter image description here

    arguments!!.getParcelable<QuestionBO>(KEY_QUESTION_BO) as Nothing?
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   shkschneider blazzerbg    6 年前

    getParcelable<QuestionBO>(KEY_QUESTION_BO) as QuestionBO?

    从你的调试器中我可以看到, result.mMap.value[0] 是公认的 QuestionBO

    否则我觉得不错。

        2
  •  0
  •   Luca Nicoletti    6 年前

    这个 as Nothing? Nothing? 而你想得到一个 QuestionBO?

    正如@shkschneider所说,替换 没有什么? 具有 QuestionBP?