Charm Geld
Charm Geld

Reputation: 191

Android - MPAndroidChart LineChart, not able to plot according to value date

I am using MPAndroidChart for my line chart. I have date values and score values.
Example: on 11/10/2016 my score was 45.

I am struggling with the dates. Not sure how to set it in my setYAxisValues.
I am getting my values from a rest api and putting it in the graph.

This part is where i have my problem.

yVals.add(new Entry(Float.valueOf(ocd.getScore()), foo));

If I change foo to a normal int value like 1, 2, 3 I have no problem. The graph is working. The issue, i need to use dates to plot my value at the correct place.

@Override
protected void onPostExecute(List<ResultModel> result) {
    super.onPostExecute(result);
   //populating my yAxis with values from rest
    for (ResultModel ocd : resModelList){
        long unixSeconds = Long.parseLong(ocd.getPost_date());
        Date date = new Date(unixSeconds*1000L);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        String formattedDate = sdf.format(date);
        int foo = Integer.parseInt(formattedDate);
        yVals.add(new Entry(Float.valueOf(ocd.getScore()), foo));
    }
}

The X axis is working

//set vales
private ArrayList<String> setXAxisValues(){
    xVals = new ArrayList<String>();
//MM/dd/yyyy
    xVals.add("01/01/2016");
    xVals.add("02/01/2016");
    xVals.add("03/01/2016");
    xVals.add("04/01/2016");
    xVals.add("05/01/2016");
    return xVals;
}

private ArrayList<Entry> setYAxisValues(){
    yVals = new ArrayList<Entry>();
    return yVals;
}

Thanks in advance

Upvotes: 1

Views: 1700

Answers (1)

Roman Iatcyna
Roman Iatcyna

Reputation: 444

I had the similar issue, the point is - MPChart library cannot have anything but float for X axis. I'd suggest you to have X axis represented by date's millis. Suppose you have four values with dates "01/01/2016", "02/01/2016", "03/01/2016", "04/01/2016", "05/01/2016". You add values like

yVals.add(new Entry(Float.valueOf(ocd.getScore()), "01/01/2016".toMillis()));

"01/01/2016".toMillis() is pseudocode of course, you need to convert your date to int (float).

Then, set up minX as "01/01/2016".toMillis(), maxX as"04/01/2016".toMillis(), and provide a label formater which will format this millis back to string dates:

private class  LabelFormatter implements AxisValueFormatter {

        private Context context; 

        private LabelFormatter(Context context) {
            this.context = context;
        }

        @Override
        public int getDecimalDigits() {
            return -1;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
             return DateUtils.formatDateTime(context, (long) value, DateUtils.FORMAT_SHOW_DATE);
        }
    } 

Upvotes: 1

Related Questions