dawn February 2016

retrieve data from database and show them in bar chart using MPAndroidChart in android

I know how to show the raw data in bar chart using MPAndroidChart but I got problem in real scenario. I have some data in my sqlite database and I want to show them in bar chart. Please give me some reference or simple example.

Database table has two columns month and some numbers. eg: Jan = 200, Feb = 300, etc.

I have searched many but could not find the right one. They were either 2-3 years old or not the type as I mentioned.

Thanks in advance.

Answers


dawn February 2016

Here is the answer to my question. these are two methods to store the x-axis data and y-axis data in arrays.

public ArrayList<String> queryXData(){
    ArrayList<String> xNewData = new ArrayList<String>();
    String query = "SELECT " + DAILY_DATE + " FROM " + TABLE_DAILY_FRAG;
    Cursor cursor = mSQLiteDatabase.rawQuery(query, null);
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        xNewData.add(cursor.getString(cursor.getColumnIndex(DAILY_DATE)));
    }
    cursor.close();
    return xNewData;
}

public ArrayList<Float> queryYData(){
    ArrayList<Float> yNewData = new ArrayList<Float>();
    String query = "SELECT " + DAILY_TOTAL + " FROM " + TABLE_DAILY_FRAG;
    Cursor cursor = mSQLiteDatabase.rawQuery(query, null);
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        yNewData.add(cursor.getFloat(cursor.getColumnIndex(DAILY_TOTAL)));
    }
    cursor.close();
    return yNewData;
}

this is another method to show the barchart. Call this method in your activity.

private void addData(){

    ArrayList<BarEntry> yVals = new ArrayList<BarEntry>();

    for (int i = 0; i < mExpenseDB.queryYData().size(); i++)
        yVals.add(new BarEntry(mExpenseDB.queryYData().get(i), i));

    ArrayList<String> xVals = new ArrayList<String>();
    for(int i = 0; i < mExpenseDB.queryXData().size(); i++)
        xVals.add(mExpenseDB.queryXData().get(i));

    BarDataSet dataSet = new BarDataSet(yVals, "expense values");
    dataSet.setColors(ColorTemplate.COLORFUL_COLORS);

    BarData data = new BarData(xVals, dataSet);


    LimitLine line = new LimitLine(12f, "average daily expense");
    line.setTextSize(12f);
    line.setLineWidth(4f);
    YAxis leftAxis = barChart.getAxisLeft();
    leftAxis.addLimitLine(line);

    barChart.setData(data);
    barChart.setDescription("The expenses chart.");
 

Post Status

Asked in February 2016
Viewed 3,746 times
Voted 6
Answered 1 times

Search




Leave an answer