我编写了一些代码,这些代码应该允许我获取数据库中列下的所有数据并将其存储在字符串数组中。我将包含信息的字符串数组转换为双数组。 double数组中的所有值都加在一起得到一个总值,然后在EditText中显示该值。 但是,每当我启动活动时,都会出现一个错误,说java.lang.NullPointerException。
这是数组的代码:
DatabaseTotalEntries getAllData = new DatabaseTotalEntries(this); //Creates a new method in the database class
getAllData.open();
String[] RunningCosts = getAllData.getCost(); //Transfers all the data under the Total Running Costs column into a String Array
String[] RunningTimes = getAllData.getTime();
String[] EnergyUsages = getAllData.getEnergy();
getAllData.close();
double[] doubleRunningCosts = new double[RunningCosts.length];
for(int i=0; i<RunningCosts.length; i++)
{
doubleRunningCosts[i] = Double.parseDouble(RunningCosts[i]);
} // Converts the string array 'RunningCosts' into a double array
double TotalCost = 0;
for (int in = 0; in <doubleRunningCosts.length; in++)
TotalCost += doubleRunningCosts[in]; //Adds the values in the double string array together to get one total value
DecimalFormat decf = new DecimalFormat("##");
totalCostBox.setText(decf.format(TotalCost)); //Sets the variable 'TotalCost' to appear in the totalCostBox edit text
LogCat表示事件发生在第31行,即
double[] doubleRunningCosts = new double[RunningCosts.length];
这是我在我的数据库中使用的getData方法:
public String[] getCost() {
// TODO Auto-generated method stub
ArrayList<String> costarraylist = new ArrayList<String>();
String[] applianceCostcolumns = new String[] { KEY_TOTAL_COST };
Cursor costcursor = allDatabase.query(DATABASE_TABLE, applianceCostcolumns, null, null, null, null, null);
String result;
int iApplianceCost = costcursor.getColumnIndex(KEY_TOTAL_COST);
for (costcursor.moveToFirst(); !costcursor.isAfterLast(); costcursor
.moveToNext()) {
result = costcursor.getString(iApplianceCost);
costarraylist.add(result);
};
return null;
}
有谁知道可能是什么问题?感谢
答案 0 :(得分:3)
更改
return null;
到
return costarraylist.toArray(new String[costarraylist.size()]);
在getCost()
方法的最后一行。
答案 1 :(得分:1)
成员函数public String[] getCost()
返回null而不是实际成本值。
因此,第31行的double[] doubleRunningCosts = new double[RunningCosts.length];
将失败,因为RunningCosts为空。
答案 2 :(得分:1)
getCost
方法返回null
时应该返回costarraylist.toArray(new String[0])