嘿伙计们我是java的初学者(整理),我遇到了麻烦。我试图通过Finances类中的变量来获取我在Budget类中设置的日期,但我不断获得NullPointerException
。
我尝试在财务类中使用dueDate
变量,但即使在我实例化之后,logCat仍然会声明它a null object reference
。
public class Budget {
private Date mDate = new Date();
public static double budgetAmount;
private static Budget instance = new Budget();
private Budget(){
}
public double getBudget(){
return budgetAmount;
}
public void setBudget(double budget){
budgetAmount = budget;
}
public static Budget getInstance(){
return instance;
}
public Date getDate() {
return mDate;
}
public void setDate(Date date) {
mDate = date;
}
}
这是财务类
public class Finances extends Activity{
int amtFood; int amtCar; int amtGas; int amtTvBill; int amtInBill;
int amtTronics; int amtWear; int amtLight; int amtWater; int amtOthers;
Date nowDate;
Date dueDate = new Date();
double MainAmount = Budget.budgetAmount;
static int SpentAmount;
Budget budgetDate;
public Finances(){
HashMap<String,Integer> amtAdd = ExpenditureLab.get(this).getExpendMap();
int food= amtAdd.get("Groceries/Food");
int car = amtAdd.get("Car servicing");
int gas = amtAdd.get("Gas Money");
int tvBill = amtAdd.get("Television Bill");
int inBill = amtAdd.get("Internet Bill");
int tronics = amtAdd.get("Electronics");
int wear = amtAdd.get("Clothes/Wearables");
int light = amtAdd.get("Light Bill");
int water = amtAdd.get("Water Bill");
int others = amtAdd.get("Others");
dueDate = budgetDate.getDate();
}
public void addSpent(int amt){
SpentAmount += amt;
}
}
答案 0 :(得分:1)
budgetDate永远不会被启动。
Budget budgetDate; #=> this is null
然后尝试在null对象上调用getDate()。
dueDate = budgetDate.getDate(); #=> causing your nullPointerException?
因此,您需要首先实例化您的budgetDate对象。
Budget budgetDate = new Budget();
然后设置mDate对象
budgetDate.setDate(someDate); #=> someDate is a Date object
之前打电话
dueDate = budgetDate.getDate();
答案 1 :(得分:1)
是budgetDate未初始化,导致空指针异常。 另外,不要在Activity中使用构造函数,您可以在Activity的onCreate方法中进行所有初始化。
答案 2 :(得分:0)
dueDate
不是空对象,您将其设置为budgetDate.getDate()
,而budgetDate
尚未实例化。
答案 3 :(得分:0)
我没有看到您为budgetDate
分配值的地方(永远不会被启动)。调用dueDate = budgetDate.getDate();
解决方案:
将budgetDate = new Budget()
放在dueDate = budgetDate.getDate();
之前:
@Override
public void onCreate(Bundle bundle) {
HashMap<String,Integer> amtAdd = ExpenditureLab.get(this).getExpendMap();
int food= amtAdd.get("Groceries/Food");
int car = amtAdd.get("Car servicing");
int gas = amtAdd.get("Gas Money");
int tvBill = amtAdd.get("Television Bill");
int inBill = amtAdd.get("Internet Bill");
int tronics = amtAdd.get("Electronics");
int wear = amtAdd.get("Clothes/Wearables");
int light = amtAdd.get("Light Bill");
int water = amtAdd.get("Water Bill");
int others = amtAdd.get("Others");
budgetDate = new Budget();
dueDate = budgetDate.getDate();
}