create account

Using PieChart to show product statistic in android by andrixyz

View this thread on: hive.blogpeakd.comecency.com
· @andrixyz · (edited)
$45.30
Using PieChart to show product statistic in android
#### What Will I Learn?

- Integrate project via gradle
- Creating the layout of chart
- Fill data set and attach data to the chart

#### Requirements
- Android Studio 3.0 (recommended)
- Understanding of Java programming language
- Gradle dependencies
- Basic layouting with android development

#### Difficulty
- Basic

#### Tutorial Contents
Pie chart  is a circular statistical graphic which is divided into slices to illustrate numerical proportion. It is usually help some companies to track their product statistics. For example, how many products were sold, view, redeemed and so on. Also, the statistic can be of any categories like office, home, furniture, etc. In this tutorial, you will learn how to implement piechart using some datas that we'll fill. Let's get started.

<b>Integrate the project via gradle</b>

First of all, we need to go to project level build.gradle. Notice on image below that has highlighted build.gradle. If you wanna see hierarchy like this, click the dropdown and choose Android.

![dasdasdsad.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520499650/xzwc5znxrbufuf0drgnl.png)

Click the hightlighted build.gradle(Project:DemoApp). The DemoApp name is depend on your project name. Put the ```maven { url "https://jitpack.io" }``` line into each repositories section inside respectively of buildscript and allprojects section. It will looks like this.

![dasdad.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520524114/ndem3ziaybz9sedibxxp.png)

We also need to add the implementation of library using this line ```implementation 'com.github.PhilJay:MPAndroidChart:v3.0.3'``` to add the dependency to our app. Add inside the dependencies section. Make sure add this line in build.gradle (module:app) and notice the implementation highlighted line. It will looks like this.

![sadsadasd.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520528590/gw6vnz5ohjjojzzghpac.png)

After done, press sync and wait until finish. We will be able to use the library.

<b>Creating the PieChart using layout</b>

Go to your layout file that corresponding to your Java class later. We'll create the layout using XML. We'll place the PieChart in middle of screen using constraint layout as its parent. Write down this code.
```
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.professional.andri.demoapp.MainActivity">

    <com.github.mikephil.charting.charts.PieChart
        android:id="@+id/pie_chart"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintBottom_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

</android.support.constraint.ConstraintLayout>
```
It will displays "no charts data available" because we haven't set any data to the chart. Note that we are using constraint to left, right, top and bottom to parent which is equal to center of the screen. 

![ppp4.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520525417/vfmupy1wsuxxj9p7hmtt.png)

Let's go to fill in the data set and set data to the chart.

<b>Fill in the data set and attach the data to Pie Chart</b>

We always need data to analyze what we want to track and log. So, we must first create the data that will represent in the pie chart. Go to your corresponding activity/fragment Java class, first get the reference of chart that will be used later. Use this line ```PieChart pieChart = findViewById(R.id.pie_chart);```. In this context, i am using activity. Then, we need to provide some datas. I created some arrays of products name, products sold and product colors. Write this code to set the data. Of course, you can change depend on your need.
```
float[] productSold = {300, 1000, 2500, 1200};
String[] productNames = {"Furniture", "Cosmetic", "Food", "Ticket"};
Integer[] productColors = {Color.DKGRAY, Color.RED, Color.GREEN, Color.BLUE};
```

We 'll create the ```pieEntries``` and ```colors``` arraylist to add the pie data and colors to the chart. Let's create those arrays.
```
ArrayList<PieEntry> pieEntries = new ArrayList<>();
ArrayList<Integer> colors = new ArrayList<>();
```
After created the arrays, we will loop to add data to the pieEntries with the provided data above that consist of productSold, productNames, productColors. Write this code.
```
for(int i = 0;i<productNames.length;i++) {
            PieEntry pieEntry = new PieEntry(productSolds[i], productNames[i]);
            pieEntries.add(pieEntry);
            colors.add(productColors[i]);
}
```
Note we are using integer to colors because Integer represents the color. Let's go to the next step.
We are going to create the PieDataSet first and set the colors we have provided above. Write this code.
```
PieDataSet pieDataSet = new PieDataSet(pieEntries, "Products Statistics");
pieDataSet.setColors(colors);
```
Then,  we need to create the PieData and attach pie data set we have created above to the Piedata and i will disable default description to the pieChart by using these codes. 
```
PieData pieData = new PieData(pieDataSet);
pieData.setDataSet(pieDataSet);
pieChart.getDescription().setEnabled(false);
```
Then, the last step is to set the pieData to the chart  and refresh the chart to display what we have provide in the data including productSold, productNames, productColors using code below.
```
pieChart.setData(pieData);
pieChart.invalidate();
```
The result will be looks like this.

![dasdasasdsad.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520527094/oer6rihq2cezrphc1oen.png)

You can see that we have 4 category data that represents ticket, cosmetics, furniture and food. The most sold is the food product with 2500 and the minimum sold is the furniture which is only 300. Note that this is just the raw value. We also can change the value to percentage by multiply 100 and divide by the total products. If you want something like that,  first sum all of the products sold and modify the code that we add data to pieEntries. But, let's get started with the sum of all products.
```
float totalSold = 0;
for(int i=0;i<productSolds.length;i++){
       totalSold += productSolds[i];
}
```
Then, we modify the product sold when we are add to the entries like this 
```
for(int i = 0;i<productNames.length;i++) {
            float soldPercentage = productSolds[i] * 100 / totalSold;
            PieEntry pieEntry = new PieEntry(soldPercentage, productNames[i]);
            pieEntries.add(pieEntry);
            colors.add(productColors[i]);
}
```
Notice the soldPercentage variable that we first multiply by 100 and divide by product sold. Then we set the formatter using percent formatter. 
```pieData.setValueFormatter(new PercentFormatter());```
After done run your app. You should see the final result like this. 

![dasdsad.PNG](https://res.cloudinary.com/hpiynhbhq/image/upload/v1520528082/xqmtkd7e46hgoohfw3mo.png)

This is the final code.
```
package com.professional.andri.demoapp;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PieChart pieChart = findViewById(R.id.pie_chart);

        float[] productSolds = {300, 1000, 2500, 1200};
        String[] productNames = {"Furniture", "Cosmetic", "Food", "Ticket"};
        Integer[] productColors = {Color.DKGRAY, Color.RED, Color.GREEN, Color.BLUE};

        float totalSold = 0;
        for(int i=0;i<productSolds.length;i++){
            totalSold += productSolds[i];
        }

        ArrayList<PieEntry> pieEntries = new ArrayList<>();
        ArrayList<Integer> colors = new ArrayList<>();
        for(int i = 0;i<productNames.length;i++) {
            float soldPercentage = productSolds[i] * 100 / totalSold;
            PieEntry pieEntry = new PieEntry(soldPercentage, productNames[i]);
            pieEntries.add(pieEntry);
            colors.add(productColors[i]);
        }

        PieDataSet pieDataSet = new PieDataSet(pieEntries, "Products Statistics");
        pieDataSet.setColors(colors);

        PieData pieData = new PieData(pieDataSet);
        pieData.setValueFormatter(new PercentFormatter());
        pieData.setDataSet(pieDataSet);
        pieChart.getDescription().setEnabled(false);
        pieChart.setData(pieData);
        pieChart.invalidate();
        

    }
}
```

And it's done. That's how we convert to percentage. Congratulation of completing this PieChart guide. This PieChart can help many developers to easily integrate statistics, analytics and so on. Thanks for following this tutorial.


<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@andrixyz/using-piechart-to-show-product-statistic-in-android">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , , , , , , , , , ,
properties (23)
authorandrixyz
permlinkusing-piechart-to-show-product-statistic-in-android
categoryutopian-io
json_metadata"{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":19148949,"name":"MPAndroidChart","full_name":"PhilJay/MPAndroidChart","html_url":"https://github.com/PhilJay/MPAndroidChart","fork":false,"owner":{"login":"PhilJay"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","android","tutorial","piechart","java"],"users":["Override","andrixyz"],"links":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1520499650/xzwc5znxrbufuf0drgnl.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520524114/ndem3ziaybz9sedibxxp.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520528590/gw6vnz5ohjjojzzghpac.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520525417/vfmupy1wsuxxj9p7hmtt.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520527094/oer6rihq2cezrphc1oen.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520528082/xqmtkd7e46hgoohfw3mo.png"],"image":["https://res.cloudinary.com/hpiynhbhq/image/upload/v1520499650/xzwc5znxrbufuf0drgnl.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520524114/ndem3ziaybz9sedibxxp.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520528590/gw6vnz5ohjjojzzghpac.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520525417/vfmupy1wsuxxj9p7hmtt.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520527094/oer6rihq2cezrphc1oen.png","https://res.cloudinary.com/hpiynhbhq/image/upload/v1520528082/xqmtkd7e46hgoohfw3mo.png"],"moderator":{"account":"cha0s0000","time":"2018-03-09T00:41:37.819Z","reviewed":true,"pending":false,"flagged":false},"questions":[{"question":"Is the project description formal?","answers":[{"value":"Yes it’s straight to the point","selected":true,"score":10},{"value":"Need more description ","selected":false,"score":5},{"value":"Not too descriptive","selected":false,"score":0}],"selected":0},{"question":"Is the language / grammar correct?","answers":[{"value":"Yes","selected":true,"score":20},{"value":"A few mistakes","selected":false,"score":10},{"value":"It's pretty bad","selected":false,"score":0}],"selected":0},{"question":"Was the template followed?","answers":[{"value":"Yes","selected":true,"score":10},{"value":"Partially","selected":false,"score":5},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is there information about the additional frameworks?","answers":[{"value":"Yes, everything is explained","selected":true,"score":5},{"value":"Yes, but not enough","selected":false,"score":3},{"value":"No details at all","selected":false,"score":0}],"selected":0},{"question":"Is there code in the tutorial?","answers":[{"value":"Yes, and it’s well explained","selected":true,"score":5},{"value":"Yes, but no explanation","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial explains technical aspects well enough?","answers":[{"value":"Yes, it teaches how and why about technical aspects","selected":true,"score":5},{"value":"Yes, but it’s not good/enough","selected":false,"score":3},{"value":"No, it explains poorly","selected":false,"score":0}],"selected":0},{"question":"Is the tutorial general and dense enough?","answers":[{"value":"Yes, it’s general and dense","selected":true,"score":5},{"value":"Kinda, it might be more generalized","selected":false,"score":3},{"value":"No, it’s sliced unnecessarily to keep part number high","selected":false,"score":0}],"selected":0},{"question":"Is there an outline for the tutorial content at the beginning of the post","answers":[{"value":"Yes, there is a well prepared outline in “What will I learn?” or another outline section","selected":true,"score":5},{"value":"Yes, but there is no proper listing for every step of the tutorial or it’s not detailed enough","selected":false,"score":3},{"value":"No, there is no outline for the steps.","selected":false,"score":0}],"selected":0},{"question":"Is the visual content of good quality?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Yes, but bad quality","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0},{"question":"Is this a tutorial series?","answers":[{"value":"Yes","selected":false,"score":5},{"value":"Yes, but first part","selected":false,"score":3},{"value":"No","selected":true,"score":0}],"selected":2},{"question":"Is the tutorial post structured?","answers":[{"value":"Yes","selected":true,"score":5},{"value":"Not so good","selected":false,"score":3},{"value":"No","selected":false,"score":0}],"selected":0}],"score":76}"
created2018-03-08 16:56:24
last_update2018-03-09 00:41:36
depth0
children2
last_payout2018-03-15 16:56:24
cashout_time1969-12-31 23:59:59
total_payout_value31.454 HBD
curator_payout_value13.847 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length9,666
author_reputation1,144,619,513,316
root_title"Using PieChart to show product statistic in android"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id43,150,313
net_rshares14,312,219,084,329
author_curate_reward""
vote details (18)
@cha0s0000 ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorcha0s0000
permlinkre-andrixyz-using-piechart-to-show-product-statistic-in-android-20180309t004143556z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-09 00:41:54
last_update2018-03-09 00:41:54
depth1
children0
last_payout2018-03-16 00:41:54
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation30,983,518,016,225
root_title"Using PieChart to show product statistic in android"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id43,218,227
net_rshares0
@utopian-io ·
### Hey @andrixyz I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-andrixyz-using-piechart-to-show-product-statistic-in-android-20180310t100721897z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-03-10 10:07:42
last_update2018-03-10 10:07:42
depth1
children0
last_payout2018-03-17 10:07:42
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,084
author_reputation152,955,367,999,756
root_title"Using PieChart to show product statistic in android"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id43,491,342
net_rshares0