kotlinlinechartmpandroidchart

MPAndroidChart line graph doesn't like my real data


My data looks like this:

{
    "id": "6e10e9fc-2d1f-4c5c-a1c5-d94d99ec55db",
    "air_temperature": 25.7,
    "timestamp": "2023-05-12 15:00:00",
    "parent_edge_device_id": "57028175-8f52-4bdd-b470-ff7485cdb80a"
}

air_temperature would be the axis Y value and timestamp would be converted to a date, take it's time, then converted to a Float to be the axis X. My code looks like this:

val formatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
for(item in items){
    val date = formatter.parse(item.timestamp)!!
    val dateTimestamp = date.time

    val entry = Entry(
        dateTimestamp.toFloat(),
        item.air_temperature!!,
        ResourcesCompat.getDrawable(resources, R.drawable.ic_star, null)
    )
    values.add(entry)
}

I made an Entry that satisfies the class, but the library doesn't seem to like it and won't display it.

I also think I'm getting an error related to this that looks like this.

java.lang.NegativeArraySizeException: -16 at com.github.mikephil.charting.utils.Transformer.generateTransformedValuesLine(Transformer.java:178) at com.github.mikephil.charting.renderer.LineChartRenderer.drawValues(LineChartRenderer.java:549) at com.github.mikephil.charting.charts.BarLineChartBase.onDraw(BarLineChartBase.java:278) at android.view.View.draw(View.java:22644) at android.view.View.updateDisplayListIfDirty(View.java:21519) at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4512)

Which is quite confusing, because I'm sure something is getting inserted to the values List


Solution

  • That error can happen if the data is not sorted by X value.

    This is described in the MPAndroidChart docs and this Github issue too, along with a solution for how to sort the data.

    Please be aware that this library does not officially support drawing LineChart data from an Entry list not sorted by the x-position of the entries in ascending manner. Adding entries in an unsorted way may result in correct drawing, but may also lead to unexpected behaviour.

    You can use the EntryXComparator provided in MPAndroidChart to easily sort them

    val values = mutableListOf<Entry>()
    // fill the values array
    values.sortWith(EntryXComparator())
    

    or just use a native Kotlin sort

    values.sortBy { it.x }