需要有关此错误日志的帮助。正在尝试创建一个食品配送应用程序,下面是androidstudio上应用程序的源代码。每次我运行应用程序时,应用程序都会不断崩溃
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)
代码:
ordersadapter.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);
}
}
}
2条答案
按热度按时间dy1byipe1#
在适配器中,您将获得名为orderprice的id,但在已定义的xml中,没有定义名为this的id。这就是为什么你会崩溃。您需要将textview6重命名为orderprice,或者您可以将适配器中的orderprice更改为textview6,如下所示
改变这个
为了这个
xxslljrj2#
检查您的textview id,它是错误的,这就是为什么android studio会产生空指针异常,因为您在另一个textview上设置了settext(),而不是这个。