Search code examples
javaandroiddatepickerandroid-sqlitempandroidchart

How can I use dates from a DatePicker element to be the x-axis values on a MPAndroidChart?


I am attempting to create a line graph using MPAndroidChart where the user enters a date (either today or a previous day) using a DatePicker and then enters a separate value for that date. The issue I am having is how to format that date from the DatePicker for saving it on a SQLite database, and then to take it out and use it for the x-axis of my graph. I have tried all of the different methods I have seen here and on the documentation, but they seem to be more for real-time data and not for graphs using previous days.

I am pretty much lost of the best way to go about this. Any help or advice would be apprecaited.


Solution

  • use custom valueformatter

    class DateValueFormatter extends ValueFormatter {
        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        private List<Date> dateList;
    
        public DateValueFormatter(List<Date> dateList) {
            this.dateList = dateList;
        }
    
        @Override
        public String getAxisLabel(float value, AxisBase axis) {
            int axisValue = (int) value;
            if (axisValue >= 0 && axisValue < dateList.size()) {
                return dateFormat.format(dateList.get(axisValue));
            } else {
                return "";
            }
        }
    }
    

    and set xaxis value formatter

    chart.getXAxis().setValueFormatter(new DateValueFormatter(datelist));