Hot questions for Date Using in MPAndroidChart

MPAndroid Date Formatting and Parsing Loses Precision

Question: I'm using the MPAndroid library for the graph of my android app. I have a long value inputted to the entry. My problem is that when I format the values of x axis, it uses float value instead of long so it loses precision.

Here is my code for the entry to the graph:

String dateString = "02/13/2019(11:23:45)";
long readingDate = 0;
try {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy(kk:mm:ss)", Locale.US);
    Date date = sdf.parse(dateString);
    readingDate = date.getTime();
    } catch (ParseException e) {
         e.printStackTrace();
    }
SensorData.add(new Entry(readingDate, 1.5);

Here is my code for formatting the x axis:

private class XAxisValueFormatter implements IAxisValueFormatter {

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        String dateString = new SimpleDateFormat("MM/dd/yyyy(kk:mm:ss)", Locale.US).format(value);
        return dateString;
    }
}

How can I fix this problem?

Answer: One of possible solutions would be to make your first point hold 0 value.

Basically you need subtract start_timestamp from every new x value of Entry so chart will be started from 0 value and not of timestamp.

For example. Let's assume start_timestamp variable holds your first timestamp of datapoints.

To add new entry use:

SensorData.add(new Entry(readingDate - start_timestamp, 1.5);

To format x value you just add start_timestamp to provided x value.


MPAndroid Chart by Date

Question: I have a date object with includes a level (y-axis), a type (colour) and a date (x-axis).

I understand that I can make a grouped barchart using MPAndroidChart but how do I change the x values to show the date?

Answer: Use an IAxisValueFormatter like so:

public class MyYAxisValueFormatter implements IAxisValueFormatter {

    private SimpleDateFormat mFormat;

    public MyAxisValueFormatter() {

        // format values to 1 decimal digit
        mFormat = new SimpleDateFormat("MMM dd");
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        // "value" represents the position of the label on the axis (x or y)
        return mFormat.format(value);
    }

    /** this is only needed if numbers are returned, else return 0 */
    @Override
    public int getDecimalDigits() { return 0; }
}