添加到可变列表(NPE)Kotlin Android时出错

问题描述 投票:0回答:1

-数据类-]

试图向进餐添加对象MutableList

data class YelpRestaurant(

val name: String,
val rating: Double,
val price: String,
@SerializedName("review_count") val numReviews: Int,
@SerializedName("image_url") val imageUrl: String,
val categories: List<YelpCategory>,
val location: YelpLocation,
val meals: MutableList<UserMeals>

-我的活动---

class ThoughtsActivity : AppCompatActivity() {

lateinit var mealName: String
lateinit var mealPrice: String
lateinit var mealThought: String

lateinit var selected_Restaurant : YelpRestaurant

@Subscribe(sticky = true)
fun getRest(selectedRestaurant : YelpRestaurant)  {
    selected_Restaurant = selectedRestaurant

}

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

    thoughtBtn.setOnClickListener() {

        mealName = m_name.text.toString()
        mealPrice = m_price.text.toString()
        mealThought = m_thought.text.toString()

        var addedMeal = UserMeals(mealName, mealPrice.toDouble(), mealThought)

        if (mealName.isNotEmpty()) {
            selected_Restaurant.meals.add(0,addedMeal)

^^^ java.lang.NullPointerException:尝试在空对象引用上调用接口方法'void java.util.List.add(int,java.lang.Object)'。

Debugger where meals=null

   Log.i(selected_Restaurant.meals[0].mealName,"UserMeal Added")
        }
    }
}

override fun onStart() {
    super.onStart()
    EventBus.getDefault().register(this)
}

override fun onStop() {
    super.onStop()
    EventBus.getDefault().unregister(this)
}

}

-数据类---尝试向餐中添加对象MutableList数据类YelpRestaurant(val名称:String,val等级:Double,val价格:字符串,@SerializedName(“ review_count”)val numReviews:整数,@。 ..

android kotlin androidx
1个回答
0
投票

meals更改为val,并在selected_Restaurant中这样声明时实例化它:

© www.soinside.com 2019 - 2024. All rights reserved.