这是运行日志:
java.lang.NullPointerException:尝试在com.Karbi.chonang.FoodDetail $ 1.onClick上的空对象引用上调用虚拟方法'java.lang.String com.Karbi.chonang.Model.Food.getName()'。 (FoodDetail.java:57)
我的代码:
TextView food_name,food_price,food_description;
ImageView img_food;
CollapsingToolbarLayout collapsingToolbarLayout;
FloatingActionButton btnCart;
ElegantNumberButton numberButton;
String foodId="";
FirebaseDatabase database;
DatabaseReference foods;
Food currentFood;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_detail);
//Firebase
database = FirebaseDatabase.getInstance();
foods= database.getReference("Foods");
//Init view
numberButton = (ElegantNumberButton)findViewById(R.id.number_button);
btnCart = (FloatingActionButton)findViewById(R.id.btnCart);
btnCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Database(getBaseContext()).addToCart(new Order(
foodId,
currentFood.getName(),
numberButton.getNumber(),
currentFood.getPrice(),
currentFood.getDiscount()
));
Toast.makeText(FoodDetail.this, "Added to your Cart", Toast.LENGTH_SHORT).show();
}
});
food_description = (TextView)findViewById(R.id.food_description);
food_name = (TextView)findViewById(R.id.food_name);
food_price = (TextView)findViewById(R.id.food_price);
img_food = (ImageView)findViewById(R.id.img_food);
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.ExpandedAppbar);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapseAppbar);
//Get Food Id from Intent
if (getIntent()!=null)
foodId = getIntent().getStringExtra("FoodId");
if(foodId.isEmpty())
{
getDetailFood(foodId);
}
}
private void getDetailFood(String foodId) {
foods.child(foodId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentFood= dataSnapshot.getValue(Food.class);
//set Image
Picasso.with(getBaseContext()).load(currentFood.getImage())
.into(img_food);
collapsingToolbarLayout.setTitle(currentFood.getName());
food_price.setText(currentFood.getPrice());
food_name.setText(currentFood.getName());
food_description.setText(currentFood.getDescription());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
我检查了构造函数,已经调用了变量,甚至返回了它。