Я получаю ошибку nullpointerexception в моей программе, но в моем коде нет ошибки. Я не понимаю, где я ошибся. Может кто-нибудь, пожалуйста, проверьте меня? Моя программа работает нормально, пока я не нажимаю кнопку «Просмотр корзины покупок», появляется исключение nullpointer. Заранее спасибо!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
};
});
}
}
Вы уверены, что сможете получить ссылку на btn. – Bennet
* «но в моем коде нет ошибки» * ... ваш компьютер не согласен. –
'Button btn = (кнопка) findViewById (R.id.Checkout);' before setContentView' ошибочно. Посмотрите на нижний ответ, это исправит. – Raghunandan