使用SQLite数据库填充MPAndroidChart条形图

时间:2018-07-19 21:41:32

标签: android sqlite mpandroidchart

我有一个MPAndroidChart,我想使用它显示SQL查询的结果,给出我的收入列的总和并按Income_category对其进行分组。这里的另一个用户使我更接近使其工作,但是在执行BarChart.setData时收到空对象引用错误。调试显示了查询的工作原理,所以我不知道为什么它为空。以下是BudgetDbHelper中的代码:

public ArrayList<BarEntry> getBarEntries() {
    String income_sum_column = "income_sum";
    SQLiteDatabase db = this.getReadableDatabase();
    String[] columns = new String[]{"SUM(income) AS " + income_sum_column,"income_category"};
    Cursor csr = db.query("transactions",columns,null,null,"income_category",null,null);
    ArrayList<BarEntry> rv = new ArrayList<>();
    while(csr.moveToNext()) {
        rv.add(new BarEntry(
                csr.getInt(csr.getColumnIndex("income_category")),
                csr.getFloat(csr.getColumnIndex(income_sum_column))
        ));
    }
    csr.close();
    return rv; 

这是CYIncomeChartActivity的代码:

public class CYIncomeChartActivity extends AppCompatActivity {

    SQLiteDatabase sqLiteDatabase;

    // Database helper object //
    private BudgetDbHelper mDbHelper;

    BarChart barChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cy_income_chart);

        mDbHelper = new BudgetDbHelper(this);
        sqLiteDatabase = mDbHelper.getWritableDatabase();

        ArrayList<BarEntry> barEntries = mDbHelper.getBarEntries();

        BarDataSet barDataSet = new BarDataSet(barEntries,"Income By Income Category");
        barDataSet.setColors(ColorTemplate.COLORFUL_COLORS);

        BarData barData = new BarData(barDataSet);
        barData.setBarWidth(0.9f);

        barChart.setData(barData);

    }


}

1 个答案:

答案 0 :(得分:0)

您的问题是barChart = findViewById(R.id.my_chart); 为null,因为您从未将其设置为任何东西。您需要类似

的东西
barChart.setData(barData);

在那儿打电话之前

{{1}}