简体   繁体   中英

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. 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

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. 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

change this

 price = itemView.findViewById(R.id.orderPrice);

to this

 price = itemView.findViewById(R.id.textView6);

检查你的 textView id 它是错误的,这就是为什么 android studio 产生空指针异常因为你 setText() 在另一个 textView 而不是这个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM