我有一个代码可以在折线图中显示数据,我需要将 xAxis 更改为日期,但是日志中存在错误
java.lang.NumberFormatException: For input string: "2019-04-19 00:00:00"
下面是我的折线图代码段
mLineChart = findViewById(R.id.chart)
importData()
val dataSet = LineDataSet(entries, "Water")
val lineData = LineData(dataSet)
mLineChart.axisRight.isEnabled = false
mLineChart.data = lineData
dataSet.color = Color.RED
dataSet.setDrawCircles(false)
dataSet.setDrawValues(false)
dataSet.mode = LineDataSet.Mode.CUBIC_BEZIER
mLineChart.description.text = ""
mLineChart.legend.isEnabled = false
mLineChart.invalidate()
val leftAxis = mLineChart.axisLeft
leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
leftAxis.axisMinimum = 0f
leftAxis.axisMaximum = 30f
val rightAxis = mLineChart.axisRight
rightAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
rightAxis.axisMinimum = 0f
rightAxis.axisMaximum = 30f
var xAxis = mLineChart.xAxis
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.setDrawGridLines(false)
xAxis.axisMinimum = 0f
xAxis.labelCount = 5
xAxis.axisMaximum = 400f
xAxis.granularity = 1f
xAxis.isGranularityEnabled = true
xAxis.valueFormatter = DateAxisValueFormatter(null)
下面是我用于插入数据的代码段
private fun importData() {
for (data in dataList) {
val date = java.lang.Float.parseFloat(data.date)
val water = java.lang.Float.parseFloat(data.water)
entries.add(Entry(date, water))
}
下面是我的值格式化程序代码段
internal inner class DateAxisValueFormatter(private val mValues: Array<String>?) : ValueFormatter(),
IAxisValueFormatter {
var sdf = SimpleDateFormat("hh:mm", Locale.ENGLISH)
override fun getFormattedValue(value: Float, axis: AxisBase?): String {
return sdf.format(Date(value.toLong()))
}
}
答案 0 :(得分:0)
您的异常很明显,您正在尝试将字符串转换为Float,但该字符串不是数字。
如果要显示日期,则必须以毫秒为单位格式化日期。 尝试类似的事情:
private fun importData() {
val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
for (data in dataList) {
val date = dateFormatter.parse(data.date)
val water = java.lang.Float.parseFloat(data.water)
//Here you get your date as a Long and you convert it in Float
entries.add(Entry(date.time.toFloat(), water))
}
编辑: 在您的xAxis中,设置您自己的valueFormatter,以这种方式将您的浮点数转换回日期:
val x = chart.xAxis
x.setValueFormatter { value, _ ->
SimpleDateFormat("HH:mm:ss", Locale.ENGLISH).format(value.toLong())
}