Bar chart and Pie chart show using retrofit rest api in android

Md. Masud Parvez
Oct 11, 2019 · 5 min read

I am a big fan of Medium I have learned a lot of things from here. So I think it’s my responsibility to back something.

I was working on a financial android project in this project I have to retrieve data from server using Rest API and show them in a Bar Chart and Pie Chart. Before this project, I have no idea about the Chart library. I found MPAndroidChart in Github.

I started digging on how I can use this library in my project. This is so big library and I need some custom design. So I was searching on google about this library example or tutorial. Suddenly I found that this library changes a lot in every version it releases. On the whole internet, no one’s code or implement doesn’t match with each other. Then I decided to implement on my own so trying to understand how this works. After 2 hours of digging, I managed my Bar chart and my Pie chart which I need.

Image for post
Image for post

To add MPAndroidChart into your project use this gradle

repositories {
maven { url 'https://jitpack.io' }
}

dependencies {
implementation 'com.github.PhilJay:MPAndroidChart:v2.0.9'
}

For parsing JSON data i am using retrofit in this project and gson which is Gson is an open-source Java library to serialize and de-serialize.

// retrofit, gson                           
implementation 'com.google.code.gson:gson:2.6.2' implementation 'com.squareup.retrofit2:retrofit:2.0.2' implementation 'com.squareup.retrofit2:converter-gson:2.0.2' implementation 'com.squareup.okhttp3:okhttp:3.2.0' implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'

I made a json format so that i can use it as my requirement and it hosted in this link.

{

"success": true,

"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
"pie_statistics": {
"assigned": 120,
"opened": 212,
"in-progress": 100,
"completed": 320,
"done": 433,
"rejected": 111,
"expired": 332
},

"bar_months":[
"jan",
"feb",
"mar"
],

"bar_pending":[
100,
200,
300
],

"bar_rejected":[
140,
220,
340
],


"bar_completed":[
170,
290,
310
]

}

Now everything found which I needed for my project. If you have no idea about how retrofit works please visit these links.

Now I need to create this JSON POJO so that retrofit can play with these objects.To convert JSON to POJO I always use

http://www.jsonschema2pojo.org/

this website is so lovely. I used this library almost every day. Just copy the JSON and paste on the left side.

Image for post
Image for post

Note careful about the settings in right side. Now just click preview button you will get pojo classes cope those classes and past into your project.
Now we need to write our ApiInterface and ApiClient Classes.

public class ApiClient {

private static Retrofit retrofit = null;

private static OkHttpClient buildClient() {
return new OkHttpClient
.Builder()
.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build();
}

public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.client(buildClient())
.addConverterFactory(GsonConverterFactory.create())

/**
*
* base url here for api
*/

.baseUrl("https://raw.githubusercontent.com/paveltech/BarchartExample/master/")
.build();
}
return retrofit;
}
}

and ApiInterface class

public interface ApiInterface {

@GET("chart.json")
Call<PiChart> init();

}

#Now for Pie Chart we need to add some xml

<com.github.mikephil.charting.charts.PieChart
android:id="@+id/piechart"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Now for Pie Chart show in need to call retrofit api and put data into the Pie chart just like..

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pi_chart);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

apiInterface = ApiClient.getClient().create(ApiInterface.class);
apiCall();

}


/**
* Api call for retriving data for pie chart
*/
private void apiCall() {
Call<PiChart> piChartCall = apiInterface.init();
piChartCall.enqueue(new Callback<PiChart>() {
@Override
public void onResponse(Call<PiChart> call, Response<PiChart> response) {
setData(response.body());
}

@Override
public void onFailure(Call<PiChart> call, Throwable t) {

}
});
}


/**
* Set Data Into the pie chart
*
@param piChart
*/

private void setData(PiChart piChart) {

PieChart pieChartList = findViewById(R.id.piechart);


/**
* get Data for pie chart
*/

ArrayList pieChartData = new ArrayList();
pieChartData.add(new Entry(piChart.getPieStatistics().getAssigned(), 0));
pieChartData.add(new Entry(piChart.getPieStatistics().getOpened(), 1));
pieChartData.add(new Entry(piChart.getPieStatistics().getInProgress(), 2));
pieChartData.add(new Entry(piChart.getPieStatistics().getCompleted(), 3));
pieChartData.add(new Entry(piChart.getPieStatistics().getDone(), 4));


PieDataSet dataSet = new PieDataSet(pieChartData, "");
dataSet.setValueTextSize(14);


/**
* set segment for pie chart
*/

ArrayList pieChartSectionName = new ArrayList();
pieChartSectionName.add("Assigned");
pieChartSectionName.add("Opened");
pieChartSectionName.add("Completed");
pieChartSectionName.add("Done");
pieChartSectionName.add("Rejected");


PieData data = new PieData(pieChartSectionName, dataSet);
pieChartList.setData(data);


/**
* Segment color added into the pie chart
*/

dataSet.setColors(new int[]{Color.parseColor("#9c27b0"),
Color.parseColor("#ef5350"),
Color.parseColor("#ff5252"),
Color.parseColor("#2196f3"),
Color.parseColor("#7cb342")});



pieChartList.animateXY(500, 500);

}

}

In this activity first i init the Retrofit clients and PieChart. Then i make HTTP call and collect data from the server then just added data into the Pie Chart. always remember segment number and pieChart data list should be same number. also you can change piechart animation show time.

#Now for Bar-chart we need to add xml

<com.github.mikephil.charting.charts.BarChart
android:id="@+id/barchart"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Now just write our Barchart activity as same like previous. Just like

public class BarchartRetrofit extends AppCompatActivity {


public ApiInterface apiInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
apiInterface = ApiClient.getClient().create(ApiInterface.class);

/**
* api call to get some data from server
*
*/
getData();

}


private void getData() {
Call<PiChart> piChartCall = apiInterface.init();
piChartCall.enqueue(new Callback<PiChart>() {
@Override
public void onResponse(Call<PiChart> call, Response<PiChart> response) {
Log.d("CHART_RESPONSE", "" + response.body().getBarMonths().toString());
setData(response.body());
}

@Override
public void onFailure(Call<PiChart> call, Throwable t) {

}
});
}


/**
* Set data into pie chart
*
@param piChart
*/

private void setData(PiChart piChart) {

ArrayList<BarDataSet> dataSets = null;

ArrayList<BarEntry> completed = new ArrayList<>();


/**
* Getting the value for Complete list
*/

for (int i = 0; i < piChart.getBarCompleted().size(); i++) {
BarEntry value = new BarEntry(piChart.getBarCompleted().get(i), i); // Jan
completed.add(value);
}


/**
* Add complete data into the bar chart
*/

BarDataSet completeData = new BarDataSet(completed, "Completed Issue");
completeData.setColor(Color.rgb(0, 155, 0));


/**
* Getting Pending data
*/

ArrayList<BarEntry> pending = new ArrayList<>();
for (int i = 0; i < piChart.getBarCompleted().size(); i++) {
BarEntry value = new BarEntry(piChart.getBarPending().get(i), i); // Jan
pending.add(value);
}

/**
* adding pending data into the bar chart
*/

BarDataSet pendingdata = new BarDataSet(pending, "Pending Issue");
pendingdata.setColor(Color.rgb(253, 129, 0));


/**
* Getting rejected data from the api
*/

ArrayList<BarEntry> rejected = new ArrayList<>();
for (int i = 0; i < piChart.getBarCompleted().size(); i++) {
BarEntry value = new BarEntry(piChart.getBarRejected().get(i), i); // Jan
rejected.add(value);
}


/**
* set rejected data into
*/

BarDataSet rejectedData = new BarDataSet(rejected, "Rejected Issue");
pendingdata.setColor(Color.rgb(255, 0, 0));


/**
* set data into the data set into the bar chart
*
*/

dataSets = new ArrayList<>();
dataSets.add(completeData);
dataSets.add(pendingdata);
dataSets.add(rejectedData);


/**
* set months for x-axis
*/

ArrayList<String> xAxis = new ArrayList<>();
for (String months : piChart.getBarMonths()) {
Log.d("CHART_RESPONSE", "month: " + months.toString());
xAxis.add(months);
}

com.github.mikephil.charting.charts.BarChart chart = (com.github.mikephil.charting.charts.BarChart) findViewById(R.id.barchart);


BarData data = new BarData(xAxis, dataSets);

chart.setData(data);
chart.setDescription("Bar chart");

/**
* Data show animation change
* millisecond wait for showing data in x-axis and y-axis
*/
chart.animateXY(2000, 2000);
chart.invalidate();

}
}

Note: Just remember the data set should be the same all the time. and you can change the animation time. If you want to add another month just add months in the JSON and increase another section.

You can find this project on GitHub link

If you find this is helpful please share this with your friends and if you find any bug please don’t forget to open a new issue.

Thanks a lot Happy Codeing ❤

The Startup

Md. Masud Parvez

Written by

Android Application Developer and love to learn new tech. I believe the hardest job is to develop simple thing. Shoot me(pavelcep.sust11@gmail.com) for project

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Md. Masud Parvez

Written by

Android Application Developer and love to learn new tech. I believe the hardest job is to develop simple thing. Shoot me(pavelcep.sust11@gmail.com) for project

The Startup

Medium's largest active publication, followed by +756K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store