提问人:BLADERVAN GAMER 提问时间:5/17/2022 最后编辑:BLADERVAN GAMER 更新时间:5/17/2022 访问量:13580
java.lang.RuntimeException 中的错误:无法启动活动 ComponentInfo{}:java.lang.NullPointerException [重复]
error in java.lang.RuntimeException: Unable to start activity ComponentInfo{}: java.lang.NullPointerException [duplicate]
问:
我在android studio中遇到以下错误,问题是在添加产品时,因为如果没有产品,它会打开购物袋,但是当添加一个并想重新输入它时,它会关闭,当您想输入购物袋购买时,应用程序会关闭。
我真的很想得到您的帮助,因为我不是这个应用程序的专家,而且我没有多少时间交付它,我将附上图像和执行应用程序的错误视频
购物袋适配器
class ShoppingBagAdapter(val context: Activity, val products: ArrayList): 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(产品) } }
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)
}
}
客户ShoppingBagActivity
类 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
}
}
应用程序运行的视频链接,以便您可以查看错误 https://youtu.be/iUNCo5aCLLY
这是一个关于所讨论问题的更明确的视频,我真的希望你能帮助我 https://youtu.be/T262TUQxRVw
现在我将继续附加图像,以便您可以看到错误的完整描述,尽管我也可以在下面看到它们
完整的错误描述
2022-05-16 16:28:46.508 6163-6163/com.blader.domicilios E/Android运行时:致命异常:主 进程:com.blader.domicilios,PID:6163 java.lang.RuntimeException:无法启动活动 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 检查以确保它们不为 null。 总是一个不好的迹象,这意味着“我保证这永远不会为空”,我的猜测是空的,这就是它崩溃的原因。(这就是为什么你应该总是处理空值,除非你绝对知道你在做什么以及为什么需要它,否则永远不要使用)!!
quantity
!!
你可以用这个来修复它:
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
评论
!!
这就是现在错误所在的地方,当我再次尝试添加产品时,应用程序会关闭,我将在这里再次附上屏幕截图,我选择错误标记的位置,以便您可以看到哪一行是向我发送错误的行,一次感谢您的帮助
再次向我发送错误的代码****
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)
}
}
评论
price
null
quantity!!
quantity
if (product.quantity != null)
?:
(product.quantity ?: 0)
评论