单击按钮时出现NullPointerException

时间:2014-01-05 04:57:21

标签: java android nullpointerexception

我的程序中出现nullpointerexception错误,但我的代码中没有错误。我不明白我错在哪里。有人可以帮我查一下吗?我的程序工作正常,直到我按下“查看购物车”按钮,nullpointerexception出来。提前谢谢!

public class ShoppingCart extends Activity implements OnClickListener{

private List<Product> mCartList;
private ProductAdapter mProductAdapter;

Button btn = (Button) findViewById(R.id.Checkout);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.shoppingcart);

mCartList = ShoppingCartHelper.getCartList();

// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
          mCartList.get(i).selected = false;
    }

// Create the list
final ListView listViewCatalog = 
    (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),true);
listViewCatalog.setAdapter(mProductAdapter);

listViewCatalog.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(), ProductDetails.class);

    productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
            startActivity(productDetailsIntent);
        }
          });
                  }

@Override
protected void onResume() {
    super.onResume();

    // Refresh the data
    if (mProductAdapter != null) {
        mProductAdapter.notifyDataSetChanged();
    }

    double subTotal = 0;
    for (Product p : mCartList) {
        int quantity = ShoppingCartHelper.getProductQuantity(p);
        subTotal += p.price * quantity;
    }

TextView productPriceTextView = (TextView)findViewById(R.id.TextViewSubtotal);
    productPriceTextView.setText("Subtotal: $" + subTotal);
            }

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

        @Override
        public void onClick(View v) {
            myClick(v); /* my method to call new intent or activity */
                }

            public void myClick(View v) {
                Intent intent = new Intent(null, MainActivity.class);
                startActivity(intent);// for calling the activity
            };
        });

    }
            }

1 个答案:

答案 0 :(得分:2)

目前,您在调用setContentView后在类级别而不是在任何方法内初始化Button。这样做:

Button btn;  // declare here 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
   setContentView(R.layout.shoppingcart);
   btn = (Button) findViewById(R.id.Checkout);//<<initialize after setContentView
//...your code
}