首页 > 解决方案 > 从 getParcelableExtra() 接收 null

问题描述

我有一个类类别,我传递给额外的类别,点击类别。这在 6 个屏幕中有效,但在最后一个屏幕中我收到 null

我把额外的活动

adapter.setOnItemClickListener { item, view ->

                    val categories = item as Categories
                    val intent = Intent(view.context, LearningFirstLibras::class.java)
                    intent.putExtra(CATEGORY_KEY, categories.category)
                    startActivity(intent)
                }

类别

@Parcelize
class Category(
               val name: String,
               val imageURL: String,
               val real_name: String,
               val object_1_screen_libras_image: String,
               val object_1_screen_libras_text: String,
               val object_2_screen_libras_text: String,
               val object_2_screen_libras_image: String,
               val object_3_screen_libras_text: String,
               val object_3_screen_libras_image: String,
               val object_1_screen_asl_text: String,
               val object_1_screen_asl_image: String,
               val object_2_screen_asl_text: String,
               val object_2_screen_asl_image: String,
               val object_3_screen_asl_text: String,
               val object_3_screen_asl_image: String,
               val question: String,
               val answer: String,
               val alternative_1: String,
               val alternative_2: String,
               val alternative_3: String,
               val alternative_4: String
                ) : Parcelable {
    constructor() : this("", "", "", "", "",
            "","","","",
            "","","","",
            "","","","","","",
            "","")
}

我得到空的活动

class Quiz : AppCompatActivity() {

    var categoryF:Category = Category()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_quiz)

        categoryF = intent.getParcelableExtra(NewWordsActivity.CATEGORY_KEY)

标签: androidandroid-intentkotlin

解决方案


试试看

使用 Bundle 发送 Parcelable

val intent = Intent(this, ProfilePage::class.java)
var bundle = Bundle()
bundle.putParcelable(CATEGORY_KEY, categories.category)
intent.putExtra("myBundle",bundle)
startActivity(intent)

恢复 Parcelable

val bundle = intent.getBundleExtra("myBundle")
var categoryF = bundle.getParcelable<Category>(NewWordsActivity.CATEGORY_KEY) as Category

推荐阅读