2012-04-29 83 views
1

我已经写了一些代码,它应该允许我获取数据库中某列的所有数据并将其存储在一个字符串数组中。我将包含信息的字符串数组转换为双数组。 double数组中的所有值都会一起添加以获得一个总值,然后将此值显示在EditText中。 但是每当我开始活动时都会出现一个错误,指出java.lang.NullPointerException。使用数组时发生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; 
} 

有谁知道可能是什么问题?谢谢

+2

被返回的东西,我建议通过这个在调试器步进。 –

+0

既然你有投掷NullPointer的线只看线,并尝试了解那一行的哪一部分可能会假设一个现有的对象(大提示 - 调用一个对象上的方法假设对象在那里,并会抛出一个null如果不是的话)。 –

回答

3

变化

return null; 

在您getCost()方法的最后一行

return costarraylist.toArray(new String[costarraylist.size()]); 

+0

啊是的,现在看起来很简单,谢谢大家的帮助,你们都是现场 – Sketzii

1

成员函数public String[] getCost()返回null而不是实际的成本值。 因此,第31行的double[] doubleRunningCosts = new double[RunningCosts.length];将失败,因为RunningCosts为空。

1

getCost方法返回null时候就应该像costarraylist.toArray(new String[0])

相关问题