Skip to main content

Featured post

Simple RecyclerView example with filter option in Android

Hi Guys, Maybe you all are expert in terms of using RecyclerView in android. This blog is simple example for using filter option with RecyclerView adapter. As for now you will instantiate RecyclerView and set the adapter to RecyclerView as following way. RecyclerView list = (RecyclerView) findViewById(R.id.list); list.setLayoutManager(new LinearLayoutManager(this)); list.setHasFixedSize(true); ArrayList&ltNumber&gt numbers = new ArrayList&lt&gt(); String ONEs[] = {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN"}; String TENs[] = {"ZERO", "TEN", "TWENTY", "THIRTY", "FOURTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY", "HUNDRED"}; String HUNDREDS[] = {"ZERO", "HUNDRED", "TWO HUND...

Pie Chart in Android without using external jar

Simple Pie Chart example without using any external jar in android. Here We are creating chart using Canvas class in android.

This is the sample screenshot of our application.



 And this is also sample screenshot of our application.


It is easy to draw this chart in android.

First our xml will be.



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </LinearLayout>

</RelativeLayout>
Our Activity will be.
public class MainActivity extends Activity {

float values[] = { 700, 400, 100, 500,600 };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

LinearLayout lv1 = (LinearLayout) findViewById(R.id.linear);

values = calculateData(values);
MyGraphview graphview = new MyGraphview(this, values);
lv1.addView(graphview);  
}

private float[] calculateData(float[] data) {
float total = 0;
for (int i = 0; i < data.length; i++) {
total += data[i];
}
for (int i = 0; i < data.length; i++) {
data[i] = 360 * (data[i] / total);
}
return data;
}

public class MyGraphview extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
private float[] value_degree;
RectF rectf = new RectF(120, 120, 380, 380);
float temp = 0;

public MyGraphview(Context context, float[] values) {
super(context);
value_degree = new float[values.length];
for (int i = 0; i &lt values.length; i++) {
value_degree[i] = values[i];
}
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Random r;
for (int i = 0; i < value_degree.length; i++) {
if (i == 0) {
r = new Random();
int color = Color.argb(100, r.nextInt(256), r.nextInt(256),
r.nextInt(256));
paint.setColor(color);
canvas.drawArc(rectf, 0, value_degree[i], true, paint);
} else {
temp += value_degree[i - 1];
r = new Random();
int color = Color.argb(255, r.nextInt(256), r.nextInt(256),
r.nextInt(256));
paint.setColor(color);
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
}
}
}  
}
}
Explainations.
float values[] = { 700, 400, 100, 500,600 };
this line defines how many attributes the chart should have. You can chnge this values and also number of elements. It will working fine.
values = calculateData(values);
In this method we calculating percentage for each element to decide how much space each element should have in piechart. So here we are calculating it for 360.
MyGraphview graphview = new MyGraphview(this, values);
In this line we are generating a chart view and store it in varalbe graphview.
lv1.addView(graphview);  
Here we are add that view to our linearlayout using addview method. Generation of graphview
RectF rectf = new RectF(120, 120, 380, 380);
This line decide at which position our chart should appear.
public MyGraphview(Context context, float[] values) {
super(context);
value_degree = new float[values.length];
for (int i = 0; i &lt values.length; i++) {
value_degree[i] = values[i];
}
}
Here we just change MainActivity's values to MyGraphview class's values. Next on draw method. We are drawing our chart here only.
int color = Color.argb(255, r.nextInt(256), r.nextInt(256),r.nextInt(256));
This line is for generating a random color. By this line our application will show different color at each time we are opening it.
paint.setColor(color);
Here just we are apply that generated color to our paint object.
canvas.drawArc(rectf, temp, value_degree[i], true, paint);
This line is most importatnt in this application. Because by using this line only we are drawing arc for each elemnt. Note: We are drawing arc only, not circle. If one arc ended at on position we start drawing another arc from that position itself. Thats why it is visible as Pi Chart.
Related article PieChart using AChartEngine

Thank You

Comments

  1. nice work thanks

    ReplyDelete
  2. How to draw two or more pie chart in a single activity? Thank you

    ReplyDelete
    Replies
    1. It is quite easy. See my question and answer in following link http://stackoverflow.com/questions/15301271/could-not-add-addview-in-android?answertab=active#tab-top

      Delete
  3. Thanks for the code, Is there any blong for barchart

    ReplyDelete
  4. Your code stops at run time.

    ReplyDelete

Post a Comment

Popular posts from this blog

Simple example of OCRReader in Android.

Hi Friends, Maybe you all heard/used text scanning using camera feature or extracting text from Image. But this sample made it very easy for you. You can made it in very simple line of code. You can download the source code from OCRSample and import the library as a module into your project. Example usage : MainActivity.java public class MainActivity extends AppCompatActivity { private TextView textView; private final int CAMERA_SCAN_TEXT = 0; private final int LOAD_IMAGE_RESULTS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSele...

Simple example of using Spinner in Kotlin | Android

Though Kotlin has lot massive features to speedup the development time, here is the simple way of using Spinner in Android. In Kotlin we don't need to declare and initialize Spinner. We can simply access the id of Spinner from xml. Ex : import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Toast import android.widget.Toast.LENGTH_LONG import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //String array. val myStrings = arrayOf("One", "Two", "Three", "Four", "Five") //Adapter for spinner mySpinner.adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_i...

Set limit for fraction in decimal numbers in EditText

            Already we know that we can set which type of input the edittext should accept from user using android:inputType="numberDecimal" But there is no predefined function to set the limit for the edittext to How many digit it should accept after the decimal point from user . We can achieve this by using TextWatcher . Full code example. Following program creates a Decimal Filter. DecimalFilter.java import android.text.Editable; import android.text.InputFilter; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.widget.EditText; public class DecimalFilter implements TextWatcher { int count= -1 ; EditText et; Activity activity; public DecimalFilter(EditText edittext, Activity activity) { et = edittext; this.activity = activity; } public void afterTextChanged(Editable s) { if (s.length() > 0) { String str = et.get...