Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.duka.activities;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Color;
- import android.net.ConnectivityManager;
- import android.net.NetworkInfo;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.Toolbar;
- import android.util.Log;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.RadioButton;
- import android.widget.RelativeLayout;
- import android.widget.Spinner;
- import android.widget.TextView;
- import com.duka.R;
- import com.github.mikephil.charting.charts.LineChart;
- import com.github.mikephil.charting.charts.PieChart;
- import com.github.mikephil.charting.components.Legend;
- import com.github.mikephil.charting.components.XAxis;
- import com.github.mikephil.charting.data.Entry;
- import com.github.mikephil.charting.data.LineData;
- import com.github.mikephil.charting.data.LineDataSet;
- import com.github.mikephil.charting.data.PieData;
- import com.github.mikephil.charting.data.PieDataSet;
- import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
- import com.github.mikephil.charting.utils.ColorTemplate;
- import com.loopj.android.http.AsyncHttpClient;
- import com.loopj.android.http.AsyncHttpResponseHandler;
- import com.loopj.android.http.RequestParams;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import java.text.DateFormat;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Calendar;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Locale;
- import butterknife.BindView;
- import butterknife.ButterKnife;
- import cz.msebera.android.httpclient.Header;
- import dataBaseHandlers.SalesHandler;
- import fr.castorflex.android.smoothprogressbar.SmoothProgressBar;
- import utility.AccountSharedPreferences;
- import utility.Crouton;
- import utility.CustomMarkerView;
- import utility.CustomValueFormatter;
- import utility.PercentagesValueFormatter;
- import utility.PeriodHelper;
- import utility.Style;
- public class Reports extends AppCompatActivity {
- SalesHandler sh;
- @BindView(R.id.app_bar)
- Toolbar toolbar;
- @BindView(R.id.hour_radioBtn)
- RadioButton hourButton;
- @BindView(R.id.day_radioBtn)
- RadioButton dayButton;
- @BindView(R.id.month_radioBtn)
- RadioButton monthButton;
- @BindView(R.id.for_1)
- Spinner year_spinner;
- @BindView(R.id.for_2)
- Spinner day_spinner;
- @BindView(R.id.for_3)
- Spinner month_spinner;
- @BindView(R.id.spinner_lay1)
- RelativeLayout layout1;
- @BindView(R.id.spinner_lay2)
- RelativeLayout layout2;
- @BindView(R.id.spinner_lay3)
- RelativeLayout layout3;
- @BindView(R.id.prog1)
- SmoothProgressBar progressBar;
- @BindView(R.id.expenses_line_graph)
- LineChart expensesLineChart;
- @BindView(R.id.linegraph)
- LineChart salesLineChart;
- @BindView(R.id.x_title)
- TextView salesXTitle;
- @BindView(R.id.tvContent)
- TextView tvContent;
- @BindView(R.id.product_pie_chart)
- PieChart product_pieChart;
- @BindView(R.id.customer_pie_chart)
- PieChart customer_pieChart;
- @BindView(R.id.staff_pie_chart)
- PieChart staff_pieChart;
- String date, final_month;
- int yearCheck = 0;
- int monthCheck = 0;
- int dayCheck = 0;
- AccountSharedPreferences asp;
- String[] day_spinner_array;
- String[] month_spinner_array;
- Boolean isYear = true;
- Boolean isDay = true;
- Boolean isMonth = true;
- PeriodHelper monthPosition;
- AsyncHttpClient client;
- public static JSONArray getSortedListByDate(JSONArray array) throws JSONException {
- List<JSONObject> list = new ArrayList<JSONObject>();
- for (int i = 0; i < array.length(); i++) {
- list.add(0, array.getJSONObject(i));
- }
- Collections.sort(list, new SortBasedOnCreatedAt());
- JSONArray resultArray = new JSONArray(list);
- return resultArray;
- }
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_reports);
- ButterKnife.bind(this);
- setSupportActionBar(toolbar);
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
- getSupportActionBar().setTitle("Reports");
- toolbar.setNavigationIcon(com.duka.R.drawable.menu);
- sh = new SalesHandler(getApplicationContext());
- // sh.getSumOfGroupedTime();
- asp = new AccountSharedPreferences(this);
- monthPosition = new PeriodHelper();
- client = new AsyncHttpClient();
- createViews();
- }
- private void createViews() {
- setUpSpinners();
- /* sh.values();
- sh.hour_labels();*/
- //initialize MPChart
- /* ArrayList<String> hour_labels = new ArrayList<String>();
- ArrayList<Entry> values = new ArrayList<>();
- values.add(new Entry(5, 0));
- values.add(new Entry(2, 1));
- hour_labels.add(0, "Test1");
- hour_labels.add(0, "Test2");*/
- initializeSalesMPChart(sh.sales_values(), sh.hour_labels(), "hours");
- initializeProductPieChart(sh.products_values(), sh.product_labels());
- initializeCustomerPieChart(sh.customer_values(), sh.customer_labels());
- initializeStaffPieChart(sh.staff_values(), sh.staff_labels());
- // initializeExpensesMPChart(sh.values(), sh.hour_labels());
- }
- private void initializeSalesMPChart(ArrayList<Entry> values, ArrayList<String> labels, String period) {
- Log.d("report_api_", "api_request displaying in chart");
- CustomMarkerView mv = new CustomMarkerView(getApplicationContext(),
- R.layout.custom_marker_view_layout, "sales", labels, period);
- // set the marker to the chart
- salesLineChart.setMarkerView(mv);
- // mpChart.setOnChartGestureListener(this);
- // mpChart.setOnChartValueSelectedListener(this);
- // ArrayList<Entry> values = new ArrayList<>();
- //x,y
- /* values.add(new Entry(5, 10));
- values.add(new Entry(2, 4));
- values.add(new Entry(6, 10));
- values.add(new Entry(3, 1));
- values.add(new Entry(6, 10));
- values.add(new Entry(7, 13));
- values.add(new Entry(9, 7));*/
- LineDataSet report = new LineDataSet(values, "Records");
- /*report.setAxisDependency(YAxis.AxisDependency.LEFT);
- report.setColor(getResources().getColor(R.color.green_color));
- report.setCircleColor(Color.RED);
- report.setCircleColorHole(Color.RED);
- report.setCircleRadius(2f);
- report.setHighLightColor(Color.parseColor("#448AFF"));*/
- report.setColor(Color.parseColor("#758cbb"));
- // report.setColor(getResources().getColor(R.color.green_color));
- // report.setCircleColor(Color.BLACK);
- report.setCircleColor(Color.parseColor("#ffc755"));
- report.setLineWidth(3f);
- report.setCircleSize(3f);
- // report.setFillAlpha(10);
- report.setFillColor(Color.parseColor("#2d374c"));
- // report.setDrawCircles(true);
- // report.setValueTextSize(-5f);
- report.setValueTextSize(0f);
- ArrayList<ILineDataSet> dataSets = new ArrayList<>();
- dataSets.add(report);
- LineData data = new LineData(labels, dataSets);
- data.setValueFormatter(new CustomValueFormatter());
- XAxis xAxis = salesLineChart.getXAxis();
- xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
- xAxis.setTextSize(10f);
- xAxis.setDrawAxisLine(true);
- xAxis.setDrawGridLines(false);
- xAxis.setTextSize(9);
- // if (period.equals("hours")) {
- //
- // }
- // if (period.equals("days")) {
- // xAxis.setLabelsToSkip(1);
- // }
- // if (period.equals("months")) {
- //
- // }
- Legend l = salesLineChart.getLegend();
- l.setEnabled(false);
- //indicates if auto scaling on the y axis is enabled
- // salesLineChart.setAutoScaleMinMaxEnabled(true);
- salesLineChart.setDescription("");
- // if disabled, scaling can be done on x- and y-axis separately
- salesLineChart.setPinchZoom(true);
- salesLineChart.setDrawBorders(false);
- /*
- salesLineChart.setVisibleXRangeMinimum(4);*/
- salesLineChart.setBorderColor(getResources().getColor(R.color.grey));
- salesLineChart.setScaleEnabled(true);
- salesLineChart.setTouchEnabled(true);
- salesLineChart.setDragEnabled(true);
- salesLineChart.setDoubleTapToZoomEnabled(false);
- salesLineChart.getAxisLeft().setEnabled(true);
- salesLineChart.getAxisLeft().setTextColor(Color.parseColor("#6a84c3"));
- salesLineChart.getAxisRight().setEnabled(false);
- salesLineChart.getXAxis().setEnabled(true);
- salesLineChart.getXAxis().setTextColor(Color.parseColor("#6a84c3"));
- salesLineChart.animateXY(2000, 2000);
- salesLineChart.setNoDataTextDescription("No data available");
- //salesLineChart.invalidate();
- salesLineChart.notifyDataSetChanged();
- salesLineChart.invalidate();
- salesLineChart.setData(data);
- Log.d("array_report", "done setting sales to graph");
- }
- private void initializeExpensesMPChart(ArrayList<Entry> values, ArrayList<String> labels) {
- LineDataSet report = new LineDataSet(values, "Records");
- report.setColor(Color.parseColor("#758cbb"));
- report.setCircleColor(Color.parseColor("#ffc755"));
- report.setLineWidth(3f);
- report.setCircleSize(3f);
- report.setFillColor(Color.parseColor("#2d374c"));
- report.setValueTextSize(0f);
- ArrayList<ILineDataSet> dataSets = new ArrayList<>();
- dataSets.add(report);
- LineData data = new LineData(labels, dataSets);
- XAxis xAxis = expensesLineChart.getXAxis();
- xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
- xAxis.setTextSize(10f);
- xAxis.setDrawAxisLine(true);
- xAxis.setDrawGridLines(false);
- data.setValueFormatter(new CustomValueFormatter());
- Legend l = expensesLineChart.getLegend();
- l.setEnabled(false);
- expensesLineChart.setDescription("");
- // if disabled, scaling can be done on x- and y-axis separately
- expensesLineChart.setPinchZoom(true);
- expensesLineChart.setDrawBorders(false);
- /*
- salesLineChart.setVisibleXRangeMinimum(4);*/
- expensesLineChart.setBorderColor(getResources().getColor(R.color.grey));
- expensesLineChart.setScaleEnabled(true);
- expensesLineChart.setTouchEnabled(true);
- expensesLineChart.setDragEnabled(true);
- expensesLineChart.setDoubleTapToZoomEnabled(false);
- expensesLineChart.getAxisLeft().setEnabled(true);
- expensesLineChart.getAxisLeft().setTextColor(Color.parseColor("#6a84c3"));
- expensesLineChart.getAxisRight().setEnabled(false);
- expensesLineChart.getXAxis().setEnabled(true);
- expensesLineChart.getXAxis().setTextColor(Color.parseColor("#6a84c3"));
- expensesLineChart.animateXY(2000, 2000);
- expensesLineChart.setNoDataTextDescription("No data available");
- //salesLineChart.invalidate();
- expensesLineChart.notifyDataSetChanged();
- expensesLineChart.invalidate();
- expensesLineChart.setData(data);
- }
- private void initializeProductPieChart(ArrayList<Entry> p_entries, ArrayList<String> product_labels) {
- /* ArrayList<Entry> entries = new ArrayList<>();
- entries.add(new Entry(4f, 0));
- entries.add(new Entry(8f, 1));
- entries.add(new Entry(6f, 2));
- entries.add(new Entry(12f, 3));
- entries.add(new Entry(18f, 4));
- entries.add(new Entry(9f, 5));*/
- PieDataSet dataset = new PieDataSet(p_entries, "");
- /* ArrayList<String> labels = new ArrayList<String>();
- labels.add("January");
- labels.add("February");
- labels.add("March");
- labels.add("April");
- labels.add("May");
- labels.add("June");*/
- Legend l = product_pieChart.getLegend();
- product_pieChart.getLegend().setWordWrapEnabled(true);
- l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
- l.setXEntrySpace(7f);
- l.setYEntrySpace(0f);
- l.setYOffset(0f);
- PieData data = new PieData(product_labels, dataset);
- // add a lot of colors
- ArrayList<Integer> colors = new ArrayList<Integer>();
- for (int c : ColorTemplate.VORDIPLOM_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.PASTEL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.COLORFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.JOYFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.LIBERTY_COLORS)
- colors.add(c);
- colors.add(ColorTemplate.getHoloBlue());
- dataset.setColors(colors);
- // data.setValueTextSize(0);
- // dataset.setColors(getResources().getIntArray(R.array.androidcolors));
- dataset.setSliceSpace(0);
- data.setValueFormatter(new PercentagesValueFormatter());
- product_pieChart.setDragDecelerationFrictionCoef(0.95f);
- product_pieChart.setDescription("");
- product_pieChart.setUsePercentValues(true);
- product_pieChart.setData(data);
- product_pieChart.animateY(2000);
- product_pieChart.setDescriptionTextSize(0);
- product_pieChart.setDrawSliceText(false);
- }
- private void initializeCustomerPieChart(ArrayList<Entry> c_entries, ArrayList<String> customer_labels) {
- PieDataSet dataset = new PieDataSet(c_entries, "");
- /* ArrayList<String> labels = new ArrayList<String>();
- labels.add("January");
- labels.add("February");
- labels.add("March");
- labels.add("April");
- labels.add("May");
- labels.add("June");*/
- Legend l = customer_pieChart.getLegend();
- customer_pieChart.getLegend().setWordWrapEnabled(true);
- l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
- l.setXEntrySpace(7f);
- l.setYEntrySpace(0f);
- l.setYOffset(0f);
- PieData data = new PieData(customer_labels, dataset);
- // add a lot of colors
- ArrayList<Integer> colors = new ArrayList<Integer>();
- for (int c : ColorTemplate.VORDIPLOM_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.PASTEL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.COLORFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.JOYFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.LIBERTY_COLORS)
- colors.add(c);
- colors.add(ColorTemplate.getHoloBlue());
- colors.add(ColorTemplate.getHoloBlue());
- data.setValueFormatter(new PercentagesValueFormatter());
- dataset.setColors(colors);
- // dataset.setColors(getResources().getIntArray(R.array.androidcolors));
- // dataset.setColors(ColorTemplate.COLORFUL_COLORS); //
- customer_pieChart.setDescription("");
- customer_pieChart.setDragDecelerationFrictionCoef(0.95f);
- customer_pieChart.setDescription("");
- customer_pieChart.setUsePercentValues(true);
- customer_pieChart.setData(data);
- customer_pieChart.setDescriptionTextSize(0);
- customer_pieChart.setDrawSliceText(false);
- customer_pieChart.animateY(2000);
- }
- private void initializeStaffPieChart(ArrayList<Entry> entries, ArrayList<String> staff_labels) {
- PieDataSet dataset = new PieDataSet(entries, "");
- Legend l = staff_pieChart.getLegend();
- staff_pieChart.getLegend().setWordWrapEnabled(true);
- l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
- l.setXEntrySpace(7f);
- l.setYEntrySpace(0f);
- l.setYOffset(0f);
- PieData data = new PieData(staff_labels, dataset);
- // add a lot of colors
- ArrayList<Integer> colors = new ArrayList<Integer>();
- for (int c : ColorTemplate.VORDIPLOM_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.PASTEL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.COLORFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.JOYFUL_COLORS)
- colors.add(c);
- for (int c : ColorTemplate.LIBERTY_COLORS)
- colors.add(c);
- colors.add(ColorTemplate.getHoloBlue());
- colors.add(ColorTemplate.getHoloBlue());
- data.setValueFormatter(new PercentagesValueFormatter());
- dataset.setColors(colors);
- // dataset.setColors(getResources().getIntArray(R.array.androidcolors));
- // dataset.setColors(ColorTemplate.COLORFUL_COLORS); //
- staff_pieChart.setDescription("");
- staff_pieChart.setDragDecelerationFrictionCoef(0.95f);
- staff_pieChart.setDescription("");
- staff_pieChart.setUsePercentValues(true);
- staff_pieChart.setData(data);
- staff_pieChart.setDescriptionTextSize(0);
- staff_pieChart.setDrawSliceText(false);
- staff_pieChart.animateY(2000);
- }
- private void setUpSpinners() {
- //for year spinner
- yearSpinner();
- //for month spinner
- monthSpinner();
- //for day spinner
- daySpinner(true);
- }
- private void yearSpinner() {
- List<String> year_spinner_array = new ArrayList<>();
- Calendar c3 = Calendar.getInstance();
- c3.add(Calendar.MONTH, -1);
- c3.add(Calendar.DAY_OF_MONTH, -1);
- SimpleDateFormat mFormat3 = new SimpleDateFormat("yyyy", Locale.US);
- int year = Integer.parseInt(mFormat3.format(c3.getTime()));
- year_spinner_array.add(0, String.valueOf(year - 4));
- year_spinner_array.add(0, String.valueOf(year - 3));
- year_spinner_array.add(0, String.valueOf(year - 2));
- year_spinner_array.add(0, String.valueOf(year - 1));
- year_spinner_array.add(0, String.valueOf(year));
- ArrayAdapter<String> spinnerArrayAdapter3 = new ArrayAdapter<String>(this,
- R.layout.period_spinner_item, year_spinner_array);
- //selected item will look like a spinner set from XML
- spinnerArrayAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
- year_spinner.setAdapter(spinnerArrayAdapter3);
- year_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
- yearCheck = yearCheck + 1;
- if (yearCheck > 1) {
- // date = (String) adapterView.getItemAtPosition(i);
- if (isMonth && isYear) {
- if (isDay) {
- date = year_spinner.getSelectedItem() + "/"
- + month_spinner.getItemAtPosition(i) + "/"
- + day_spinner.getSelectedItem();
- getDataFrom(date, "months");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- } else {
- date = (String) adapterView.getItemAtPosition(i) + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
- getDataFrom(date, "months");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- } else {
- date = (String) adapterView.getItemAtPosition(i);
- getDataFrom(date, "months");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> adapterView) {
- }
- });
- }
- private void monthSpinner() {
- /* List<String> month_spinner_array = new ArrayList<>();
- Calendar c2 = Calendar.getInstance();
- c2.add(Calendar.MONTH, -1);
- c2.add(Calendar.DAY_OF_MONTH, -1);
- SimpleDateFormat mFormat2 = new SimpleDateFormat("MM", Locale.US);
- while (c2.before(Calendar.getInstance())) {
- month_spinner_array.add(0, mFormat2.format(c2.getTime()));
- c2.add(Calendar.DAY_OF_MONTH, 1);
- }
- */
- Calendar c2 = Calendar.getInstance();
- c2.add(Calendar.MONTH, 0);
- c2.add(Calendar.DAY_OF_MONTH, 0);
- SimpleDateFormat mFormat2 = new SimpleDateFormat("MMMM", Locale.US);
- String month = mFormat2.format(c2.getTime());
- if (month.startsWith("0")) {
- final_month = mFormat2.format(c2.getTime()).replace("0", "");
- } else {
- final_month = mFormat2.format(c2.getTime());
- }
- month_spinner_array = getResources().getStringArray(R.array.month_name_arrays);
- ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(this,
- R.layout.period_spinner_item, month_spinner_array);
- //selected item will look like a spinner set from XML
- spinnerArrayAdapter2.setDropDownViewResource(R.layout.period_spinner_dropdown_item);
- month_spinner.setAdapter(spinnerArrayAdapter2);
- month_spinner.setSelection(((ArrayAdapter) month_spinner.getAdapter()).getPosition(month));
- month_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
- monthCheck = monthCheck + 1;
- if (monthCheck > 1) {
- // date = (String) adapterView.getItemAtPosition(i);
- // daySpinner(false);
- if (isMonth && isYear) {
- if (isDay) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + day_spinner.getSelectedItem();
- getDataFrom(date, "days");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- } else {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
- getDataFrom(date, "days");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- }
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> adapterView) {
- }
- });
- }
- private void daySpinner(final boolean b) {
- Calendar c = Calendar.getInstance();
- c.add(Calendar.MONTH, -1);
- c.add(Calendar.DAY_OF_MONTH, 0);
- SimpleDateFormat mFormat = new SimpleDateFormat("dd", Locale.US);
- // while (c.before(Calendar.getInstance())) {
- //// day_spinner_array.add(0, mFormat.format(c.getTime()));
- // c.add(Calendar.DAY_OF_MONTH, 1);
- // }
- String today = mFormat.format(c.getTime());
- // if () {
- // day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- // }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("1")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("2")) {
- day_spinner_array = getResources().getStringArray(R.array.days_28_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("3")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("4")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("5")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("6")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("7")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("8")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("9")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("10")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("11")) {
- day_spinner_array = getResources().getStringArray(R.array.days_30_arrays);
- }
- if (monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()).equals("12")) {
- day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- }
- Log.d("month_position", monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()));
- // day_spinner_array = getResources().getStringArray(R.array.days_31_arrays);
- ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,
- R.layout.period_spinner_item, day_spinner_array);
- //
- // //selected item will look like a spinner set from XML
- spinnerArrayAdapter.setDropDownViewResource(R.layout.period_spinner_dropdown_item);
- day_spinner.setAdapter(spinnerArrayAdapter);
- day_spinner.setSelection(((ArrayAdapter) day_spinner.getAdapter()).getPosition(today));
- day_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
- if (b) {
- dayCheck = dayCheck + 1;
- if (dayCheck > 1) {
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + (String) adapterView.getItemAtPosition(i);
- getDataFrom(date, "hours");
- // Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
- }
- }
- }
- @Override
- public void onNothingSelected(AdapterView<?> adapterView) {
- }
- });
- }
- private void getDataFrom(String period, final String label) {
- Log.d("report_api_", "api_request made");
- client.cancelAllRequests(true);
- client.cancelRequests(getApplicationContext(), true);
- ConnectivityManager cm =
- (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
- boolean isConnected = activeNetwork != null &&
- activeNetwork.isConnectedOrConnecting();
- if (isConnected) {
- String url = getResources().getString(R.string.url) + "sales/" + period
- + "/api";
- RequestParams params = new RequestParams();
- client.addHeader("class", "Business");
- client.addHeader("attendant_name", asp.getAttendantName());
- client.addHeader("attendant_id", asp.getAttendantId());
- client.addHeader(getResources().getString(R.string.api_token), asp.getApiKey());
- client.get(url,
- params, new AsyncHttpResponseHandler() {
- @Override
- public void onStart() {
- Log.d("report_api_", "api_request started");
- progressBar.setVisibility(View.VISIBLE);
- }
- @Override
- public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
- String s = new String(responseBody);
- progressBar.setVisibility(View.INVISIBLE);
- Log.d("sale_reports_", s);
- try {
- Log.d("report_api_", "api_request successful");
- JSONObject objs = new JSONObject(s);
- HashMap<String, String> map = new HashMap<String, String>();
- Boolean success = objs.getBoolean("success");
- if (success) {
- JSONArray array = objs.getJSONArray("data");
- sh.setLabelType(label);
- new AsyncUpdateSalesToDisplayGraph(array, label).execute();
- } else {
- String failure = objs.getString("message");
- Crouton.makeText(
- Reports.this,
- failure,
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- } catch (JSONException e) {
- }
- }
- @Override
- public void onFailure(int statusCode, Header[] headers,
- byte[] responseBody, Throwable error) {
- progressBar.setVisibility(View.INVISIBLE);
- Log.d("something_went_wrong", String.valueOf(error));
- //errorDialog();
- Crouton.makeText(Reports.this, "Check your network connection",
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- }
- );
- } else {
- Crouton.makeText(Reports.this, "Check your network connection",
- Style.ALERT, com.duka.R.id.report_holder).show();
- }
- }
- public void onRadioButtonClicked(View view) {
- // Is the button now checked?
- boolean checked = ((RadioButton) view).isChecked();
- // Check which radio button was clicked
- switch (view.getId()) {
- case R.id.hour_radioBtn:
- if (checked) {
- dayButton.setChecked(false);
- monthButton.setChecked(false);
- layout1.setVisibility(View.VISIBLE);
- layout2.setVisibility(View.VISIBLE);
- layout3.setVisibility(View.VISIBLE);
- isDay = true;
- isMonth = true;
- isYear = true;
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem()) + "/"
- + day_spinner.getSelectedItem();
- getDataFrom(date, "hours");
- }
- break;
- case R.id.day_radioBtn:
- if (checked) {
- hourButton.setChecked(false);
- monthButton.setChecked(false);
- layout3.setVisibility(View.VISIBLE);
- layout1.setVisibility(View.VISIBLE);
- layout2.setVisibility(View.GONE);
- isDay = false;
- isMonth = true;
- isYear = true;
- date = year_spinner.getSelectedItem() + "/"
- + monthPosition.getMonthPostion("" + month_spinner.getSelectedItem());
- getDataFrom(date, "days");
- }
- break;
- case R.id.month_radioBtn:
- if (checked) {
- dayButton.setChecked(false);
- hourButton.setChecked(false);
- layout1.setVisibility(View.VISIBLE);
- layout2.setVisibility(View.GONE);
- layout3.setVisibility(View.GONE);
- isDay = false;
- isMonth = false;
- isYear = true;
- date = year_spinner.getSelectedItem() + "";
- getDataFrom(date, "months");
- }
- break;
- }
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // Handle action bar item clicks here. The action bar will
- // automatically handle clicks on the Home/Up button, so long
- // as you specify a parent activity in AndroidManifest.xml.
- int id = item.getItemId();
- //noinspection SimplifiableIfStatement
- if (id == android.R.id.home) {
- finish();
- // MainActivity ma = new MainActivity();
- // ma.openResideMenu();
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
- private String getDayFormatted(String dateStr) {
- DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- DateFormat writeFormat = new SimpleDateFormat("dd");
- Date date = null;
- try {
- date = readFormat.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- String formattedDate = writeFormat.format(date);
- return formattedDate;
- }
- private String getTimeFormattedInAMPM(String dateStr) {
- DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- DateFormat writeFormat = new SimpleDateFormat("ha");
- Date date = null;
- try {
- date = readFormat.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- String formattedDate = writeFormat.format(date);
- return formattedDate;
- }
- private String getMonthFormatted(String dateStr) {
- DateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- DateFormat writeFormat = new SimpleDateFormat("MMM ");
- Date date = null;
- try {
- date = readFormat.parse(dateStr);
- } catch (ParseException e) {
- e.printStackTrace();
- }
- String formattedDate = writeFormat.format(date);
- return formattedDate;
- }
- public static class SortBasedOnCreatedAt implements Comparator<JSONObject> {
- String CompareString1 = "", CompareString2 = "";
- /*
- * (non-Javadoc)
- *
- * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
- * lhs- 1st message in the form of json object. rhs- 2nd message in the form
- * of json object.
- */
- @Override
- public int compare(JSONObject lhs, JSONObject rhs) {
- try {
- // return Integer.valueOf(lhs.getString("created_at")) > Integer.valueOf(rhs.getString("created_at"))
- // ? 1 : (Integer.valueOf(lhs.getString("created_at")) < Integer.valueOf(rhs.getString("created_at")) ? -1 : 0);
- CompareString1 = lhs.getString("created_at"); //Key must be present in JSON
- CompareString2 = rhs.getString("created_at"); //Key must be present in JSON
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return CompareString1.compareTo(CompareString2);
- }
- }
- class AsyncUpdateSalesToDisplayGraph extends AsyncTask<Void, String, Void> {
- Activity activity;
- JSONArray sales;
- JSONObject sale_obj;
- ArrayList<Entry> sales_values_1 = new ArrayList<>();
- ArrayList<String> sales_labels_1 = new ArrayList<>();
- ArrayList<Entry> product_values_1 = new ArrayList<>();
- ArrayList<String> product_labels_1 = new ArrayList<>();
- ArrayList<Entry> customer_values_1 = new ArrayList<>();
- ArrayList<String> customer_labels_1 = new ArrayList<>();
- ArrayList<Entry> staff_values_1 = new ArrayList<>();
- ArrayList<String> staff_labels_1 = new ArrayList<>();
- ArrayList<Entry> sales_values;
- ArrayList<String> sales_labels;
- ArrayList<Entry> product_values;
- ArrayList<String> product_labels;
- ArrayList<Entry> customer_values;
- ArrayList<String> customer_labels;
- ArrayList<Entry> staff_values;
- ArrayList<String> staff_labels;
- ArrayList<String> sales_count;
- String label;
- public AsyncUpdateSalesToDisplayGraph(JSONArray sale, String label) throws JSONException {
- this.sales = getSortedListByDate(sale);
- this.label = label;
- }
- @Override
- protected void onPreExecute() {
- Crouton.makeText(
- Reports.this,
- "Processing the data...",
- Style.INFO, com.duka.R.id.report_holder).show();
- }
- @Override
- protected Void doInBackground(Void... params) {
- Log.d("array_report_track", "adding sales in background");
- JSONObject groupedSales = new JSONObject();
- JSONObject groupedProducts = new JSONObject();
- JSONObject groupedCustomers = new JSONObject();
- JSONObject groupedStaff = new JSONObject();
- JSONArray groupedSalesArray = new JSONArray();
- for (int i = 0; i < sales.length(); i++) {
- // for (int i = 0; i < getSortedListByDate(sales).length(); i++) {
- try {
- sale_obj = (JSONObject) sales.get(i);
- // sale_obj = (JSONObject) getSortedListByDate(sales).get(i);
- //sales
- if (label.equals("hours")) {
- String hour = getTimeFormattedInAMPM(sale_obj.getString("created_at"));
- int count = 1;
- if (groupedSales.has(hour)) {
- int current_count = groupedSales.getInt(hour); // read the current count
- count = Integer.valueOf(current_count) + 1; // increment by 1
- }
- groupedSales.put(hour, count);
- int index = Arrays.asList(sales_labels_1).indexOf(hour);
- if (index == 0) {
- sales_labels_1.add(hour);
- index = 1;
- }
- sales_values_1.add(new Entry(Float.valueOf(String.valueOf(count)), index));
- }
- if (label.equals("days")) {
- String day = getDayFormatted(sale_obj.getString("created_at"));
- int count = 1;
- if (groupedSales.has(day)) {
- int current_count = groupedSales.getInt(day); // read the current count
- count = Integer.valueOf(current_count) + 1; // increment by 1
- }
- groupedSales.put(day, count);
- sales_values_1.add(new Entry(Float.valueOf(String.valueOf(count)), i));
- sales_labels_1.add(day);
- }
- if (label.equals("months")) {
- String months = getMonthFormatted(sale_obj.getString("created_at"));
- // String months = "Jan";
- int count = 1;
- if (groupedSales.has(months)) {
- int current_count = groupedSales.getInt(months); // read the current count
- count = Integer.valueOf(current_count) + 1; // increment by 1
- }
- groupedSales.put(months, count);
- sales_values_1.add(new Entry(Float.valueOf(String.valueOf(count)), i));
- sales_labels_1.add(months);
- }
- //products
- String productName = sale_obj.getString("name");
- int quantity = Integer.parseInt(sale_obj.getString("quantity"));
- if (groupedProducts.has(productName)) {
- int current_quantity = groupedProducts.getInt(productName);
- // read the current count
- // increment by quantity
- quantity = current_quantity + Integer.parseInt(sale_obj.getString("quantity"));
- }
- groupedProducts.put(productName, quantity);
- Log.d("array_report_products", groupedProducts.toString());
- //customer
- String customerName = sale_obj.getString("customer_first_name") + " "
- + sale_obj.getString("customer_first_name");
- int customerQuantity = Integer.parseInt(sale_obj.getString("quantity"));
- if (groupedCustomers.has(customerName)) {
- int current_quantity = groupedCustomers.getInt(customerName); // read the current count
- // increment by the quantity
- customerQuantity = current_quantity + Integer.parseInt(sale_obj.getString("quantity"));
- }
- groupedCustomers.put(customerName, customerQuantity);
- Log.d("array_report_customer", groupedCustomers.toString());
- //staff
- String staffName = sale_obj.getString("attendant_name");
- double price = Double.parseDouble(sale_obj.getString("price"));
- if (groupedStaff.has(staffName)) {
- double current_price = groupedStaff.getDouble(staffName); // read the current count
- // increment by the price
- price = current_price + Double.parseDouble(sale_obj.getString("price"));
- }
- groupedStaff.put(staffName, price);
- Log.d("array_report_staff", groupedStaff.toString());
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- groupedSalesArray.put(groupedSales);
- Log.d("array_report_track", "done adding sales in background" + groupedSalesArray.toString());
- Log.d("array_report_sales", sales_labels_1.toString() + "///" + sales_values_1.toString());
- /*
- Type type = new TypeToken<Map<String, String>>() {
- }.getType();
- //sales loop
- Map<String, String> sales_map = new Gson().fromJson(String.valueOf(groupedSales), type);
- Log.d("gson_vals", sales_map.toString());
- int i = 0;
- for (Map.Entry<String, String> entry : sales_map.entrySet()) {
- String key = entry.getKey();
- sales_values_1.add(new Entry(Float.valueOf(String.valueOf(entry.getValue())), i));
- sales_labels_1.add(key);
- i++;
- }
- Log.d("array_report_track", "done adding sales to x and y");
- //products iterator
- Map<String, String> products_map = new Gson().fromJson(String.valueOf(groupedProducts), type);
- Log.d("gson_vals_products", products_map.toString());
- int i2 = 0;
- for (Map.Entry<String, String> entry : products_map.entrySet()) {
- String key = entry.getKey();
- product_values_1.add(new Entry(Float.valueOf(String.valueOf(entry.getValue())), i2));
- product_labels_1.add(entry.getValue() + " " + key);
- i2++;
- }
- Log.d("array_report_track", "done adding products to x and y");
- //customers iterator
- Map<String, String> customers_map = new Gson().fromJson(String.valueOf(groupedCustomers), type);
- Log.d("gson_vals_customers", customers_map.toString());
- int i3 = 0;
- for (Map.Entry<String, String> entry : customers_map.entrySet()) {
- String key = entry.getKey();
- customer_values_1.add(new Entry(Float.valueOf(String.valueOf(entry.getValue())), i3));
- customer_labels_1.add(entry.getValue() + " " + key);
- i3++;
- }
- Log.d("array_report_track", "done adding customers to x and y");
- //staff iterator
- DecimalFormat mFormat = new DecimalFormat("###,###,###");
- Map<String, String> staff_map = new Gson().fromJson(String.valueOf(groupedStaff), type);
- Log.d("gson_vals_staff", staff_map.toString());
- int i4 = 0;
- for (Map.Entry<String, String> entry : staff_map.entrySet()) {
- String key = entry.getKey();
- staff_values_1.add(new Entry(Float.valueOf(String.valueOf(entry.getValue())), i4));
- staff_labels_1.add(entry.getValue() + " " + key);
- i4++;
- }*/
- /* sales_values = sh.dateValues();
- sales_labels = sh.hour_labels();
- product_values = sh.date_products_values();
- product_labels = sh.product_labels();
- customer_values = sh.date_customer_values();
- customer_labels = sh.customer_labels();
- staff_values = sh.date_staff_values();
- staff_labels = sh.staff_labels();*/
- return null;
- }
- @Override
- protected void onPostExecute(Void unused) {
- Log.d("sum_sales_values_1", sales_values_1.toString() + "/" + sales_labels_1.toString());
- if (label.equals("hours")) {
- salesXTitle.setText("TIME");
- }
- if (label.equals("days")) {
- salesXTitle.setText("DATES");
- }
- if (label.equals("months")) {
- salesXTitle.setText("MONTHS");
- }
- initializeSalesMPChart(sales_values_1, sales_labels_1, label);
- /* initializeProductPieChart(product_values_1, product_labels_1);
- initializeCustomerPieChart(customer_values_1, customer_labels_1);
- initializeStaffPieChart(staff_values_1, staff_labels_1);*/
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement