Ejemplo n.º 1
0
  public LineGraph() {
    // Add datasets to multiple dataset
    mDataset.addSeries(dataset1);
    mDataset.addSeries(dataset2);

    // Customization time for line 1!
    renderer1.setColor(Color.BLUE);
    // renderer.setPointStyle(PointStyle.SQUARE);
    // renderer.setFillPoints(true);
    renderer1.setLineWidth(8);

    // Customization time for line 2!
    renderer2.setColor(Color.RED);
    // renderer.setPointStyle(PointStyle.SQUARE);
    // renderer.setFillPoints(true);
    renderer2.setLineWidth(8);

    // Enable Zoom
    // mRenderer.setZoomButtonsVisible(true);
    mRenderer.setXTitle("Time");
    mRenderer.setYTitle("Temp");

    mRenderer.setAxisTitleTextSize(20);
    mRenderer.setLabelsTextSize(20);
    // mRenderer.setLegendTextSize(30);
    mRenderer.setShowLegend(false);
    mRenderer.setYLabelsAlign(Align.LEFT);

    // Add renderers to multiple renderer
    mRenderer.addSeriesRenderer(renderer1);
    mRenderer.addSeriesRenderer(renderer2);

    mRenderer.setInScroll(true);
  }
Ejemplo n.º 2
0
 public void addSegment(View v) {
   mChartView.setOnClickListener(
       new View.OnClickListener() {
         public void onClick(View v) {}
       });
   mRenderer.setZoomEnabled(true);
   mRenderer.setZoomRate(mRenderer.getZoomRate() + 2);
   String seriesTitle = "Series " + (mDataset.getSeriesCount() + 1);
   // create a new series of data
   XYSeries series = new XYSeries(seriesTitle);
   mDataset.addSeries(series);
   mCurrentSeries = series;
   // create a new renderer for the new series
   XYSeriesRenderer renderer = new XYSeriesRenderer();
   mRenderer.addSeriesRenderer(renderer);
   // mRenderer.setZoomButtonsVisible(true);
   // set some renderer properties
   renderer.setPointStyle(PointStyle.CIRCLE);
   renderer.setFillPoints(true);
   renderer.setDisplayChartValues(true);
   renderer.setDisplayChartValuesDistance(40);
   mCurrentRenderer = renderer;
   mChartView.repaint();
   CustomDialog cdd = new CustomDialog(this);
   cdd.show();
 }
  private void initChart() {
    // 初始化,必须保证XYMultipleSeriesDataset对象中的XYSeries数量和
    // XYMultipleSeriesRenderer对象中的XYSeriesRenderer数量一样多
    line1 = new XYSeries("折线1");
    line2 = new XYSeries("折线2");
    renderer1 = new XYSeriesRenderer();
    renderer2 = new XYSeriesRenderer();
    mDataset = new XYMultipleSeriesDataset();
    mXYMultipleSeriesRenderer = new XYMultipleSeriesRenderer();

    // 对XYSeries和XYSeriesRenderer的对象的参数赋值
    // initLine(line1);
    // initLine(line2);
    initRenderer(renderer1, Color.GREEN, PointStyle.CIRCLE, true);
    initRenderer(renderer2, Color.CYAN, PointStyle.TRIANGLE, true);

    // 将XYSeries对象和XYSeriesRenderer对象分别添加到XYMultipleSeriesDataset对象和XYMultipleSeriesRenderer对象中。
    mDataset.addSeries(line1);
    mDataset.addSeries(line2);
    mXYMultipleSeriesRenderer.addSeriesRenderer(renderer1);
    mXYMultipleSeriesRenderer.addSeriesRenderer(renderer2);

    // 配置chart参数
    setChartSettings(mXYMultipleSeriesRenderer, "X", "Y", 0, 10, 0, 100, Color.RED, Color.WHITE);

    // 通过该函数获取到一个View 对象
    chart = ChartFactory.getLineChartView(this, mDataset, mXYMultipleSeriesRenderer);

    // 将该View 对象添加到layout中。
    dynamic_chart_line_layout.addView(
        chart, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
  }
Ejemplo n.º 4
0
    public void setValues(long time, int dBm, String ssid) {
      if (time > 300) {
        timeStart = System.nanoTime();
        time = 0;
        series.clear();
      }

      XYSeriesRenderer renderer = new XYSeriesRenderer();
      renderer.setColor(Color.BLUE);
      renderer.setDisplayBoundingPoints(true);

      renderer.setLineWidth(1);
      renderer.setPointStyle(PointStyle.CIRCLE);
      renderer.setPointStrokeWidth(1);

      XYSeries xySerieseries;

      if (series.containsKey(SERIES_KEY)) {
        xySerieseries = series.get(SERIES_KEY);
        xySerieseries.add(time, dBm);
        series.remove(SERIES_KEY);
        series.put(SERIES_KEY, xySerieseries);
      } else {
        xySerieseries = new XYSeries(ssid);
        xySerieseries.add(time, dBm);
        series.put(SERIES_KEY, xySerieseries);
      }

      mDataset.addSeries(0, xySerieseries);
      mRenderer.addSeriesRenderer(0, renderer);
    }
  private void initView(View view) {
    // TODO Auto-generated method stub
    mLightView = (TextView) view.findViewById(R.id.info_light_data);

    XYSeries series = new XYSeries("");
    mDataset.addSeries(series);
    mCurrentSeries = series;
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    mRenderer.addSeriesRenderer(renderer);
    renderer.setPointStyle(PointStyle.CIRCLE);
    renderer.setFillPoints(true);
    renderer.setDisplayChartValues(true);
    renderer.setDisplayChartValuesDistance(20);
    renderer.setChartValuesTextSize(15);
    mCurrentRenderer = renderer;

    // set data
    mCurrentSeries.clear();
    LinearLayout parentLayout = (LinearLayout) view.findViewById(R.id.chart_layout);
    mChartView = ChartFactory.getLineChartView(getActivity(), mDataset, mRenderer);
    parentLayout.addView(
        mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    // 平均值
    Date day = TimeController.getToday();
    day = TimeController.getDayDiffDay(-6, day);
    for (int i = 1; i <= 7; i++) {
      mRenderer.addXTextLabel(i, TimeController.getDayString(day));
      Integer light = getAverageLight(day);
      mCurrentSeries.add(i, light);
      day = TimeController.getTomorrow(day);
    }

    mChartView.repaint();
  }
Ejemplo n.º 6
0
 private void initDataset() {
   Log.d(TAG, "initDataset() is called");
   String[] titles = {"全厂"};
   for (int i = 0; i < titles.length; i++) {
     XYSeries series = new XYSeries(titles[i]);
     mDataset.addSeries(series);
   }
 }
  private static XYChart prepareChart(
      final double minValue,
      final double maxValue,
      @NotNull final Generic expression,
      @NotNull final Constant variable) {
    final MyXYSeries realSeries =
        new MyXYSeries(getRealFunctionName(expression, variable), DEFAULT_NUMBER_OF_STEPS * 2);
    final MyXYSeries imagSeries =
        new MyXYSeries(getImagFunctionName(variable), DEFAULT_NUMBER_OF_STEPS * 2);

    boolean imagExists =
        PlotUtils.addXY(
            minValue,
            maxValue,
            expression,
            variable,
            realSeries,
            imagSeries,
            false,
            DEFAULT_NUMBER_OF_STEPS);

    final XYMultipleSeriesDataset data = new XYMultipleSeriesDataset();
    data.addSeries(realSeries);
    if (imagExists) {
      data.addSeries(imagSeries);
    }

    final XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
    renderer.setShowGrid(true);
    renderer.setXTitle(variable.getName());
    renderer.setYTitle("f(" + variable.getName() + ")");
    renderer.setChartTitleTextSize(20);

    renderer.setZoomEnabled(true);
    renderer.setZoomButtonsVisible(true);

    renderer.addSeriesRenderer(createCommonRenderer());
    if (imagExists) {
      renderer.addSeriesRenderer(createImagRenderer());
    }

    return new CubicLineChart(data, renderer, 0.1f);
  }
 private XYMultipleSeriesDataset getCostsDataset() {
   XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
   for (Calculator curCalculator : calculatorList) {
     Calculation[] calculations = curCalculator.getCalculations();
     XYSeries existingCosts = new XYSeries("Without Solar - " + curCalculator.getName());
     XYSeries solarCosts = new XYSeries("With Solar - " + curCalculator.getName());
     for (Calculation curCalculation : calculations) {
       double annualCost =
           curCalculation.getTariff11Fee()
               * curCalculator.getCustomer().getElectricityUsage().getDailyAverageUsage()
               * 365;
       existingCosts.add(curCalculation.getYear(), annualCost);
       solarCosts.add(curCalculation.getYear(), annualCost - curCalculation.getAnnualSaving());
     }
     dataset.addSeries(existingCosts);
     dataset.addSeries(solarCosts);
   }
   return dataset;
 }
 private XYMultipleSeriesDataset getDemoDataset() {
   XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
   final int nr = 10;
   Random r = new Random();
   for (int i = 0; i < SERIES_NR; i++) {
     XYSeries series = new XYSeries("Demo series " + (i + 1));
     for (int k = 0; k < nr; k++) {
       series.add(k, 20 + r.nextInt() % 100);
     }
     dataset.addSeries(series);
   }
   return dataset;
 }
Ejemplo n.º 10
0
 /**
  * Builds a bar multiple series dataset using the provided values.
  *
  * @param titles the series titles
  * @param values the values
  * @return the XY multiple bar dataset
  */
 public XYMultipleSeriesDataset buildBarDataset(String[] titles, List<double[]> values) {
   XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
   int length = titles.length;
   for (int i = 0; i < length; i++) {
     CategorySeries series = new CategorySeries(titles[i]);
     double[] v = values.get(i);
     int seriesLength = v.length;
     for (int k = 0; k < seriesLength; k++) {
       series.add(v[k]);
     }
     dataset.addSeries(series.toXYSeries());
   }
   return dataset;
 }
 private XYMultipleSeriesDataset getDateDemoDataset() {
   XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
   final int nr = 10;
   long value = new Date().getTime() - 3 * TimeChart.DAY;
   Random r = new Random();
   for (int i = 0; i < SERIES_NR; i++) {
     TimeSeries series = new TimeSeries("Demo series " + (i + 1));
     for (int k = 0; k < nr; k++) {
       series.add(new Date(value + k * TimeChart.DAY / 4), 20 + r.nextInt() % 100);
     }
     dataset.addSeries(series);
   }
   return dataset;
 }
  private void getObservations(Integer patientId, String fieldName) {

    ClinicAdapter ca = new ClinicAdapter();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    ca.open();
    Cursor c = ca.fetchPatientObservation(patientId, fieldName);

    if (c != null && c.getCount() >= 0) {

      XYSeries series;
      if (mDataset.getSeriesCount() > 0) {
        series = mDataset.getSeriesAt(0);
        series.clear();
      } else {
        series = new XYSeries(fieldName);
        mDataset.addSeries(series);
      }

      int valueIntIndex = c.getColumnIndex(ClinicAdapter.KEY_VALUE_INT);
      int valueNumericIndex = c.getColumnIndex(ClinicAdapter.KEY_VALUE_NUMERIC);
      int encounterDateIndex = c.getColumnIndex(ClinicAdapter.KEY_ENCOUNTER_DATE);
      int dataTypeIndex = c.getColumnIndex(ClinicAdapter.KEY_DATA_TYPE);

      do {
        try {
          Date encounterDate = df.parse(c.getString(encounterDateIndex));
          int dataType = c.getInt(dataTypeIndex);

          double value;
          if (dataType == Constants.TYPE_INT) {
            value = c.getInt(valueIntIndex);
            series.add(encounterDate.getTime(), value);
          } else if (dataType == Constants.TYPE_DOUBLE) {
            value = c.getFloat(valueNumericIndex);
            series.add(encounterDate.getTime(), value);
          }
        } catch (ParseException e) {
          e.printStackTrace();
        }

      } while (c.moveToNext());
    }

    if (c != null) {
      c.close();
    }
    ca.close();
  }
Ejemplo n.º 13
0
 /**
  * Builds an XY multiple time dataset using the provided values.
  *
  * @param titles the series titles
  * @param xValues the values for the X axis
  * @param yValues the values for the Y axis
  * @return the XY multiple time dataset
  */
 public XYMultipleSeriesDataset buildDateDataset(
     String[] titles, List<Date[]> xValues, List<double[]> yValues) {
   XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
   int length = titles.length;
   for (int i = 0; i < length; i++) {
     TimeSeries series = new TimeSeries(titles[i]);
     Date[] xV = xValues.get(i);
     double[] yV = yValues.get(i);
     int seriesLength = xV.length;
     for (int k = 0; k < seriesLength; k++) {
       series.add(xV[k], yV[k]);
     }
     dataset.addSeries(series);
   }
   return dataset;
 }
Ejemplo n.º 14
0
  public LineGraph() {
    // Add single dataset to multiple dataset
    mDataset.addSeries(dataset);

    // Customization time for line 1!
    renderer.setColor(Color.WHITE);
    renderer.setPointStyle(PointStyle.SQUARE);
    renderer.setFillPoints(true);

    // Enable Zoom
    mRenderer.setZoomButtonsVisible(true);
    mRenderer.setXTitle("Day #");
    mRenderer.setYTitle("CM in Rainfall");

    // Add single renderer to multiple renderer
    mRenderer.addSeriesRenderer(renderer);
  }
Ejemplo n.º 15
0
 public void addXYSeries(
     XYMultipleSeriesDataset dataset,
     String[] titles,
     List<double[]> xValues,
     List<double[]> yValues,
     int scale) {
   int length = titles.length;
   for (int i = 0; i < length; i++) {
     XYSeries series = new XYSeries(titles[i], scale);
     double[] xV = xValues.get(i);
     double[] yV = yValues.get(i);
     int seriesLength = xV.length;
     for (int k = 0; k < seriesLength; k++) {
       series.add(xV[k], yV[k]);
     }
     dataset.addSeries(series);
   }
 }
Ejemplo n.º 16
0
  @Override
  public void onCreate(Bundle savedInstanceState) {

    // Test mode quickly generates a batch of fake points for testing the graph
    // future improvement will move this into a test section

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    super.onCreate(savedInstanceState);
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    status = new SelfClearingMessage(this);
    // TODO make this setting of x  DRY in eliminating it multiple places
    x = System.currentTimeMillis();

    setrotation();
    context = getApplicationContext();

    // for Achart engine
    series = new TimeSeries(title);
    eseries = new TimeSeries("Heart Efficiency");
    mDataset = new XYMultipleSeriesDataset();
    setContentView(R.layout.activity_main);
    mDataset.addSeries(series);

    // This handles the Bluetooth data from the Zephyr XxM BT
    zm = new ZephyrManager(this);

    // adds some random points if we need to test that the graph looks ok
    if (testmode) {
      for (int i = 0; i < 70; i++) {
        updateChart((int) (Math.random() * 1000 + 500));
      }
    }
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
  }
  private void initView(View view) {
    // TODO Auto-generated method stub
    mLightView = (TextView) view.findViewById(R.id.info_light_data);

    XYSeries series = new XYSeries("");
    mDataset.addSeries(series);
    mCurrentSeries = series;
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    mRenderer.addSeriesRenderer(renderer);
    renderer.setPointStyle(PointStyle.CIRCLE);
    renderer.setFillPoints(true);
    renderer.setDisplayChartValues(true);
    renderer.setDisplayChartValuesDistance(20);
    renderer.setChartValuesTextSize(15);
    mCurrentRenderer = renderer;

    // set data
    mCurrentSeries.clear();
    LinearLayout parentLayout = (LinearLayout) view.findViewById(R.id.chart_layout);
    mChartView = ChartFactory.getLineChartView(getActivity(), mDataset, mRenderer);
    parentLayout.addView(
        mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
  }
Ejemplo n.º 18
0
  private static XYMultipleSeriesDataset getDemoDataset() {

    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

    String DATE_FORMAT = "yyyy-MM-dd";
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);

    // Calcul Nbjt
    int nbjt = -1 * _DataPool.Param_nb_jour_graph();

    Cursor MinDateCursor = _OperationDbAdapter.MinDate();
    MinDateCursor.moveToFirst();
    if (MinDateCursor.getCount() > 0) {
      String MinDate = MinDateCursor.getString(0);

      long t1 = Calendar.getInstance().getTime().getTime();
      int diff;
      try {
        long t2 = sdf.parse(MinDate).getTime();
        diff = (int) (-1 * (t1 - t2) / (1000 * 60 * 60 * 24));
      } catch (ParseException e1) {
        diff = -999;
      }

      diff = diff - 1;

      if (diff > nbjt) {
        nbjt = diff;
      }
    } else {
      nbjt = -1;
    }

    Calendar c1 = Calendar.getInstance();
    c1.add(Calendar.DATE, nbjt);
    String dDate = sdf.format(c1.getTime());
    //

    //    Cursor SumAmountCursor = _OperationDbAdapter.SumAmount(dDate);
    Cursor SumAmountCursor = _OperationDbAdapter.SumAmount(dDate);
    SumAmountCursor.moveToFirst();

    XYSeries Zero = new XYSeries("Zero");

    int num_cpt;

    String pa;

    int count;
    if (SumAmountCursor.getCount() > 0) {

      for (int nbj = nbjt; nbj < 1; nbj++) {

        c1 = Calendar.getInstance();
        c1.add(Calendar.DATE, nbj);
        String dDate2 = sdf.format(c1.getTime());

        pa = "9999-12-31";
        if (!SumAmountCursor.isAfterLast()) {
          pa = SumAmountCursor.getString(1).trim();
        }

        String pb = dDate2.trim();
        while (pa.compareTo(pb) == 0) {
          num_cpt = ConstitutionNumCpt(SumAmountCursor.getString(2));
          MtduJour[num_cpt] = MtduJour[num_cpt] + Float.parseFloat(SumAmountCursor.getString(0));
          SumAmountCursor.moveToNext();

          pa = "9999-12-31";
          if (!SumAmountCursor.isAfterLast()) {
            pa = SumAmountCursor.getString(1).trim();
          }
        }

        // boucle de remplissage
        count = 0;
        while (count < 20) {
          if (Compte_Present[count] != null) {
            Mtsum[count] = Mtsum[count] + MtduJour[count];
            Mtbudget[count] = Mtbudget[count] + _DataPool.BudgetJour(Compte_Present[count]);
            MtBal[count] = Mtbudget[count] - Mtsum[count];

            Balance[count].add(nbj, MtBal[count]);
            MtduJour[count] = 0;
          }
          count++;
        }

        Zero.add(nbj, 0);
      }
    }

    dataset.addSeries(Zero);

    count = 0;
    while (count < 20) {
      if (Compte_Present[count] != null) {
        dataset.addSeries(Balance[count]);
      }
      count++;
    }

    MinDateCursor.close();
    SumAmountCursor.close();
    return dataset;
  }
Ejemplo n.º 19
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    Cursor settings;
    mDbHelper = new gasDbAdapter(getApplicationContext());
    mDbHelper.open();
    settings = mDbHelper.GetSettings();
    setContentView(R.layout.xy_chart);
    setTitle(R.string.analyze_d);
    mLayout = (LinearLayout) findViewById(R.id.chart);
    mDailyCost = (TextView) findViewById(R.id.avg_cost);

    if (settings.moveToFirst()) {
      dunits = settings.getString(settings.getColumnIndex(mDbHelper.KEY_DUNITS));
      cunits = settings.getString(settings.getColumnIndex(mDbHelper.KEY_CUNITS));
      funits = settings.getString(settings.getColumnIndex(mDbHelper.KEY_FUNITS));
      numVehicles = settings.getInt(settings.getColumnIndex(mDbHelper.KEY_VNUM));

      mVehicle = (Spinner) findViewById(R.id.vname_spinner);
      String[] columns = new String[] {mDbHelper.KEY_VNAME};
      int[] to = new int[] {android.R.id.text1};
      Cursor v = mDbHelper.getVehicles();
      SimpleCursorAdapter mAdapter =
          new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, v, columns, to);
      mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      Spinner spnVnames = (Spinner) findViewById(R.id.vname_spinner);
      spnVnames.setAdapter(mAdapter);
      spnVnames.setOnItemSelectedListener(SpinnerOnItemSelectedListener);

      mVehicle.setSelection(0); // set to first vehicle, spinner is 0-based Db is 1 based

    } else {
      // error - no settings
      Toast.makeText(
              this,
              getApplicationContext().getResources().getString(R.string.nosett_err),
              Toast.LENGTH_SHORT)
          .show();
      finish(); // no settings = no cars, no fuel, nothing to show. Get the hell out.
    }
    mDbHelper.close();

    // get the current date
    Calendar c = Calendar.getInstance();
    today = c.getTimeInMillis();

    String dmsunits = dunits.replace('s', ' ');
    costTitle = cunits + " / " + dmsunits;
    avgCostTitle = "Avg";
    mCurrentCostSeries = new XYSeries(costTitle);

    String fmsunits = funits.replace('s', ' ');
    effTitle = dunits + " / " + fmsunits;
    avgEffTitle = "Avg";
    mCurrentEffSeries = new XYSeries(effTitle, 1);

    mDataset.addSeries(mCurrentCostSeries);
    mDataset.addSeries(mCurrentEffSeries);
    mRenderer = new XYMultipleSeriesRenderer(2);

    setRenderer(mRenderer, colors, styles);
    int length = mRenderer.getSeriesRendererCount();
    for (int i = 0; i < length; i++) {
      XYSeriesRenderer r = (XYSeriesRenderer) mRenderer.getSeriesRendererAt(i);
      r.setLineWidth(3f);
    }

    mChartView = ChartFactory.getTimeChartView(this, mDataset, mRenderer, null);
    mChartView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
            double[] xy = mChartView.toRealPoint(0);
            if (seriesSelection == null) {
              //
            } else {
              String fs;
              Calendar c = Calendar.getInstance();
              c.setTimeInMillis((long) seriesSelection.getXValue());
              if (seriesSelection.getSeriesIndex() == 0) {
                fs = String.format("%.1f " + costTitle + " on %tD", seriesSelection.getValue(), c);
              } else {
                fs = String.format("%.1f " + effTitle + " on %tD", seriesSelection.getValue(), c);
              }
              Toast.makeText(AnalyzeFuel.this, fs, Toast.LENGTH_LONG).show();
            }
          }
        });

    mChartView.addZoomListener(
        new ZoomListener() {
          public void zoomApplied(ZoomEvent e) {
            String type = "out";
            if (e.isZoomIn()) {
              type = "in";
            }
            System.out.println("Zoom " + type + " rate " + e.getZoomRate());
          }

          public void zoomReset() {
            System.out.println("Reset");
          }
        },
        true,
        true);

    mChartView.addPanListener(
        new PanListener() {
          public void panApplied() {
            System.out.println(
                "New X range=["
                    + mRenderer.getXAxisMin()
                    + ", "
                    + mRenderer.getXAxisMax()
                    + "], Y range=["
                    + mRenderer.getYAxisMax()
                    + ", "
                    + mRenderer.getYAxisMax()
                    + "]");
          }
        });
  }
Ejemplo n.º 20
0
  public void AChart() {
    //		mDataset = new XYMultipleSeriesDataset();
    //		mRenderer = new XYMultipleSeriesRenderer();
    //		mCurrentRenderer = new XYSeriesRenderer();

    mRenderer.setApplyBackgroundColor(true); // 设置是否显示背景色
    mRenderer.setBackgroundColor(Color.argb(50, 214, 241, 255)); // 设置背景色

    mRenderer.setAxisTitleTextSize(32); // 设置轴标题文字的大小
    mRenderer.setAxesColor(Color.BLACK); // 坐标轴颜色

    mRenderer.setChartTitleTextSize(32); // ?设置整个图表标题文字大小
    mRenderer.setChartTitle(appState.userID);

    mRenderer.setXLabelsColor(Color.BLACK); // 设置X轴刻度颜色
    mRenderer.setYLabelsColor(0, Color.BLACK); // 设置Y轴刻度颜色	
    mRenderer.setLabelsTextSize(32); // 设置刻度显示文字的大小(XY轴都会被设置)

    mRenderer.setLegendTextSize(32); // 图例文字大小

    mRenderer.setMargins(new int[] {30, 30, 50, 10}); // 设置图表的外边框(上/左/下/右)
    mRenderer.setMarginsColor(Color.argb(50, 214, 241, 255)); // 边框颜色

    mRenderer.setZoomButtonsVisible(false); // 是否显示放大缩小按钮

    mRenderer.setShowGrid(true); // 显示网格

    mRenderer.setPointSize(10); // 设置点的大小(图上显示的点的大小和图例中点的大小都会被设置)

    String seriesTitle = "I-Sleep";

    if (mDataset.getSeriesCount() > 0) {
      mDataset.removeSeries(0);
      mRenderer.removeAllRenderers();
    }

    XYSeries series = new XYSeries(seriesTitle); // 定义XYSeries
    mDataset.addSeries(series); // 在XYMultipleSeriesDataset中添加XYSeries
    mCurrentSeries = series; // 设置当前需要操作的XYSeries  \	

    addPoint();

    XYSeriesRenderer renderer = new XYSeriesRenderer(); // 定义XYSeriesRenderer
    mRenderer.addSeriesRenderer(renderer); // 将单个XYSeriesRenderer增加到XYMultipleSeriesRenderer
    renderer.setPointStyle(PointStyle.CIRCLE); // 点的类型是圆形
    renderer.setFillPoints(true); // 设置点是否实心
    renderer.setColor(Color.BLUE); // 折线颜色

    mCurrentRenderer = renderer;

    //	    if (mChartView == null) {
    if (layout != null) {
      layout.removeAllViews();
    }
    layout = (LinearLayout) getActivity().findViewById(R.id.chart);
    mChartView =
        ChartFactory.getLineChartView(getActivity().getApplicationContext(), mDataset, mRenderer);
    mRenderer.setClickEnabled(true); // 设置图表是否允许点击
    mRenderer.setSelectableBuffer(100); // 设置点的缓冲半径值(在某点附件点击时,多大范围内都算点击这个点)
    mChartView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // 这段代码处理点击一个点后,获得所点击的点在哪个序列中以及点的坐标.
            // -->start
            SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
            double[] xy = mChartView.toRealPoint(0);
            if (seriesSelection == null) {
              //	              Toast.makeText(getActivity().getApplicationContext(), "No chart
              // element was clicked", Toast.LENGTH_SHORT).show();
            } else {
              //	              Toast.makeText(getActivity().getApplicationContext(),
              //	                  "Chart element in series index " +
              // seriesSelection.getSeriesIndex()
              //	                      + " data point index " + seriesSelection.getPointIndex() + "
              // was clicked"
              //	                      + " closest point value X=" + seriesSelection.getXValue() +
              // ", Y=" + seriesSelection.getValue()
              //	                      + " clicked point value X=" + (float) xy[0] + ", Y=" +
              // (float) xy[1], Toast.LENGTH_SHORT).show();

              //	              tv_graphdata.setText("X = " +
              // String.valueOf(seriesSelection.getXValue()) +
              //	            		  " Y = " + String.valueOf(seriesSelection.getValue()));
              tv_graphdata.setText(
                  appState.userID
                      + "  "
                      + appState.userName
                      + "  "
                      + "Duration:"
                      + duration[(int) seriesSelection.getXValue() - 1]
                      + "hours\n"
                      + "Starttime:"
                      + starttime[(int) seriesSelection.getXValue() - 1]
                      + "\n"
                      + "Endtime:"
                      + endtime[(int) seriesSelection.getXValue() - 1]);
              tv_graphdata.setTextSize(16);

              // 播放音频
              if (!"".equals(recfile[(int) seriesSelection.getXValue() - 1])) {
                playRecWithSysPlayer(recfile[(int) seriesSelection.getXValue() - 1]);
              } else {
                Toast.makeText(getActivity(), "There's no record.", Toast.LENGTH_LONG).show();
              }
            }
            // -->end
          }
        });
    mChartView.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            SeriesSelection seriesSelection = mChartView.getCurrentSeriesAndPoint();
            if (seriesSelection == null) {
              //	              Toast.makeText(XYChartBuilder.this, "No chart element was long
              // pressed",Toast.LENGTH_SHORT);
              return false; // no chart element was long pressed, so let something
              // else handle the event
            } else {
              //	              Toast.makeText(XYChartBuilder.this, "Chart element in series index "
              //	                  + seriesSelection.getSeriesIndex() + " data point index "
              //	                  + seriesSelection.getPointIndex() + " was long pressed",
              // Toast.LENGTH_SHORT);
              return true; // the element was long pressed - the event has been
              // handled
            }
          }
        });
    // 这段代码处理放大缩小
    // -->start
    mChartView.addZoomListener(
        new ZoomListener() {
          public void zoomApplied(ZoomEvent e) {
            String type = "out";
            if (e.isZoomIn()) {
              type = "in";
            }
            System.out.println("Zoom " + type + " rate " + e.getZoomRate());
          }

          public void zoomReset() {
            System.out.println("Reset");
          }
        },
        true,
        true);
    // -->end
    // 设置拖动图表时后台打印出图表坐标的最大最小值.
    mChartView.addPanListener(
        new PanListener() {
          public void panApplied() {
            System.out.println(
                "New X range=["
                    + mRenderer.getXAxisMin()
                    + ", "
                    + mRenderer.getXAxisMax()
                    + "], Y range=["
                    + mRenderer.getYAxisMax()
                    + ", "
                    + mRenderer.getYAxisMax()
                    + "]");
          }
        });
    layout.addView(
        mChartView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    boolean enabled = mDataset.getSeriesCount() > 0;
    //	      } else {
    //	        mChartView.repaint();
    //	      }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get local Bluetooth adapter
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    // If the adapter is null, then Bluetooth is not supported
    if (mBluetoothAdapter == null) {
      Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
      finish();
      return;
    }

    dispRunTime = (TextView) findViewById(R.id.dispRunTime);
    dispTemp = (TextView) findViewById(R.id.dispTemp);
    dispRoc = (TextView) findViewById(R.id.dispRoc);
    dispWRoC = (TextView) findViewById(R.id.dispTargRoc);
    dispMaxT = (TextView) findViewById(R.id.dispMaxTemp);
    alarmSet = (ZoomControls) findViewById(R.id.alarmSet);
    dispAlarmTemp = (TextView) findViewById(R.id.AlarmTemp);

    //		dispLogData = (ListView) findViewById(R.id.listLogData);
    //		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    //				android.R.layout.simple_list_item_1, logValues);
    //		setListAdapter(adapter);

    tempBar = (SeekBar) findViewById(R.id.tempBar);
    tempBar.setOnSeekBarChangeListener(this);
    tempBar.setMax(100);
    tempBar.setProgress(50);

    Log.v(TAG, "onCreate - add data");

    mDataset.addSeries(liveGraphXYSeries);
    Log.v(TAG, "onCreate - set render");

    mRenderer.setAxisTitleTextSize(14);
    mRenderer.setChartTitleTextSize(16);
    mRenderer.setLabelsTextSize(13);
    mRenderer.setLegendTextSize(13);
    mRenderer.setPointSize(5f);
    mRenderer.setMargins(new int[] {10, 20, 8, 10});
    // mRenderer.setXAxisMax(600);
    mRenderer.setYAxisMax(240);

    int[] colors = new int[] {Color.GREEN};
    PointStyle[] styles = new PointStyle[] {PointStyle.POINT};
    int length = colors.length;
    for (int i = 0; i < length; i++) {
      Log.v(TAG, "onCreate - add renderes");

      XYSeriesRenderer r = new XYSeriesRenderer();
      r.setColor(colors[i]);
      r.setPointStyle(styles[i]);
      mRenderer.addSeriesRenderer(r);
    }

    Button start = (Button) findViewById(R.id.ButtonStart);
    Button stop = (Button) findViewById(R.id.ButtonStop);
    Button reset = (Button) findViewById(R.id.buttonReset);
    Button acceptTemps = (Button) findViewById(R.id.buttonAcceptVariance);

    start.setOnClickListener(startClickHandler);
    stop.setOnClickListener(stopClickHandler);
    reset.setOnClickListener(resetClickHandler);
    acceptTemps.setOnClickListener(acceptTempsClickHandler);
    alarmSet.setOnZoomInClickListener(tempUpClickHandler);
    alarmSet.setOnZoomOutClickListener(tempDownClickHandler);

    Intent a = new Intent(this, TempService.class);
    startService(a);
    // Binding ..this block can also start service if not started already
    Intent bindIntent = new Intent(this, TempService.class);
    bindService(bindIntent, serviceConncetion, Context.BIND_AUTO_CREATE);
    // Register Broadcast Receiver
    IntentFilter filter = new IntentFilter(TempService.MYOWNACTIONFILTER);
    registerReceiver(myReceiver, filter);

    // Set our 'default' temp  - entire array is set so the average is what we expect.
    for (int i = 0; i < 5; i++) tempValues[i] = runTemp;

    // dispTemp.setText("Temp: " + String.valueOf(tempValues[0]));

    Log.v(TAG, "onCreate - main");

    if (mChartView == null) {
      Log.v(TAG, "onCreate - before chart layout");
      LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
      Log.v(TAG, "onCreate - before chart Factory");

      mChartView = ChartFactory.getLineChartView(this, mDataset, mRenderer);
      Log.v(TAG, "onCreate - before chart addview");
      layout.addView(
          mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    } else {
      mChartView.repaint();
    }

    final EditText edittext = (EditText) findViewById(R.id.simulateSpeed);
    edittext.setOnKeyListener(
        new OnKeyListener() {
          public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                && (keyCode == KeyEvent.KEYCODE_ENTER)) {
              // Perform action on key press
              currentSimulateSpeed = Integer.parseInt(edittext.getText().toString());
              tempUpdService.simluateMode(currentSimulateMode, currentSimulateSpeed);
              return true;
            }
            return false;
          }
        });
    final CheckBox checkbox = (CheckBox) findViewById(R.id.cSimulate);
    if (checkbox != null) {
      checkbox.setOnClickListener(
          new OnClickListener() {
            public void onClick(View v) {
              // Perform action on clicks, depending on whether it's now checked
              if (((CheckBox) v).isChecked()) {
                currentSimulateMode = true;
              } else {
                currentSimulateMode = false;
              }

              tempUpdService.simluateMode(currentSimulateMode, currentSimulateSpeed);
            }
          });
    }

    OnClickListener radio_listener =
        new OnClickListener() {
          public void onClick(View v) {
            // Perform action on clicks
            RadioButton rb = (RadioButton) v;
            Toast.makeText(Coffee2ohActivity.this, rb.getText(), Toast.LENGTH_SHORT).show();
            switch (v.getId()) {
              case R.id.runAuto:
                tempUpdService.setRunMode(TempService.RunModeAuto);
                break;
              case R.id.runOff:
                tempUpdService.setRunMode(TempService.RunModeStop);
                break;
              case R.id.runHold:
                tempUpdService.setRunMode(TempService.RunModeHold);
                break;
              case R.id.runManual:
                tempUpdService.setRunMode(TempService.RunModeManual);
                break;
            }
          }
        };

    final RadioButton rbAuto = (RadioButton) findViewById(R.id.runAuto);
    final RadioButton rbStop = (RadioButton) findViewById(R.id.runOff);
    final RadioButton rbHold = (RadioButton) findViewById(R.id.runHold);
    final RadioButton rbManual = (RadioButton) findViewById(R.id.runManual);
    rbAuto.setOnClickListener(radio_listener);
    rbManual.setOnClickListener(radio_listener);
    rbStop.setOnClickListener(radio_listener);
    if (rbHold != null) {
      rbHold.setOnClickListener(radio_listener);
    }
  } // End OnCreate
  private void updateChart() {
    String url = gConfig.URL.BASE_URL + "query_temperature";
    System.out.println("url: " + url);
    String xml_base = HttpUtil.queryStringForGet(url);
    System.out.println("HttpGet end");
    System.out.println("get xml: " + xml_base);
    if (xml_base.equals("error")) {
      Toast.makeText(app_query_temperature_Activity.this, "网络异常", Toast.LENGTH_SHORT).show();
    } else {
      try {
        // 创建一个SAXParserFactory
        SAXParserFactory factory = SAXParserFactory.newInstance();
        XMLReader reader = factory.newSAXParser().getXMLReader();
        // 将XMLReader设置内容处理器
        reader.setContentHandler(new ContentHandler_temperature());
        // 开始解析文件
        reader.parse(new InputSource(new StringReader(xml_base)));
      } catch (Exception e) {
        System.out.println("xml parse error");
        e.printStackTrace();
      }
    }

    series.clear();
    Cursor cursor =
        dbReadHandle.query(
            gConfig.testTableName, new String[] {"time", "value"}, null, null, null, null, null);
    java.util.Date date = new Date(0);
    Calendar cal = Calendar.getInstance();
    cal.get(Calendar.HOUR_OF_DAY); // 得到24小时机制的
    // date.get(Calendar.HOUR);// 得到12小时机制的

    while (cursor.moveToNext()) {
      String time_s = cursor.getString(cursor.getColumnIndex("time"));
      int time_i = Integer.parseInt(time_s); // 413,1352
      System.out.println("time_i: " + time_i);

      System.out.println(
          "time: "
              + "2013 "
              + (time_i / 1000000 + 1)
              + "."
              + time_i % 1000000 / 10000
              + " "
              + time_i % 10000 / 100
              + ":"
              + time_i % 100);
      cal.set(Calendar.YEAR, 2013);
      cal.set(Calendar.MONTH, time_i / 1000000);
      cal.set(Calendar.DATE, time_i % 1000000 / 10000);
      cal.set(Calendar.HOUR_OF_DAY, time_i % 10000 / 100);
      cal.set(Calendar.MINUTE, time_i % 100);

      date = cal.getTime();

      String yValue = cursor.getString(cursor.getColumnIndex("value"));
      // System.out.println("time: " + time + " value: " + value);
      // series.add(cursor.getPosition() * 10,
      // Double.parseDouble(yValue));
      series.add(date, Double.parseDouble(yValue));
      System.out.println("value_double: " + Double.parseDouble(yValue));
    }
    // 移除数据集中旧的点集
    mDataset.removeSeries(series);
    // 在数据集中添加新的点集
    mDataset.addSeries(series);
    // 视图更新,没有这一步,曲线不会呈现动态
    // 如果在非UI主线程中,需要调用postInvalidate(),具体参考api
    // chart.invalidate();
    mChartView.invalidate();

    //
    // // 设置好下一个需要增加的节点
    // addX = 0;
    // // addY = (int)(Math.random() * 90);
    // addY = (int) (Math.random() * 50);
    // // 移除数据集中旧的点集
    // mDataset.removeSeries(series);
    // // 判断当前点集中到底有多少点,因为屏幕总共只能容纳100个,所以当点数超过100时,长度永远是100
    // int length = series.getItemCount();
    // if (length > 100) {
    // length = 100;
    // }
    // // 将旧的点集中x和y的数值取出来放入backup中,并且将x的值加1,造成曲线向右平移的效果
    // for (int i = 0; i < length; i++) {
    // xv[i] = (int) series.getX(i) + 1;
    // yv[i] = (int) series.getY(i);
    // }
    // // 点集先清空,为了做成新的点集而准备
    // series.clear();
    // // 将新产生的点首先加入到点集中,然后在循环体中将坐标变换后的一系列点都重新加入到点集中
    // // 这里可以试验一下把顺序颠倒过来是什么效果,即先运行循环体,再添加新产生的点
    // series.add(addX, addY);
    // for (int k = 0; k < length; k++) {
    // series.add(xv[k], yv[k]);
    // }
    // // 在数据集中添加新的点集
    // mDataset.addSeries(series);
    //
    // // 视图更新,没有这一步,曲线不会呈现动态
    // // 如果在非UI主线程中,需要调用postInvalidate(),具体参考api
    // chart.invalidate();
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.app_temperature);

    dbHelper = new DBUtil(app_query_temperature_Activity.this, gConfig.db_Name, 1);
    dbWriteHandle = dbHelper.getWritableDatabase();
    dbReadHandle = dbHelper.getReadableDatabase();

    context = getApplicationContext();
    // 这里获得main界面上的布局,下面会把图表画在这个布局里面
    LinearLayout layout = (LinearLayout) findViewById(R.id.query_chart);

    // 这个类用来放置曲线上的所有点,是一个点的集合,根据这些点画出曲线
    // series = new XYSeries(title);
    series = new TimeSeries(title);

    // 创建一个数据集的实例,这个数据集将被用来创建图表
    mDataset = new XYMultipleSeriesDataset();

    // 将点集添加到这个数据集中
    mDataset.addSeries(series);

    // 以下都是曲线的样式和属性等等的设置,renderer相当于一个用来给图表做渲染的句柄
    int color = Color.GREEN;
    PointStyle style = PointStyle.TRIANGLE;
    // 设置好图表的样式
    renderer = buildRenderer(color, style, true);
    setChartSettings(renderer);

    // 生成图表
    // chart = ChartFactory.getLineChartView(context, mDataset, renderer);
    mChartView = ChartFactory.getTimeChartView(context, mDataset, renderer, "M/d HH:mm");

    // 折线被点击回调
    // mChartView.setOnTouchListener(chartViewOnTouchListener);
    // mChartView.setId(0);

    layout.removeAllViews(); // 先remove再add可以实现统计图更新
    // 将图表添加到布局中去
    layout.addView(
        mChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    // 这里的Handler实例将配合下面的Timer实例,完成定时更新图表的功能
    handler =
        new Handler() {
          @Override
          public void handleMessage(Message msg) {
            // 刷新图表
            updateChart();
            super.handleMessage(msg);
          }
        };
    task =
        new TimerTask() {
          public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
          }
        };
    // 1秒后开始进行定时器调度,5秒为循环周期
    timer.schedule(task, 1, 5 * 1000);
  }
  private void setupTopChart() {

    // Creating an  XYSeries for Sound
    visitsSeries = new XYSeries("");
    secondSeries = new XYSeries("");

    // Creating a dataset to hold each series
    dataset = new XYMultipleSeriesDataset();
    Sdataset = new XYMultipleSeriesDataset();

    // Adding Visits Series to the dataset
    dataset.addSeries(visitsSeries);
    Sdataset.addSeries(secondSeries);

    // Adding datasets together
    multiDateSet = new XYMultipleSeriesDataset();
    multiDateSet.addSeries(visitsSeries);
    multiDateSet.addSeries(secondSeries);

    // Creating XYSeriesRenderer to customize visitsSeries
    visitsRenderer = new XYSeriesRenderer();
    visitsRenderer.setColor(getResources().getColor(R.color.colorAccent));
    visitsRenderer.setPointStyle(PointStyle.CIRCLE);
    visitsRenderer.setFillPoints(true);
    visitsRenderer.setDisplayChartValues(false);
    visitsRenderer.setLineWidth(10);

    // Creating a XYMultipleSeriesRenderer to customize the whole chart
    multiRenderer = new XYMultipleSeriesRenderer();

    multiRenderer.setMargins(new int[] {0, 0, 0, 0});
    multiRenderer.setPanEnabled(false);
    multiRenderer.setShowLegend(false);
    multiRenderer.setChartTitle("");
    // multiRenderer.setFitLegend(true);

    // Eliminate the S***e
    multiRenderer.setApplyBackgroundColor(true);
    multiRenderer.setXTitle("");
    multiRenderer.setShowLabels(false);
    multiRenderer.setShowAxes(false);

    multiRenderer.setMarginsColor(Color.TRANSPARENT);
    multiRenderer.setBackgroundColor(Color.TRANSPARENT);
    multiRenderer.setXLabelsColor(Color.TRANSPARENT);
    multiRenderer.setYLabelsColor(0, Color.TRANSPARENT);
    multiRenderer.setGridColor(Color.TRANSPARENT);
    multiRenderer.setXLabelsPadding(0);
    multiRenderer.setYLabelsPadding(0);
    multiRenderer.setBarWidth(100);

    // Establish Beginning Dimensions
    multiRenderer.setXAxisMin(0);
    multiRenderer.setXAxisMax(10);
    multiRenderer.setYAxisMin(0);
    multiRenderer.setYAxisMax(0);

    // Make the bar graphs touching
    multiRenderer.setBarSpacing(0);

    // Adding visitsRenderer to multipleRenderer
    // Note: The order of adding dataseries to dataset and renderers to multipleRenderer
    // should be same
    multiRenderer.addSeriesRenderer(visitsRenderer);
    multiRenderer.addSeriesRenderer(visitsRenderer);

    // Getting a reference to LinearLayout of the RecordActivity Layout
    LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chartTop);

    mChart =
        (GraphicalView)
            ChartFactory.getBarChartView(
                getBaseContext(),
                multiDateSet,
                multiRenderer,
                org.achartengine.chart.BarChart.Type.DEFAULT);

    // Adding the Line Chart to the LinearLayout
    chartContainer.addView(mChart);
  }
Ejemplo n.º 25
0
  @Override
  protected void onStart() {
    // TODO Auto-generated method stub
    super.onStart();

    try {
      elec_thread.join();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    int k = CH.getNum_of_msg(); // 보여줄 데이터 개수

    Log.d("get", "onStart시작");

    int seriesLength = 0;
    double max = 0;

    recv_packet = new Packet[k];

    for (int i = 0; i < k; i++) {
      recv_packet[i] = CH.get_Packet(i);
    }
    Log.d("get", "recv_packet배열 저장");

    List<Float[]> values = new ArrayList<Float[]>();
    Float[][] a = new Float[4][k];
    int[][] c = new int[4][k];

    for (int j = 0; j < k; j++) {
      a[0][j] = Float.parseFloat(recv_packet[j].getData(3));
      a[1][j] = Float.parseFloat(recv_packet[j].getData(4));
      a[2][j] = Float.parseFloat(recv_packet[j].getData(5));
      a[3][j] = Float.parseFloat(recv_packet[j].getData(7));
      c[0][j] = (int) (a[0][j] * 10);
      c[1][j] = (int) (a[1][j] * 10);
      c[2][j] = (int) (a[2][j] * 10);
      c[3][j] = (int) (a[3][j] * 10);
      a[0][j] = ((float) c[0][j] / (float) 10);
      a[1][j] = ((float) c[1][j] / (float) 10);
      a[2][j] = ((float) c[2][j] / (float) 10);
      a[3][j] = ((float) c[3][j] / (float) 10);

      // a[3][j] = (float) Math.round(Float.parseFloat(recv_packet[j].getData(7))*10000)/10000;
      // values.add(a);// 이번달
    }
    for (int w = 0; w < 4; w++) {
      //        a[w] = Math.round(a[w]*10) / 10.0;
      values.add(a[w]);
    }

    Log.d("get", "values배열 저장");
    XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();

    renderer.setChartTitle("과거 사용량과의 비교");
    renderer.setChartTitleTextSize(50);

    String[] titles = new String[] {"3달 전", "2달 전", "1달 전", "이번 달"};

    int[] colors =
        new int[] {
          Color.rgb(255, 90, 217),
          Color.rgb(54, 255, 255),
          Color.rgb(255, 255, 72),
          Color.rgb(83, 255, 76)
        };
    // //////////////////////////////////////////////////////
    //   renderer.setLegendTextSize(35);

    int length = values.size(); // 항목갯수

    Log.d("get", "legnth : " + length);
    for (int i = 0; i < length; i++) {
      SimpleSeriesRenderer r = new SimpleSeriesRenderer();
      r.setColor(colors[i]);
      renderer.addSeriesRenderer(r);
    }

    renderer.setXTitle("제품별");
    renderer.setYTitle("사용량");
    renderer.setAxisTitleTextSize(28);
    renderer.setMarginsColor(Color.WHITE);

    renderer.setLabelsTextSize(20);
    renderer.setLegendHeight(200);
    renderer.setXAxisMin(0.5);
    // renderer.setXAxisMax(length + 0.5); // 장비 갯수 +0.5
    renderer.setYAxisMin(0);

    renderer.setLabelsColor(Color.BLACK);
    renderer.setBackgroundColor(Color.WHITE);

    // 그래프 위에 값 표시하기
    for (int i = 0; i < length; i++) {
      renderer.getSeriesRendererAt(i).setDisplayChartValues(true);
      renderer.getSeriesRendererAt(i).setChartValuesTextAlign(Align.RIGHT);
      renderer.getSeriesRendererAt(i).setChartValuesTextSize(20);
    }
    Log.d("get", "그래프위값 표시하기");

    renderer.setYLabels(5);

    // x,y축 정렬 방향
    renderer.setXLabelsAlign(Align.CENTER);
    renderer.setYLabelsAlign(Align.CENTER);
    renderer.setPanEnabled(true, true); // x,y축 스크롤 여부 on/off
    renderer.setZoomEnabled(true); // zoom기능 on/off
    renderer.setZoomRate(1.0f);
    renderer.setBarSpacing(0.5f);

    Log.d("get", "xy축 정렬 방향");

    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
    for (int i = 0; i < titles.length; i++) {
      CategorySeries series = new CategorySeries(titles[i]);
      Float[] v = values.get(i);

      Log.d("get", "int i = 0; i < titles.length; i++");

      seriesLength = v.length;
      renderer.setXAxisMax(seriesLength + 0.5);

      for (int q = 0; q < seriesLength; q++) {
        series.add(v[q]);
        if (max < v[q]) {
          max = v[q];
        }
        // Log.d("Test", "series.add : " + v[q]);
        renderer.setXLabels(seriesLength + 1);
      }
      dataset.addSeries(series.toXYSeries());
    }
    Log.d("get", "111111111");
    String[] x_name = new String[seriesLength];
    for (int b = 0; b < k; b++) {
      x_name[b] = recv_packet[b].getData(2);
    }
    Log.d("get", "222222222");
    renderer.setXLabels(0);
    for (int i = 0; i < seriesLength; i++) {
      renderer.addXTextLabel(i + 1, x_name[i]);
    }
    renderer.setYAxisMax(max + (max * 0.1)); // max 찾아서 넣기
    GraphicalView gv = ChartFactory.getBarChartView(this, dataset, renderer, Type.DEFAULT);

    setContentView(gv);
  }
Ejemplo n.º 26
0
  public static View genBarChart(final Activity activity, final BarChartData data) {
    if (data == null || data.getData() == null) return null;
    Resources resources = activity.getResources();
    final String[] axis_x_string = resources.getStringArray(R.array.week);
    final XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
    XYMultipleSeriesDataset dataSet = new XYMultipleSeriesDataset();
    renderer.setApplyBackgroundColor(true);
    renderer.setBackgroundColor(Color.WHITE);
    renderer.setMarginsColor(Color.WHITE);
    renderer.setTextTypeface(null, Typeface.NORMAL);

    renderer.setShowGrid(true);
    renderer.setGridColor(resources.getColor(R.color.gray3));

    renderer.setLabelsColor(Color.BLACK);
    renderer.setAxesColor(resources.getColor(R.color.gray1));
    renderer.setBarSpacing(0.5);

    renderer.setXTitle("");
    renderer.setYTitle("");
    renderer.setXLabelsColor(Color.BLACK);
    renderer.setLabelsTextSize(
        activity.getResources().getDimensionPixelSize(R.dimen.ov_statistics_axis_text_size));
    renderer.setYLabelsColor(0, Color.BLACK);
    renderer.setXLabelsPadding(resources.getDimension(R.dimen.ov_statistics_x_axis_padding));
    renderer.setYLabelsPadding(resources.getDimension(R.dimen.ov_statistics_x_axis_padding));
    renderer.setXLabelsAlign(Paint.Align.CENTER);
    renderer.setYLabelsAlign(Paint.Align.CENTER);
    renderer.setXLabelsAngle(0);
    renderer.setShowTickMarks(false);

    renderer.setXLabels(0);
    renderer.setYAxisMin(0);

    for (int i = 0; i < data.getData().length; i++) {
      final XYSeries series = new XYSeries("");
      dataSet.addSeries(series);
      XYSeriesRenderer yRenderer = new XYSeriesRenderer();
      renderer.addSeriesRenderer(yRenderer);
      yRenderer.setColor(resources.getColor(data.sColorId[i]));
      series.add(0, 0);
      renderer.addXTextLabel(0, "");
      for (int j = 0; j < data.getData()[i].length; j++) {
        renderer.addXTextLabel(j + 1, axis_x_string[j]);
        series.add(j + 1, ((float) data.getData()[i][j]) / 3600000);
      }
      series.add(data.getData()[i].length + 1, 0);
      renderer.addXTextLabel(data.getData()[i].length + 1, "");
    }

    renderer.setZoomEnabled(false);
    renderer.setZoomEnabled(false, false);
    renderer.setClickEnabled(true);
    renderer.setPanEnabled(false);
    renderer.setShowLegend(false);
    try {
      renderer.setDrawGridAfterBar(true);
      renderer.setHighLightRectEnabled(true);
      renderer.setHighLightRectStrokeWidth(
          activity
              .getResources()
              .getDimensionPixelOffset(R.dimen.ov_statistics_highlight_stroke_width));
      renderer.setHighLightRectStrokeColor(activity.getResources().getColor(R.color.gray3));
    } catch (NoSuchMethodError e) {
      e.printStackTrace();
    }
    View view = ChartFactory.getBarChartView(activity, dataSet, renderer, BarChart.Type.DEFAULT);
    view.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (!(v instanceof GraphicalView)) return;
            final GraphicalView view = (GraphicalView) v;
            SeriesSelection selection = view.getCurrentSeriesAndPoint();
            try {
              view.onClick(selection);
            } catch (NoSuchMethodError e) {
              e.printStackTrace();
            }
            if (selection == null) return;
            int idx = selection.getPointIndex() - 1;
            View popupView = activity.getLayoutInflater().inflate(R.layout.bar_chart_popup, null);
            if (data.from.equals(CaseOverviewFragment.class.getSimpleName())
                || data.from.equals(EquipmentOverviewFragment.class.getSimpleName())) {
              ((TextView) popupView.findViewById(R.id.date)).setText(data.getDate()[idx]);
              if (data.getData()[0][idx] >= 0) {
                int hour = (int) data.getData()[0][idx] / 3600000;
                int min = (int) ((data.getData()[0][idx] % 3600000)) / 60000;
                ((TextView) popupView.findViewById(R.id.working_time))
                    .setText(
                        activity.getResources().getString(R.string.statistics_popup_time_finish)
                            + " "
                            + (hour < 10 ? ("0" + hour) : hour)
                            + " : "
                            + (min < 10 ? ("0" + min) : min));
              } else {
                popupView.findViewById(R.id.vg_working_time).setVisibility(View.GONE);
              }
              popupView.findViewById(R.id.vg_overtime).setVisibility(View.GONE);
            } else if (data.from.equals(WorkerOverviewFragment.class.getSimpleName())) {
              ((TextView) popupView.findViewById(R.id.date)).setText(data.getDate()[idx]);
              if (data.getData()[0][idx] >= 0) {
                int hour = (int) data.getData()[0][idx] / 3600000;
                int min = (int) ((data.getData()[0][idx] % 3600000)) / 60000;
                ((TextView) popupView.findViewById(R.id.working_time))
                    .setText(
                        activity.getResources().getString(R.string.statistics_popup_time_work)
                            + " "
                            + (hour < 10 ? ("0" + hour) : hour)
                            + " : "
                            + (min < 10 ? ("0" + min) : min));
              } else {
                popupView.findViewById(R.id.vg_working_time).setVisibility(View.GONE);
              }
              if (data.getData()[1][idx] >= 0) {
                int hour = (int) data.getData()[1][idx] / 3600000;
                int min = (int) ((data.getData()[1][idx] % 3600000)) / 60000;
                ((TextView) popupView.findViewById(R.id.overtime))
                    .setText(
                        activity.getResources().getString(R.string.statistics_popup_time_overtime)
                            + " "
                            + (hour < 10 ? ("0" + hour) : hour)
                            + " : "
                            + (min < 10 ? ("0" + min) : min));
              } else {
                popupView.findViewById(R.id.vg_overtime).setVisibility(View.GONE);
              }
            }
            final PopupWindow popup =
                new PopupWindow(
                    popupView,
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            popup.setBackgroundDrawable(new BitmapDrawable());
            popup.setOutsideTouchable(true);
            popup.setOnDismissListener(
                new PopupWindow.OnDismissListener() {
                  @Override
                  public void onDismiss() {
                    try {
                      view.onClick(null);
                    } catch (NoSuchMethodError e) {
                      e.printStackTrace();
                    }
                  }
                });
            /* calculate popup position */
            popupView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            int[] dateChooserLocations = new int[2];
            (activity.findViewById(R.id.ov_statistics_week_chooser))
                .getLocationOnScreen(dateChooserLocations);
            int[] statisticsViewLocations = new int[2];
            v.getLocationOnScreen(statisticsViewLocations);
            int[] barChartLocations = new int[2];
            v.getLocationOnScreen(barChartLocations);
            int x_pos =
                barChartLocations[0]
                    + (int) ((XYChart) view.getChart()).getXAxisPos((double) (idx + 1))
                    - popupView.getMeasuredWidth() / 2;
            int y_base =
                dateChooserLocations[1]
                    + (activity.findViewById(R.id.ov_statistics_week_chooser)).getMeasuredHeight();
            int y_pos =
                (statisticsViewLocations[1] - y_base) / 2
                    + y_base
                    - popupView.getMeasuredHeight() / 2;
            popup.showAtLocation(v, Gravity.NO_GRAVITY, x_pos, y_pos);
          }
        });
    return view;
  }
Ejemplo n.º 27
0
  /** Called when the fragment is first created. */
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ScrollView view = (ScrollView) inflater.inflate(R.layout.clima, container, false);

    context = getActivity();
    ((MainActivity) context).setFooter(R.id.footer_sensor);

    RelativeLayout row1 = (RelativeLayout) view.findViewById(R.id.temp);
    RelativeLayout row2 = (RelativeLayout) view.findViewById(R.id.humi);
    RelativeLayout row3 = (RelativeLayout) view.findViewById(R.id.baro);

    Animation animation = AnimationUtils.loadAnimation(context, R.anim.push_top_in);
    row1.startAnimation(animation);
    row2.startAnimation(animation);
    row3.startAnimation(animation);

    humidity = (TextView) view.findViewById(R.id.humidity);
    barometric = (TextView) view.findViewById(R.id.barometric);
    temperature = (TextView) view.findViewById(R.id.temperature);

    app = (Node) context.getApplication();
    sensor = app.getSensor();

    // Tempurature
    LinearLayout chart1 = (LinearLayout) view.findViewById(R.id.chart1);

    tempRenderer = Node.getGraphStyle(tempRenderer, context);

    tempChartView = ChartFactory.getLineChartView(context, tempDataset, tempRenderer);

    chart1.addView(
        tempChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    tempChartView.repaint();

    tempSeries = new XYSeries("temp");
    tempDataset.addSeries(tempSeries);
    XYSeriesRenderer renderer1 = new XYSeriesRenderer();
    tempRenderer.addSeriesRenderer(renderer1);
    // renderer.setPointStyle(PointStyle.CIRCLE);
    // renderer.setFillPoints(true);
    renderer1.setLineWidth(4);
    renderer1.setColor(Color.RED);

    tempArray = new ArrayList<Double>();

    // Humidity
    LinearLayout chart2 = (LinearLayout) view.findViewById(R.id.chart2);

    humiRenderer = Node.getGraphStyle(humiRenderer, context);

    humiChartView = ChartFactory.getLineChartView(context, humiDataset, humiRenderer);

    chart2.addView(
        humiChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    humiChartView.repaint();

    humiSeries = new XYSeries("humi");
    humiDataset.addSeries(humiSeries);
    XYSeriesRenderer renderer2 = new XYSeriesRenderer();
    humiRenderer.addSeriesRenderer(renderer2);
    // renderer.setPointStyle(PointStyle.CIRCLE);
    // renderer.setFillPoints(true);
    renderer2.setLineWidth(4);
    renderer2.setColor(Color.RED);

    humiArray = new ArrayList<Double>();

    // Pressure
    LinearLayout chart3 = (LinearLayout) view.findViewById(R.id.chart3);

    presRenderer = Node.getGraphStyle(presRenderer, context);

    presChartView = ChartFactory.getLineChartView(context, presDataset, presRenderer);

    chart3.addView(
        presChartView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    presChartView.repaint();

    presSeries = new XYSeries("pres");
    presDataset.addSeries(presSeries);
    XYSeriesRenderer renderer3 = new XYSeriesRenderer();
    presRenderer.addSeriesRenderer(renderer3);
    // renderer.setPointStyle(PointStyle.CIRCLE);
    // renderer.setFillPoints(true);
    renderer3.setLineWidth(4);
    renderer3.setColor(Color.RED);

    presArray = new ArrayList<Double>();

    return view;
  }
Ejemplo n.º 28
0
  private void openChart() {

    String[] chartTitles;
    chartTitles = new String[] {"Total"};
    List<double[]> values = new ArrayList<double[]>();
    values.add(mStatsDataDaysList.getDataDoubleArray());
    int totalXlength = 0;

    XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

    List<double[]> xAxisValues = new ArrayList<double[]>();
    xAxisValues.add(mStatsDataDaysList.getXDoubleArray());

    for (int i = 0; i < chartTitles.length; i++) {
      XYSeries series = new XYSeries(chartTitles[i]);
      double[] xV = xAxisValues.get(i);
      double[] yV = values.get(i);
      int seriesLength = xV.length;
      for (int k = 0; k < seriesLength; k++) {
        System.out.println("LOG X is " + xV[k] + " y is " + yV[k]);
        series.add(xV[k] - 1, yV[k]);
      }
      dataset.addSeries(series);
    }

    XYSeriesRenderer incomeRenderer = new XYSeriesRenderer();
    incomeRenderer.setColor(Color.WHITE);
    incomeRenderer.setPointStyle(PointStyle.CIRCLE);
    incomeRenderer.setFillPoints(true);
    incomeRenderer.setDisplayChartValues(true);
    incomeRenderer.setDisplayChartValuesDistance(15);
    incomeRenderer.setDisplayBoundingPoints(false); // for hiding the series when we scroll

    // Creating a XYMultipleSeriesRenderer to customize the whole chart
    XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
    multiRenderer.setChartTitle(getString(R.string.my_mined_km_history));
    multiRenderer.setXTitle(getString(R.string.days));
    multiRenderer.setYTitle(getString(R.string.km));
    multiRenderer.setZoomButtonsVisible(true);
    multiRenderer.setBackgroundColor(0xf7f7f7);
    multiRenderer.setMarginsColor(0xf7f7f7);
    multiRenderer.setMargins(new int[] {50, 60, 60, 30});

    multiRenderer.setXLabelsAlign(Align.CENTER);
    multiRenderer.setYLabelsAlign(Align.RIGHT);
    multiRenderer.setPanEnabled(true, false); // scroll only x axis so true
    multiRenderer.setZoomEnabled(ZOOM_X, false);

    multiRenderer.setPointSize(8); // increase the width of point size
    multiRenderer.setXLabelsPadding(10);

    if (Utils.getScreenDendity(this) > DisplayMetrics.DENSITY_HIGH) {
      multiRenderer.setAxisTitleTextSize(20);
      multiRenderer.setChartTitleTextSize(25);
      multiRenderer.setLabelsTextSize(20);
      multiRenderer.setPointSize(8);
      incomeRenderer.setLineWidth(4);
      incomeRenderer.setChartValuesTextSize(20);
    } else {
      multiRenderer.setAxisTitleTextSize(12);
      multiRenderer.setChartTitleTextSize(18);
      multiRenderer.setLabelsTextSize(12);
      multiRenderer.setPointSize(5);
      incomeRenderer.setLineWidth(2);
      incomeRenderer.setChartValuesTextSize(15);
    }

    xyValues = new LinkedHashMap<Integer, String>();

    for (int i = 0; i < chartTitles.length; i++) {
      double[] xV = xAxisValues.get(i);
      totalXlength = xV.length;
      System.out.println("LOG len is " + totalXlength);
      for (int j = 0; j < totalXlength; j++) {
        multiRenderer.addXTextLabel(j + 1, Utils.addDays(xV[j], mInitialDateUser));
        xyValues.put(j + 1, Utils.addDays(xV[j], mInitialDateUser));
      }
    }

    multiRenderer.setXLabels(0);
    multiRenderer.setShowAxes(false);

    multiRenderer.setXAxisMin(totalXlength - 5);
    multiRenderer.setXAxisMax(totalXlength + 1);

    if (totalXlength <= X_AXIS_MAX) {
      multiRenderer.setXAxisMin(0);
      multiRenderer.setXAxisMax(totalXlength);
    }

    multiRenderer.setPanEnabled(true);
    multiRenderer.setPanLimits(new double[] {0, totalXlength + 1, 0, 0});

    multiRenderer.setYAxisMin(Utils.getMinValueFromList(values));
    multiRenderer.setYAxisMax(Utils.getMaxValueFromList(values));
    multiRenderer.setAxesColor(Color.GRAY);
    multiRenderer.setLabelsColor(Color.WHITE);
    multiRenderer.addSeriesRenderer(incomeRenderer);

    // Creating a Time Chart
    mChartView2 =
        (GraphicalView)
            ChartFactory.getTimeChartView(getBaseContext(), dataset, multiRenderer, "dd-MMM-yyyy");

    multiRenderer.setClickEnabled(true);
    multiRenderer.setSelectableBuffer(10);

    // Setting a click event listener for the graph
    mChartView2.setOnClickListener(
        new View.OnClickListener() {

          @Override
          public void onClick(View v) {

            SeriesSelection seriesSelection = mChartView2.getCurrentSeriesAndPoint();
            double[] xy = mChartView2.toRealPoint(0);

            if (seriesSelection != null) {

              //                  debug
              Log.d("Punto", seriesSelection.getXValue() + ", " + seriesSelection.getValue());
              //                  debug
              Log.d(
                  "Chart point",
                  "Chart element in series index "
                      + seriesSelection.getSeriesIndex()
                      + " data point index "
                      + seriesSelection.getPointIndex()
                      + " was clicked"
                      + " closest point value X="
                      + seriesSelection.getXValue()
                      + ", Y="
                      + seriesSelection.getValue()
                      + " clicked point value X="
                      + (float) xy[0]
                      + ", Y="
                      + (float) xy[1]);

              Toast.makeText(
                      getBaseContext(),
                      ""
                          + xyValues.get((int) seriesSelection.getXValue())
                          + " , "
                          + seriesSelection.getValue()
                          + " "
                          + getString(R.string.km),
                      Toast.LENGTH_SHORT)
                  .show();
            }
          }
        });

    // Adding the Line Chart to the LinearLayout
    mLayoutChart2.addView(mChartView2);
  }
  /**
   * Executes the chart demo.
   *
   * @param context the context
   * @return the built intent
   */
  public Intent execute(Context context) {
    String[] titles = new String[] {"Crete Air Temperature", "Skiathos Air Temperature"};
    List<double[]> x = new ArrayList<double[]>();
    for (int i = 0; i < titles.length; i++) {
      x.add(new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12});
    }
    List<double[]> values = new ArrayList<double[]>();
    values.add(
        new double[] {12.3, 12.5, 13.8, 16.8, 20.4, 24.4, 26.4, 26.1, 23.6, 20.3, 17.2, 13.9});
    values.add(new double[] {9, 10, 11, 15, 19, 23, 26, 25, 22, 18, 13, 10});
    int[] colors = new int[] {Color.GREEN, Color.rgb(200, 150, 0)};
    PointStyle[] styles = new PointStyle[] {PointStyle.CIRCLE, PointStyle.DIAMOND};
    XYMultipleSeriesRenderer renderer = buildRenderer(colors, styles);
    renderer.setPointSize(5.5f);
    int length = renderer.getSeriesRendererCount();

    for (int i = 0; i < length; i++) {
      XYSeriesRenderer r = (XYSeriesRenderer) renderer.getSeriesRendererAt(i);
      r.setLineWidth(5);
      r.setFillPoints(true);
    }
    setChartSettings(
        renderer,
        "Weather data",
        "Month",
        "Temperature",
        0.5,
        12.5,
        0,
        40,
        Color.LTGRAY,
        Color.LTGRAY);

    renderer.setXLabels(12);
    renderer.setYLabels(10);
    renderer.setShowGrid(true);
    renderer.setXLabelsAlign(Align.RIGHT);
    renderer.setYLabelsAlign(Align.RIGHT);
    renderer.setZoomButtonsVisible(true);
    renderer.setPanLimits(new double[] {-10, 20, -10, 40});
    renderer.setZoomLimits(new double[] {-10, 20, -10, 40});

    XYValueSeries sunSeries = new XYValueSeries("Sunshine hours");
    sunSeries.add(1, 35, 4.3);
    sunSeries.add(2, 35, 4.9);
    sunSeries.add(3, 35, 5.9);
    sunSeries.add(4, 35, 8.8);
    sunSeries.add(5, 35, 10.8);
    sunSeries.add(6, 35, 11.9);
    sunSeries.add(7, 35, 13.6);
    sunSeries.add(8, 35, 12.8);
    sunSeries.add(9, 35, 11.4);
    sunSeries.add(10, 35, 9.5);
    sunSeries.add(11, 35, 7.5);
    sunSeries.add(12, 35, 5.5);
    XYSeriesRenderer lightRenderer = new XYSeriesRenderer();
    lightRenderer.setColor(Color.YELLOW);

    XYSeries waterSeries = new XYSeries("Water Temperature");
    waterSeries.add(1, 16);
    waterSeries.add(2, 15);
    waterSeries.add(3, 16);
    waterSeries.add(4, 17);
    waterSeries.add(5, 20);
    waterSeries.add(6, 23);
    waterSeries.add(7, 25);
    waterSeries.add(8, 25.5);
    waterSeries.add(9, 26.5);
    waterSeries.add(10, 24);
    waterSeries.add(11, 22);
    waterSeries.add(12, 18);
    renderer.setBarSpacing(0.5);
    XYSeriesRenderer waterRenderer = new XYSeriesRenderer();
    waterRenderer.setColor(Color.argb(250, 0, 210, 250));

    XYMultipleSeriesDataset dataset = buildDataset(titles, x, values);
    dataset.addSeries(0, sunSeries);
    dataset.addSeries(0, waterSeries);
    renderer.addSeriesRenderer(0, lightRenderer);
    renderer.addSeriesRenderer(0, waterRenderer);
    waterRenderer.setDisplayChartValues(true);
    waterRenderer.setChartValuesTextSize(10);

    String[] types =
        new String[] {BarChart.TYPE, BubbleChart.TYPE, LineChart.TYPE, CubicLineChart.TYPE};
    Intent intent =
        ChartFactory.getCombinedXYChartIntent(
            context, dataset, renderer, types, "Weather parameters");
    return intent;
  }
Ejemplo n.º 30
0
  // the zephry manager will send RR values to this listener.
  // RRs are the milliseconds between beats.  Example, steady 60 BPM heartbeat sends rr values of
  // 1000 because there is a full second between beats
  public void updateChart(int rr) {

    // we throw out any 0s or absurd values.  We have found this tends not to happen with a good
    // chest strap
    if ((rr < 1) || (rr > 3000)) return;
    int pulserate = 60000 / rr;
    series.add(x, pulserate);
    x = x + rr; // time is also the accumulation of RR values

    // Achartengine stuff
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

    // Set the right side to current time
    mRenderer.setXAxisMax(x);

    // set the left side to one minute earlier 60000 miliseconds
    mRenderer.setXAxisMin(x - 60000);

    mRenderer.setYAxisMin(MIN_HEART_RATE);
    mRenderer.setYAxisMax(MAX_HEART_RATE);

    mRenderer.setLabelsTextSize(LABELTEXTSIZE);
    renderer.setFillPoints(true);
    renderer.setLineWidth(2);

    renderer.setPointStyle(style);
    mRenderer.setShowLegend(false);
    mRenderer.setChartTitle(title);
    mRenderer.setShowGrid(true);
    mRenderer.setGridColor(gridcolor);
    mRenderer.setXLabels(11);
    mRenderer.setYLabels(5);

    mRenderer.setAxisTitleTextSize(25);
    mRenderer.setChartTitleTextSize(30);
    mRenderer.setLabelsTextSize(20);
    mRenderer.setLegendTextSize(15);
    mRenderer.setPointSize(2f);
    mRenderer.setMargins(new int[] {20, 30, 15, 0});

    mRenderer.setYLabelsAlign(Align.RIGHT);
    mDataset.removeSeries(0);

    mDataset.addSeries(series);

    renderer.setColor(linecolor);
    context = getApplicationContext();
    mRenderer.setApplyBackgroundColor(true);
    mRenderer.setBackgroundColor(bgcolor);
    mRenderer.addSeriesRenderer(renderer);

    chartview = ChartFactory.getTimeChartView(context, mDataset, mRenderer, null);
    chartview.invalidate();
    ((TextView) findViewById(R.id.heartratelabel)).setText("HR:" + pulserate);

    chartview.repaint();

    FrameLayout chartlayout = (FrameLayout) findViewById(R.id.chartlayout);
    chartlayout.removeAllViewsInLayout();

    chartlayout.addView(
        chartview,
        new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT));

    status
        .checkForClear(); // this needs to be done time to time regularly so statuses are not stuck
                          // on.
  }