[英]java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference. App crashes on run
Need help with this error log.需要有关此错误日志的帮助。 Trying to create a food delivery app and here is the source code of said application on Android Studio.
尝试创建一个送餐应用程序,这是 Android Studio 上所述应用程序的源代码。 The application keep on crashing every time I run the application.:
每次运行该应用程序时,该应用程序都会崩溃。:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.swiftbites.Adapters.OrdersAdapter.onBindViewHolder(OrdersAdapter.java:43)
at com.example.swiftbites.Adapters.OrdersAdapter.onBindViewHolder(OrdersAdapter.java:19)
Codes:代码:
OrdersAdapter.java订单适配器.java
package com.example.swiftbites.Adapters;
import ...
public class OrdersAdapter extends RecyclerView.Adapter<OrdersAdapter.viewHolder>{
ArrayList<OrdersModel> list;
Context context;
public OrdersAdapter(ArrayList<OrdersModel> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.order_sample, parent, false);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull viewHolder holder, int position) {
final OrdersModel model = list.get(position);
holder.orderImage.setImageResource(model.getOrderImage());
holder.soldItemName.setText(model.getSoldItemName());
holder.orderNumber.setText(model.getOrderNumber());
holder.price.setText(model.getPrice());
}
@Override
public int getItemCount() {
return list.size();
}
public class viewHolder extends RecyclerView.ViewHolder {
ImageView orderImage;
TextView soldItemName, orderNumber, price;
public viewHolder(@NonNull View itemView) {
super(itemView);
orderImage = itemView.findViewById(R.id.orderImage);
soldItemName = itemView.findViewById(R.id.orderItemName);
orderNumber = itemView.findViewById(R.id.orderNumber);
price = itemView.findViewById(R.id.orderPrice);
}
}
}
In your adapter you are getting id named orderPrice but in defined xml, there is no id defined named as this.在您的适配器中,您将获得名为orderPrice 的id,但在定义的 xml 中,没有定义为 this 的 id。 This is why you are getting crash.
这就是你崩溃的原因。 You need to rename textView6 to orderPrice or you can change orderPrice in adapter to textView6 as below
您需要textView6重命名为orderPrice也可以在适配器改变orderPrice到textView6如下
change this改变这个
price = itemView.findViewById(R.id.orderPrice);
to this对此
price = itemView.findViewById(R.id.textView6);
检查你的 textView id 它是错误的,这就是为什么 android studio 产生空指针异常因为你 setText() 在另一个 textView 而不是这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.