访问变量时收到NullPointerException

时间:2013-07-29 08:08:32

标签: android nullpointerexception

我在访问变量时遇到空指针异常。我做了几次相同的代码,它工作正常。但在这里,我无法弄清楚到底出了什么问题。我知道某处有一个简单的故障。谢谢你的帮助!!

继承人代码:

public void getSumsForPie(PieGraph pieGraph)
    {
    Cursor reportSumCursor = ourDatabase.rawQuery("SELECT SUM(total_cost) FROM food_table ", null);
            if(reportSumCursor!=null && reportSumCursor.getCount()>0)
            {
                reportSumCursor.moveToFirst();
                double getTotalFuelCostSum = reportCursor.getDouble(0); // Here the nullPointerException is thrown
                pieGraph.setFoodTotalSum(getTotalFoodCostSum);
            }
}

2 个答案:

答案 0 :(得分:0)

检查if语句中是否为reportCursor != null && pieGraph != null,这样就不会出现空引用异常:

public void getSumsForPie(PieGraph pieGraph)
{
    Cursor reportSumCursor = ourDatabase.rawQuery("SELECT SUM(total_cost) FROM food_table ", null);

    if(reportSumCursor!=null && reportSumCursor.getCount()>0 &&
       reportCursor != null && pieGraph != null)
    {
         reportSumCursor.moveToFirst();
         double getTotalFuelCostSum = reportCursor.getDouble(0); // Here the nullPointerException is thrown
         pieGraph.setFoodTotalSum(getTotalFoodCostSum);
    }
}

答案 1 :(得分:0)

试试这个:

 public void getSumsForPie(PieGraph pieGraph)
{
        SQLiteDatabase db = this.getReadableDatabase();
       Cursor reportSumCursor = db.query("SELECT SUM(total_cost) FROM food_table ", null);
        if(reportSumCursor!=null && reportSumCursor.getCount()!= 0)
        {
            reportSumCursor.moveToFirst();
            double getTotalFuelCostSum = reportSumCursor.getDouble(0);
            pieGraph.setFoodTotalSum(getTotalFoodCostSum);
        }
}