Showing Bar Chart in Android using Kotlin (an Agrego Seller case)

Yudanto Anas Nugroho
3 min readMar 16, 2021

When developing an admin panel or dashboard, we always encounter charts and diagrams. Those two things are essential in visualizing the raw data that we got from the database.

In this article, I used the Agrego Seller app as an example. Basically, Agrego Seller is a platform that helps Seller in manage orders from customers, organize products and logistics, and also receive a sales report. The app also has a Dashboard menu where users can see a summary report from their selling activity in the current and previous months. And just like any other Dashboard out there in this menu, we can see Bar Chart that shows total purchases from 3 months before.

Before we start, in this tutorial we are going to use an external library from Github called MPAndroidChart by our friend PhilJay (go check out his repo and support him!). We can begin import dependency in Gradle like this.

Next, we insert the Bar Chart view in our XML layout. It’s important to note that I use match_parent in both the width and height of this view because if it is wrap_content the chart will become messy and unreadable.

Bar Chart View in the XML layout

As for the data, we’re going to retrieve the data first and put it in a List object in this case, it’s List<OrderReport>. After that, we’re going to iterate each item in the list and put it on the BarEntry object. This BarEntry object has multiple implementations one of which is it takes a float value of x (data label) and a float value of y (data value). Finally, we’re inserting all of BarEntry objects into ArrayList<BarEntry>.

Now, we insert that ArrayList <BarEntry> into a BarDataSet, and after that, we take the data set and add it to the BarData object. We can imagine, the data set as a set of data in each Bar and the BarData object collects those set of data and display it in the chart. Lastly, we’re going to set this data in chart view by using chart.setData(). Notice that at the end of the line we invoke the invalidate function to refresh our chart view, this function is pretty useful if you have a refresh mechanism in your code so that the chart will refresh every time it receives a new set of data.

That’s pretty much it! now let’s run our code.

Looks good, doesn’t it? As for the styling option, you can explore more in the documentation here or try the demo app here. Big credits to PhilJay for making the library. It is very helpful and easy to use 👍

Thank you guys for reading!

Don’t forget to check agrego.id and emall.agrego.id for more info. Cheers! 👐

--

--