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

时间:2018-10-18 10:36:11

标签: android kotlin parcelable

  

我使用@Parcelize使数据类像Parcelable一样

@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)
            }
        }
    }

onViewCreated 中,我使用类似的参数

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 个答案:

答案 0 :(得分:1)

首先,我很确定您应该使用getParcelable<QuestionBO>(KEY_QUESTION_BO) as QuestionBO?

然后从调试器中可以看到,result.mMap.value[0]实际上被识别为QuestionBO对象。

否则对我很好。

答案 1 :(得分:0)

您使用的as Nothing?是错误的部分。 您说的是,您检索的对象是Nothing?类型,而您正在尝试获取QuestionBO?

正如@shkschneider所说,将Nothing?替换为QuestionBP?,您的代码将正常工作。

相关问题