在 Context.getResource 上获取 null 对象引用错误。将自定义适配器用于回收器视图时

Getting null object reference error on Context.getResource. when using a custom adapter for recycler view

提问人:Sanjay Chunduru 提问时间:3/11/2022 最后编辑:Sanjay Chunduru 更新时间:3/12/2022 访问量:134

问:

每当我启动购物车活动时,我都会收到此错误。我制作了客户订单的回收商视图,自从我添加了一个按钮以允许用户从购物车中删除商品并尝试使用新的弹出窗口将此按钮添加到适配器中以来(context,holder.buttonViewOption),我收到此错误: 这是完整的错误消息

E/AndroidRuntime:致命异常:main 进程:com.example.rotekapp,PID:22120 java.lang.NullPointerException:尝试调用虚拟方法“android.content.res.Resources android.content.Context.getResources()” 在 null 对象引用上 位于 com.android.internal.view.menu.MenuBuilder。(MenuBuilder.java:200) 在 android.widget.PopupMenu。(弹出菜单.java:103) 在 android.widget.PopupMenu。(弹出菜单.java:78) 在 android.widget.PopupMenu。(弹出菜单.java:63) 在 com.example.rotekapp.CartAdapter.onBindViewHolder(CartAdapter.java:69) 在 com.example.rotekapp.CartAdapter.onBindViewHolder(CartAdapter.java:29) 在 androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7254) 在 androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7337) 在 androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6194) 在 androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6460) 在 androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6300) 在 androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6296) 在 androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2330) 在 androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1631) 在androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1591) 在 androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:668) 在 androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4309) 在 androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3686) 在 android.view.View.measure(View.java:24530) 在 androidx.constraintlayout.widget.ConstraintLayout$Measurer.measure(ConstraintLayout.java:811) 在 androidx.constraintlayout.core.widgets.analyzer.BasicMeasure.measure(BasicMeasure.java:466) 在 androidx.constraintlayout.core.widgets.analyzer.BasicMeasure.measureChildren(BasicMeasure.java:134) 在 androidx.constraintlayout.core.widgets.analyzer.BasicMeasure.solverMeasure(BasicMeasure.java:278) 在 androidx.constraintlayout.core.widgets.ConstraintWidgetContainer.measure(ConstraintWidgetContainer.java:120) 在 androidx.constraintlayout.widget.ConstraintLayout.resolveSystem(ConstraintLayout.java:1594) 在 androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1708) 在 android.view.View.measure(View.java:24530) 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828) 在 android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 在androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:145) 在 android.view.View.measure(View.java:24530) 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828) 在 android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552) 在 android.widget.LinearLayout.measureVertical(LinearLayout.java:842) 在android.widget.LinearLayout.onMeasure(LinearLayout.java:721) 在 android.view.View.measure(View.java:24530) 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828) 在 android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 在 android.view.View.measure(View.java:24530) 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828) 在 android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552) 在 android.widget.LinearLayout.measureVertical(LinearLayout.java:842) 在android.widget.LinearLayout.onMeasure(LinearLayout.java:721) 在 android.view.View.measure(View.java:24530) 在 android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6828) 在 android.widget.FrameLayout.onMeasure(FrameLayout.java:194) 在 com.android.internal.policy.DecorView.onMeasure(DecorView.java:742) 在 android.view.View.measure(View.java:24530) E/AndroidRuntime: 在 android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3006) 在 android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1833) 在 android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2122) 在 android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721) 在 android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7598) 在android.view.Choreographer$CallbackRecord.run(Choreographer.java:966) 在 android.view.Choreographer.doCallbacks(Choreographer.java:790) 在android.view.Choreographer.doFrame(Choreographer.java:725) 在 android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951) 在 android.os.Handler.handleCallback(Handler.java:883) 在 android.os.Handler.dispatchMessage(Handler.java:100) 在android.os.Looper.loop(Looper.java:214) 在 android.app.ActivityThread.main(ActivityThread.java:7356) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

任何帮助都是值得赞赏的! 我的适配器类:

public class CartAdapter extends RecyclerView.Adapter<CartAdapter.CartViewHolder> {

Context context;
ArrayList<CartItemsModel> list;
private SelectListener listener;
private Context mCtx;

public CartAdapter(Context context, ArrayList<CartItemsModel> list, SelectListener listener) {
    this.context = context;
    this.list = list;
    this.listener = listener;
}



@NonNull
@Override
public CartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.cart_items,parent,false);
    return new CartViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull CartViewHolder holder, int position) {
    CartItemsModel cartItemsModel = list.get(position);
    int tPrice = cartItemsModel.getTotalPrice();
    String tPriceMod = String.valueOf(tPrice);
    holder.TotalQuantity.setText(cartItemsModel.getTotalQuantity());
    holder.TotalPrice.setText(String.valueOf(cartItemsModel.getTotalPrice()));
    holder.ProductPrice.setText(cartItemsModel.getProductPrice());
    holder.ProductName.setText(cartItemsModel.getProductName());
    holder.ProductID.setText(cartItemsModel.getProductID());
    holder.CurrentDate.setText(tPriceMod);
    holder.CurrentTime.setText(cartItemsModel.getCurrentTime());
    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            listener.onItemClicked(list.get(position));
        }
    });
    PopupMenu popup = new PopupMenu(context, holder.buttonViewOption); <-- Error is here
    popup.inflate(R.menu.options_menu);
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.menu1:
                    DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("Orders");
                    FirebaseAuth auth = FirebaseAuth.getInstance();
                    String username = getUser(auth.getCurrentUser().getEmail());
                    Query productIDQuery = database.child(username).orderByChild("ProductID").equalTo(cartItemsModel.getProductID());
                    productIDQuery.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            for (DataSnapshot productIDsnapshot : snapshot.getChildren()) {
                                productIDsnapshot.getRef().removeValue();
                                Toast.makeText(context, "Removed from cart", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {
                            Toast.makeText(context, "error: " + error, Toast.LENGTH_SHORT).show();

                        }
                    });
                    break;
                case R.id.menu2:
                    Toast.makeText(context, "Quantity: " + cartItemsModel.getTotalQuantity(), Toast.LENGTH_SHORT).show();
                    break;
            }
            return false;
        }
    });




}

private String getUser(String FullUserName) {
    String fullUserName = FullUserName;
    String firstChar = fullUserName.substring(0);
    int firstCharPos = fullUserName.lastIndexOf(firstChar);
    int atsyPos = fullUserName.indexOf("@");
    String realUserName = fullUserName.substring(firstCharPos, atsyPos);
    return realUserName;
}

@Override
public int getItemCount() {
    return list.size();
}

public static class CartViewHolder extends RecyclerView.ViewHolder{
    TextView CurrentDate,CurrentTime,ProductID,ProductName,ProductPrice,TotalPrice,TotalQuantity;
    public CardView cardView;
    public TextView buttonViewOption;


    public CartViewHolder(@NonNull View itemView) {
        super(itemView);

        CurrentDate = itemView.findViewById(R.id.cart_items_date);
        CurrentTime = itemView.findViewById(R.id.cart_items_time);
        ProductID = itemView.findViewById(R.id.cart_items_id);
        ProductName = itemView.findViewById(R.id.cart_items_name);
        ProductPrice = itemView.findViewById(R.id.cart_items_price);
        TotalPrice = itemView.findViewById(R.id.cart_items_tot_price);
        TotalQuantity = itemView.findViewById(R.id.cart_items_qty);
        cardView = itemView.findViewById(R.id.cart_container);
        buttonViewOption = itemView.findViewById(R.id.textViewOptions);
    }
}




}

任何帮助都是值得赞赏的!

android-studio android-recyclerview nullPointerException 适配器

评论


答:

0赞 Teresita Ferme 3/12/2022 #1

您收到的错误来自 MenuBuilder。显然,您在适配器构造函数中收到的上下文尚未初始化。您确定在初始化适配器时发送了正确的上下文吗?

最好用小写形式命名变量。

评论

0赞 Sanjay Chunduru 3/12/2022
感谢您的回答!下面是初始化适配器的类的 pastebin - pastebin.com/Y6RUkff6