java.lang.RuntimeException 中的错误:无法启动 activity ComponentInfo{}:java.lang.NullPointerException

error in java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.NullPointerException

我在 android studio 中出现以下错误,问题是在添加产品时,因为如果没有产品,它会打开购物袋,但在添加一个并想重新输入时,它关闭,当您想进入购物袋购买时,应用程序关闭。

我真的很想得到你的帮助,因为我不是这个应用程序的专家,我也没有时间交付它,我将附上执行应用程序时出错的图片和视频

购物袋适配器

class ShoppingBagAdapter(val context: Activity, val products: ArrayList): RecyclerView.Adapter() {

val sharedPref = SharedPref(context)
val TAG = "ShoppingBag"


init {
    (context as ClientShoppingBagActivity).setTotal(getTotal())
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingBagViewHolder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_shopping_bag, parent, false)
    return ShoppingBagViewHolder(view)
}

override fun getItemCount(): Int {
    return products.size
}


override fun onBindViewHolder(holder: ShoppingBagViewHolder, position: Int) {

    val product = products[position] // CADA UNA DE LAS CATEGORIAS

    holder.textViewName.text = product.name
    holder.textViewCounter.text = "${product.quantity}"
    holder.textViewPrice.text = "${product.price * product.quantity!!}"
    Glide.with(context).load(product.image1).into(holder.imageViewProduct)

    holder.imageViewAdd.setOnClickListener { addItem(product, holder) }
    holder.imageViewRemove.setOnClickListener { removeItem(product, holder) }
    holder.imageViewDelete.setOnClickListener { deleteItem(position) }

// holder.itemView.setOnClickListener { goToDetail(产品) } }

private fun getTotal(): Double {
    var total = 0.0

    for (p in products) {
        total = total + (p.quantity!! * p.price)
    }
    return total
}

private fun getIndexOf(idProduct: String): Int {
    var pos = 0

    for (p in products) {
        if (p.id == idProduct) {
            return pos
        }
        pos++
    }

    return -1
}

private fun deleteItem(position: Int) {
    products.removeAt(position)
    notifyItemRemoved(position)
    notifyItemRangeRemoved(position, products.size)
    sharedPref.save("order", products)
    (context as ClientShoppingBagActivity).setTotal(getTotal())
}


private fun addItem(product: Product, holder: ShoppingBagViewHolder) {

    val index = getIndexOf(product.id!!)
    product.quantity = product.quantity!! + 1
    products[index].quantity = product.quantity

    holder.textViewCounter.text = "${product.quantity}"
    holder.textViewPrice.text = "${product.quantity!! * product.price}$"

    sharedPref.save("order", products)
    (context as ClientShoppingBagActivity).setTotal(getTotal())
}

private fun removeItem(product: Product, holder: ShoppingBagViewHolder) {

    if (product.quantity!! > 1) {

        val index = getIndexOf(product.id!!)
        product.quantity = product.quantity!! - 1
        products[index].quantity = product.quantity

        holder.textViewCounter.text = "${product.quantity}"
        holder.textViewPrice.text = "${product.quantity!! * product.price}$"

        sharedPref.save("order", products)
        (context as ClientShoppingBagActivity).setTotal(getTotal())

    }

}

private fun goToDetail(product: Product) {
    val i = Intent(context, ClientProductsDetailActivity::class.java)
    i.putExtra("product", product.toJson())
    context.startActivity(i)
}

class ShoppingBagViewHolder(view: View): RecyclerView.ViewHolder(view) {

    val textViewName: TextView
    val textViewPrice: TextView
    val textViewCounter: TextView
    val imageViewProduct: ImageView
    val imageViewAdd: ImageView
    val imageViewRemove: ImageView
    val imageViewDelete: ImageView

    init {
        textViewName = view.findViewById(R.id.textview_name)
        textViewPrice = view.findViewById(R.id.textview_price)
        textViewCounter = view.findViewById(R.id.textview_counter)
        imageViewProduct = view.findViewById(R.id.imageview_product)
        imageViewAdd = view.findViewById(R.id.imageview_add)
        imageViewRemove = view.findViewById(R.id.imageview_remove)
        imageViewDelete = view.findViewById(R.id.imageview_delete)
    }

}

ClientShoppingBagActivity

class ClientShoppingBagActivity : AppCompatActivity() {

var recyclerViewShoppingBag:  RecyclerView? = null
var textViewTotal: TextView? = null
var buttomNext: Button? = null
var toolbar: Toolbar? = null


var adapter: ShoppingBagAdapter? = null
var sharedPref: SharedPref? = null
var gson = Gson()
var selectedProducts = ArrayList<Product>()

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

    sharedPref = SharedPref(this)

    recyclerViewShoppingBag = findViewById(R.id.recyclerview_shopping_bag)
    textViewTotal = findViewById(R.id.textview_total)
    buttomNext = findViewById(R.id.btn_next)
    toolbar = findViewById(R.id.toolbar)
    toolbar?.setTitleTextColor(ContextCompat.getColor(this, R.color.white))
    toolbar?.title = "Tu orden"

    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayHomeAsUpEnabled(true)

    recyclerViewShoppingBag?.layoutManager = LinearLayoutManager(this)

    getProductsFromSharedPref()

    buttomNext?.setOnClickListener{goToAddressList() }

}

private fun goToAddressList(){
    val i = Intent(this, ClientAddressListActivity::class.java)
    startActivity(i)
}

fun setTotal(total: Double){
    textViewTotal?.text = "${total}$"
}

private fun getProductsFromSharedPref() {

    if (!sharedPref?.getData("order").isNullOrBlank()) { // EXISTE UNA ORDEN EN SHARED PREF
        val type = object : TypeToken<ArrayList<Product>>() {}.type
        selectedProducts = gson.fromJson(sharedPref?.getData("order"), type)

        adapter = ShoppingBagAdapter(this, selectedProducts)
        recyclerViewShoppingBag?.adapter = adapter
    }
}

link 视频 其中应用是运行 所以你可以看到错误在哪里 https://youtu.be/iUNCo5aCLLY

这里有一个更明确的视频关于问题的问题,我真的希望你可以帮助我https://youtu.be/T262TUQxRVw

现在我将继续附上图片,这样你就可以看到错误的完整描述,尽管我也可以在下面看到它们

image 1 where is the complete error

in this image I specify the error line

in this image I specify the other line of the error

in this image I specify the other line of the error

in this image I specify the other line of the error

完整的错误描述

2022-05-16 16:28:46.508 6163-6163/com.blader.domicilios E/AndroidRuntime:致命异常:main 进程:com.blader.domicilios,PID:6163 java.lang.RuntimeException: 无法启动 activity ComponentInfo{com.blader.domicilios/com.blader.domicilios.activities.client.shopping_bag.ClientShoppingBagActivity}: java.lang.NullPointerException 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:223) 在 android.app.ActivityThread.main(ActivityThread.java:7656) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 原因:java.lang.NullPointerException 在 com.blader.domicilios.adapters.ShoppingBagAdapter.getTotal(ShoppingBagAdapter.kt:57) 在 com.blader.domicilios.adapters.ShoppingBagAdapter.(ShoppingBagAdapter.kt:25) 在 com.blader.domicilios.activities.client.shopping_bag.ClientShoppingBagActivity.getProductsFromSharedPref(ClientShoppingBagActivity.kt:73) 在 com.blader.domicilios.activities.client.shopping_bag.ClientShoppingBagActivity.onCreate(ClientShoppingBagActivity.kt:52) 在 android.app.Activity.performCreate(Activity.java:8000) 在 android.app.Activity.performCreate(Activity.java:7984) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:223) 在 android.app.ActivityThread.main(ActivityThread.java:7656) 在 java.lang.reflect.Method.invoke(本机方法)


我真的很担心你不能帮我能按时交作业,我的时间真的很少**

您还没有发布完整的堆栈跟踪,所以我只是猜测,但我认为是这一行:

total = total + (p.quantity!! * p.price)

quantity 是可以为 null 的类型,您应该 null-check 那些以确保它们 not null 在你做任何事情之前他们。 !! 始终是一个不好的迹象,它的意思是“我保证这永远不会为空”,我的猜测是 quantity is null 这就是它崩溃的原因。 (这就是为什么你应该始终处理空值并且永远不要使用 !! 除非你完全知道你在做什么以及为什么需要它)

你或许可以用这个来解决它:

private fun getTotal(): Double {
    var total = 0.0

    for (p in products) {
        if (p.quantity != null) total += p.quantity * p.price
    }
    return total
}

或者如果您愿意:

private fun getTotal(): Double =
    products.sumByDouble { p -> (p.quantity ?: 0) * p.price }

我不知道你的应用程序是否明显存在任何其他问题,但希望这应该能阻止你获得特定的 NullPointerException

这是现在的错误所在,当我再次尝试添加产品时应用程序关闭,我会再次附上截图 here I select where the error marks, so that you can see which is the line that sends me the error, once thanks for helping me

enter image description here

再次向我发送错误的代码****

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.blader.domicilios.R
import com.blader.domicilios.activities.client.products.detail.ClientProductsDetailActivity
import com.blader.domicilios.activities.client.shopping_bag.ClientShoppingBagActivity
import com.blader.domicilios.models.Product
import com.blader.domicilios.utils.SharedPref
import com.bumptech.glide.Glide

class ShoppingBagAdapter(val context: Activity, val products: ArrayList<Product>): RecyclerView.Adapter<ShoppingBagAdapter.ShoppingBagViewHolder>() {

    val sharedPref = SharedPref(context)
    val TAG = "ShoppingBag"


    init {
        (context as ClientShoppingBagActivity).setTotal(getTotal())
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShoppingBagViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cardview_shopping_bag, parent, false)
        return ShoppingBagViewHolder(view)
    }

    override fun getItemCount(): Int {
        return products.size
    }


    override fun onBindViewHolder(holder: ShoppingBagViewHolder, position: Int) {

        val product = products[position] // CADA UNA DE LAS CATEGORIAS

        holder.textViewName.text = product.name
        holder.textViewCounter.text = "${product.quantity}"
        holder.textViewPrice.text = "${product.price * product.quantity!!}"
        Glide.with(context).load(product.image1).into(holder.imageViewProduct)

        holder.imageViewAdd.setOnClickListener { addItem(product, holder) }
        holder.imageViewRemove.setOnClickListener { removeItem(product, holder) }
        holder.imageViewDelete.setOnClickListener { deleteItem(position) }
//        holder.itemView.setOnClickListener { goToDetail(product) }
    }

    private fun getTotal(): Double =
        products.sumByDouble { p -> (p.quantity ?: 0) * p.price }

    private fun getIndexOf(idProduct: String): Int {
        var pos = 0

        for (p in products) {
            if (p.id == idProduct) {
                return pos
            }
            pos++
        }

        return -1
    }

    private fun deleteItem(position: Int) {
        products.removeAt(position)
        notifyItemRemoved(position)
        notifyItemRangeRemoved(position, products.size)
        sharedPref.save("order", products)
        (context as ClientShoppingBagActivity).setTotal(getTotal())
    }


    private fun addItem(product: Product, holder: ShoppingBagViewHolder) {

        val index = getIndexOf(product.id!!)
        product.quantity = product.quantity!! + 1
        products[index].quantity = product.quantity

        holder.textViewCounter.text = "${product.quantity}"
        holder.textViewPrice.text = "${product.quantity!! * product.price}$"

        sharedPref.save("order", products)
        (context as ClientShoppingBagActivity).setTotal(getTotal())
    }

    private fun removeItem(product: Product, holder: ShoppingBagViewHolder) {

        if (product.quantity!! > 1) {

            val index = getIndexOf(product.id!!)
            product.quantity = product.quantity!! - 1
            products[index].quantity = product.quantity

            holder.textViewCounter.text = "${product.quantity}"
            holder.textViewPrice.text = "${product.quantity!! * product.price}$"

            sharedPref.save("order", products)
            (context as ClientShoppingBagActivity).setTotal(getTotal())

        }

    }

    private fun goToDetail(product: Product) {
        val i = Intent(context, ClientProductsDetailActivity::class.java)
        i.putExtra("product", product.toJson())
        context.startActivity(i)
    }

    class ShoppingBagViewHolder(view: View): RecyclerView.ViewHolder(view) {

        val textViewName: TextView
        val textViewPrice: TextView
        val textViewCounter: TextView
        val imageViewProduct: ImageView
        val imageViewAdd: ImageView
        val imageViewRemove: ImageView
        val imageViewDelete: ImageView

        init {
            textViewName = view.findViewById(R.id.textview_name)
            textViewPrice = view.findViewById(R.id.textview_price)
            textViewCounter = view.findViewById(R.id.textview_counter)
            imageViewProduct = view.findViewById(R.id.imageview_product)
            imageViewAdd = view.findViewById(R.id.imageview_add)
            imageViewRemove = view.findViewById(R.id.imageview_remove)
            imageViewDelete = view.findViewById(R.id.imageview_delete)
        }

    }