-3
我在程序中出現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
};
});
}
}
你確定你能夠得到btn的參考。 – Bennet
*「但我的代碼中沒有錯誤」* ...您的計算機不同意。 –
'Button btn =(Button)findViewById(R.id.Checkout);'setContentView'錯誤之前。看下面的答案會解決它。 – Raghunandan