Zar E Ahmer
Zar E Ahmer

Reputation: 34370

getParcelable in kotlin not parsing to model object correctly Android

I use @Parcelize to make data class Parcelable like

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

And calling and passing data to fragment like

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

newInstance Method

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

And in onViewCreated I am getting it using arguments like

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)*/
        }
    }

Notes

I debug argument it shows data in onViewCreated but don't convert it to QuestionBO

enter image description here

What's wrong in the given statement!!!

arguments!!.getParcelable<QuestionBO>(KEY_QUESTION_BO) as Nothing?

Upvotes: 1

Views: 2305

Answers (2)

Luca Nicoletti
Luca Nicoletti

Reputation: 2427

The as Nothing? you're using is the wrong part. You're saying that the object you retrieve is of type Nothing? whereas you're trying to get a QuestionBO?.

As @shkschneider said, replace Nothing? with QuestionBP? and your code will work properly.

Upvotes: 0

shkschneider
shkschneider

Reputation: 18243

First, I'm pretty sure you should use getParcelable<QuestionBO>(KEY_QUESTION_BO) as QuestionBO?

And then from what I can see from your debugger, result.mMap.value[0] is indeed recognized as a QuestionBO object.

Looks good to me otherwise.

Upvotes: 2

Related Questions