Kotlin How do I use Realtime Database in MPAndroidChart

I am trying to use the realtime database in a chart but it seems to not be able to convert the values in the database to a float.

The code below is how I have the graph set up.

Fragment.kt

private fun setBarChart() {
        databaseReference?.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {


                val testMon = snapshot.child("user_data/most_recent_per_day/Mon").value.toString().toFloat()

                val entries = ArrayList<BarEntry>()
                entries.add(BarEntry(test, 0))
                entries.add(BarEntry(10f, 1))
                entries.add(BarEntry(5f, 2))
                entries.add(BarEntry(20f, 3))
                entries.add(BarEntry(15f, 4))
                entries.add(BarEntry(19f, 5))
                entries.add(BarEntry(19f, 6))

                val barDataSet = BarDataSet(entries, "Cells")

                val labels = ArrayList<String>()
                labels.add("Mon")
                labels.add("Tue")
                labels.add("Wed")
                labels.add("Thu")
                labels.add("Fri")
                labels.add("Sat")
                labels.add("Sun")
                val data = BarData(labels, barDataSet)
                barChart.data = data // set the data and list of lables into chart

                barChart.setDescription("Set Bar Chart Description")  // set the description

                //barDataSet.setColors(ColorTemplate.COLORFUL_COLORS)
                barDataSet.color = resources.getColor(R.color.colorAccent)

                barChart.animateY(5000)
            }

When i set a value of the graph as testMon = snapshot.child("user_data/most_recent_per_day/Mon").value.toString().toFloat() it gives a numException. The BarEntry() only accepts a Float as the first parameter.

Below is the logcat.

 java.lang.NumberFormatException: For input string: "null"
        at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
        at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
        at java.lang.Float.parseFloat(Float.java:451)
        at com.fitnessproject.fragments.StatsFragment$setBarChart$1.onDataChange(StatsFragment.kt:66)

Any idea how to convert my database values to a Float correctly?

Source: Android Questions

LEAVE A COMMENT