android Kotlin应用程序在按下按钮后崩溃,并出现NullPointerException

3htmauhk  于 2023-06-20  发布在  Android
关注(0)|答案(1)|浏览(140)

我正在Android Studio中制作一个Kotlin应用程序,我可以像列表一样添加食物及其卡路里值。
它的工作原理是,两个EditText组件,“etName”和“etCalories”,将被传递到一个列表中,然后RecyclerView中的TextView应该显示它们。
问题是,如果我按下按钮添加项目,应用程序会崩溃。
这是logcat

FATAL EXCEPTION: main
    Process: com.example.bbar, PID: 25930
    java.lang.NullPointerException
        at com.example.bbar.ui.home.FoodlistadapterKt.getBinding(foodlistadapter.kt:16)
        at com.example.bbar.ui.home.FoodlistadapterKt.access$getBinding(foodlistadapter.kt:1)
        at com.example.bbar.ui.home.Foodlistadapter.onBindViewHolder(foodlistadapter.kt:57)
        at com.example.bbar.ui.home.Foodlistadapter.onBindViewHolder(foodlistadapter.kt:18)

这是密码

foodlistadapter.kt

package com.example.bbar.ui.home

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.bbar.R
import android.graphics.Paint.STRIKE_THRU_TEXT_FLAG
import android.widget.TextView
import com.example.bbar.databinding.FooditemBinding

@SuppressLint("StaticFieldLeak")
private var _binding: FooditemBinding? = null
private val binding get() =  _binding!!

class Foodlistadapter(

    private val foods: MutableList<food>
) : RecyclerView.Adapter<Foodlistadapter.foodlistviewholder>() {

    class foodlistviewholder(itemView: View) : RecyclerView.ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): foodlistviewholder {
        return foodlistviewholder(
            LayoutInflater.from(parent.context).inflate(
                R.layout.fragment_home,
                parent,
                false
            )
        )
    }

     fun addFood(food: food) {
        foods.add(food)
        notifyItemInserted(foods.size - 1)
    }

     fun deleteFood() {
        foods.removeAll { foods -> foods.isChecked }
        notifyDataSetChanged()

    }

    private fun toggleStrikeThrough(tvFood: TextView, isChecked: Boolean) {
        if (isChecked) {
            tvFood.paintFlags = tvFood.paintFlags or STRIKE_THRU_TEXT_FLAG
        } else {
            tvFood.paintFlags = tvFood.paintFlags or STRIKE_THRU_TEXT_FLAG.inv()
        }
    }

    override fun onBindViewHolder(holder: foodlistviewholder, position: Int) {
        val currentFood = foods[position]
        holder.itemView.apply {
            binding.tvFood.text = currentFood.name
            binding.tvCalories.text= currentFood.calories.toString()
            binding.cbDelete.isChecked = currentFood.isChecked
            toggleStrikeThrough(binding.tvFood, currentFood.isChecked)
            binding.cbDelete.setOnCheckedChangeListener { _, isChecked ->
                toggleStrikeThrough(binding.tvFood, isChecked)
                currentFood.isChecked = !currentFood.isChecked
            }
        }
    }

    override fun getItemCount(): Int {
        return foods.size
    }
}
package com.example.bbar.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.bbar.R

import com.example.bbar.databinding.FragmentHomeBinding


class HomeFragment : Fragment() {

    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    private lateinit var foodlistadapter: Foodlistadapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)

        return binding!!.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        foodlistadapter = Foodlistadapter(mutableListOf())
        binding.rvFoodItems.adapter = foodlistadapter
        binding.rvFoodItems.layoutManager = LinearLayoutManager(activity)

        binding.bSubmit.setOnClickListener{
            val foodTitle= binding.etName.text.toString()
            val foodCalories = binding.etCalories.text.toString()
            if (foodTitle.isNotEmpty()){
                val food= food(foodTitle, foodCalories.toInt(), false )
                foodlistadapter.addFood(food)
                binding.etName.text.clear()
                binding.etCalories.text.clear()
            }
        }
        binding.bDelete.setOnClickListener{
            foodlistadapter.deleteFood()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}

摘要:试图添加食物与其尊重的卡路里值与一个按钮,但程序崩溃。

ohtdti5x

ohtdti5x1#

你的binding是空的,而且它没有被正确使用。
首先,删除类外部的声明,即:

@SuppressLint("StaticFieldLeak")
private var _binding: FooditemBinding? = null
private val binding get() =  _binding!!

ViewHolder实现更改为:

class FoodListViewHolder(val binding: FooditemBinding) : RecyclerView.ViewHolder(binding.root)

onCreateViewHolder中膨胀绑定:

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodListViewHolder {
    val inflater = LayoutInflater.from(parent.context)
    return FoodListViewHolder(FooditemBinding.inflate(inflater, parent, false))
}

使用onBindViewHolder中的绑定:

override fun onBindViewHolder(holder: FoodListViewHolder, position: Int) {
    val currentFood = foods[position]

    holder.binding.apply {
        tvFood.text = currentFood.name
        tvCalories.text= currentFood.calories.toString()
        cbDelete.isChecked = currentFood.isChecked
        toggleStrikeThrough(tvFood, isChecked)
        cbDelete.setOnCheckedChangeListener { _, isChecked ->
            toggleStrikeThrough(tvFood, isChecked)
            currentFood.isChecked = !currentFood.isChecked
        }
    }
}

相关问题