列表视图适配器onclick方法在oncreate中使用

时间:2017-10-02 08:27:44

标签: android nullpointerexception

我的主要活动

   public void removefunction(){
    List<CartItem> cartItems = getCartItems(cart);
    cart.remove(cartItems.get(position).getProduct());
    cartItems.remove(position);
    cartItemAdapter.updateCartItems(getCartItems(cart));
    cartItemAdapter.notifyDataSetChanged();
    tvTotalPrice.setText(Constant.CURRENCY+String.valueOf(cart.getTotalPrice().setScale(2, BigDecimal.ROUND_HALF_UP)));
}

适配器代码

 btnremove= (Button) convertView.findViewById(R.id.btnrem);

    btnremove.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ((ShoppingCartActivity) context).removefunction();


        }
    });

导致tvTotalPrice.setText中的空指针异常

  

致命的例外:主要                                                                             处理:com.android.tonyvu.sc.demo,PID:7601                                                                             java.lang.NullPointerException:尝试调用虚方法&#39; void   android.widget.TextView.setText(java.lang.CharSequence中)&#39;在null   对象参考   com.android.tonyvu.sc.demo.ShoppingCartActivity.removefunction(ShoppingCartActivity.java:263)                                                                                 在   com.android.tonyvu.sc.demo.adapter.CartItemAdapter $ 1.onClick(CartItemAdapter.java:98)                                                                                 在android.view.View.performClick(View.java:6205)                                                                                 在android.widget.TextView.performClick(TextView.java:11103)

1 个答案:

答案 0 :(得分:0)

ButtonClick事件没问题,因为您的方法触发了setText方法。问题是你的tvTotalPrice-Textview没有设置(或设置错误),这就是为什么它是null。这就是你得到NullPointerException的原因。