使用数组时出现 java.lang.NullPointerException 错误

标签 java arrays eclipse nullpointerexception

我已经编写了一些代码,应该允许我获取数据库中列下的所有数据并将其存储在字符串数组中。我将包含信息的字符串数组转换为 double 组。 double 数组中的所有值都加在一起得到一个总值,然后该值显示在 EditText 中。 但是,每当我开始 Activity 时,都会出现一个错误,提示 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;
}

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

最佳答案

改变

return null;

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

getCost() 方法的最后一行。

关于使用数组时出现 java.lang.NullPointerException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10376857/

相关文章:

java - MVC : Property change events for nested models

javascript - 如何将数据转换为字符串

java - 第一个官方 Android 教程崩溃

java - 将现有 Java 项目放入 Github

java - 为什么在 Java 中调试(单步执行)时 https 连接如此慢?

java - 创建排序链表类

java - 将图像分配给字符串

java - 我有一个尝试创建的约会计划应用程序

java - 使用插入排序对数组进行排序

c - 如何在 C 中将文本文件中的字符串存储在数组中