Wednesday, February 25, 2015

ANDROID code to create PI Chart

package com.raj.er.activities;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.raj.er.R;
import com.raj.er.constants.EApplicationConstants;
import com.raj.er.dao.DAO;
import com.raj.er.report.ChartReportAdapter;
import com.raj.er.report.ReportAdapter;
import com.raj.er.utility.PersonalManagerUtility;

public class PiChartActivity extends Activity {
   
    private static final String CLASS = ViewDatesReportActivity.class.getSimpleName();
    private float expenses[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    private String[] categories = {};
    private DAO dao = null;
    private ListView     categoryListView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pi_charts);
       
        categoryListView = (ListView) findViewById(R.id.lvCategoriesList);
        dao = new DAO(this);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
       
        AdView adView = (AdView) this.findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
         .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
         .addTestDevice("").build();
        adView.loadAd(adRequest);
       
        Bundle rcvBag = getIntent().getBundleExtra(EApplicationConstants.ARGUMENTS.getValue());
        String datesValues = (String) rcvBag.getCharSequence(EApplicationConstants.VALUE.getValue());
        String header = (String) rcvBag.getCharSequence(EApplicationConstants.REPORT_HEADER.getValue());
        this.setTitle(header);
       
        getAllCategoriesExpenses(datesValues);
       
        ChartReportAdapter adapter = new ChartReportAdapter(this, categories);
        categoryListView.setAdapter(adapter);

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

        expenses = calculateData(expenses);
        MyGraphview graphview = new MyGraphview(this, expenses);
        lv1.addView(graphview);
       
    }
   
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
        
        case R.id.menuShareApp:
            shareApp();
            break;
           
        case R.id.menuAbout:
            Intent intent = new Intent(getApplicationContext(), AboutActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            break;
          }
        return super.onOptionsItemSelected(item);
    }
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.topmenu, menu);
        return super.onCreateOptionsMenu(menu);
    }
   

    private void shareApp() {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, PersonalManagerUtility.getAppSubject());
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, PersonalManagerUtility.getAppUrlWithMsg());
        startActivity(Intent.createChooser(sharingIntent, "Share via"));       
    }


    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(60, 20, 420, 400);
        float temp = 0;
       
        public MyGraphview(Context context, float[] values) {
            super(context);
       
            int totalCategories = dao.getCategories().size();
            value_degree = new float[totalCategories];
            for (int i = 0; i < values.length; i++) {
                value_degree[i] = values[i];
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            int colors[] = new int[20];

            colors[0] = getContext().getResources().getColor(R.color.chartyellow);
            colors[1] = getContext().getResources().getColor(R.color.chartgreen);
            colors[2] = getContext().getResources().getColor(R.color.chartblue);
            colors[3] = getContext().getResources().getColor(R.color.chartred);
            colors[4] = getContext().getResources().getColor(R.color.chartpopati);
            colors[5] = getContext().getResources().getColor(R.color.chartdarkblue);
            colors[6] = getContext().getResources().getColor(R.color.chartorange);
            colors[7] = getContext().getResources().getColor(R.color.chartgray);
            colors[8] = getContext().getResources().getColor(R.color.chartpink);
            colors[9] = getContext().getResources().getColor(R.color.chartblack);
            colors[10] = getContext().getResources().getColor(R.color.chartrani);
            colors[11] = getContext().getResources().getColor(R.color.xpmati);
            colors[12] = getResources().getColor(R.color.xprani);
            colors[13] = getResources().getColor(R.color.xpslate);
            colors[14] = getResources().getColor(R.color.xppopati);
            colors[15] = getResources().getColor(R.color.xpmagenta);
            colors[16] = getResources().getColor(R.color.xpchokolate);
            colors[17] = getResources().getColor(R.color.xpsteelyellow);
            colors[18] = getResources().getColor(R.color.YellowGreen);
            colors[19] = getResources().getColor(R.color.xpabout);
            
            int totalValues = value_degree.length;
            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(colors[0]);
                    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));
                    if(totalValues<=colors.length){
                        paint.setColor(colors[i]);
                    } else{
                        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);
                }
            }
        }
    }
   
    public void getAllCategoriesExpenses(String datesValues){
       
        Log.i(CLASS,"Method called getAllCategoriesExpenses()");
        //String thisMonthDates = PersonalManagerUtility.getMonthDates(PersonalManagerUtility.getCurrentMonthOfYear()-1, PersonalManagerUtility.getCurrentYear());

        dao =  new DAO(this);       
        List<String> rows = new ArrayList<String>(0);
 
        List<String> catList = dao.getCategories();
        for(String categoryName: catList){
            List<String> categoryRows = new ArrayList<String>(0);
            List<String>    tempRows = dao.getCategoryWiseData(datesValues, categoryName);                       
            categoryRows.addAll(tempRows);
            rows.addAll(categoryRows);
        }
       
        expenses = new float[rows.size()];
        categories = new String[rows.size()+1];
        int totalExpense = 0;
       
        for(String row:rows){
            String array[] = row.split("&");                               
            float expense = (array[1]==null ? 0 : Float.parseFloat(array[1]));
            totalExpense += expense;
        }
       
        int i = 0;
        for(String row:rows){
            String array[] = row.split("&");;                   
            float expense = (array[1]==null ? 0 : Float.parseFloat(array[1]));
            double pertFlt = ((expense*100)/totalExpense);
            Log.d(CLASS,"pertFlt------->> "+pertFlt);
            DecimalFormat twoDForm = new DecimalFormat("#.##");
            double percentage =  Double.valueOf(twoDForm.format(pertFlt));
            Log.d(CLASS,"percentage------->> "+percentage);
            categories[i] = array[0]+" ("+array[1]+""+PersonalManagerUtility.getCurrency()+")& "+percentage+"%";
            expenses[i++] = expense;
        }
        categories[i] = "Total ("+totalExpense+""+PersonalManagerUtility.getCurrency()+")& 100%";
       
    }

    public void setReportData(List<String> rows){
        Log.i(CLASS,"Method called setReportData()");
         String[]  values = new String[rows.size()];
        
        int i=0;
        for(String row:rows){
            values[i]=row;
            i++;
        }
       
        ReportAdapter adapter = new ReportAdapter(this, values);
        /*itemList.setAdapter(adapter);
        tvScreenName.setText(reportHeader);
        if(PersonalManagerUtility.getCurrency()==null || PersonalManagerUtility.getCurrency().equalsIgnoreCase("RUPEES")){
            tvTotalExpValue.setText(getResources().getString(R.string.rs)+" "+dao.getTotalPrice());
        }else{
            tvTotalExpValue.setText(PersonalManagerUtility.getCurrency()+" "+dao.getTotalPrice());
        }*/

        //tvTotalExpValue.setText(getResources().getString(R.string.rs)+" "+dao.getTotalPrice());
    }
}

No comments:

Post a Comment