0

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

继承人的代码:

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);
            }
}
4

2 回答 2

0

检查reportCursor != null && pieGraph != null你的 if 语句,这样你就不会得到空引用异常:

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);
    }
}
于 2013-07-29T08:11:10.430 回答
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);
        }
}
于 2013-07-29T08:16:01.677 回答