title: Passing data to custom view in Android
body: <p>I'm fairly new to Android and am trying to create a custom view to display a pie chart. I'm OK with Java and have written the pie chart code in iOS/Swift before.</p>
  
  <p>My problem is that the data doesn't appear to get passed as I had expected, or perhaps that the onDraw function is getting called before the data is set somehow from the superclass.</p>
  
  <p>I'd like to know the best method for passing data to be used in the onDraw function. So far, with a bit of help from posts like <a href="https://stackoverflow.com/questions/2884501/android-custom-view-constructor">Android Custom View Constructor</a> I've got the following code:</p>
  
  <pre><code>public PieChart(Context _context) {
      this(_context, null);
  }
  public PieChart(Context _context, AttributeSet _attrs) {
      this(_context, _attrs, null);
  }
  public PieChart(Context _context, AttributeSet _attrs, ArrayList&lt;ChartData&gt; _data) {
      super(_context, _attrs);
      if(this.isInEditMode()) {
          data = new ArrayList&lt;ChartData&gt;();
          data.add(new ChartData("Column A", 50));
          data.add(new ChartData("Column B", 75));
          data.add(new ChartData("Column C", 60));
      } else {
          data = _data;
      }
      context = _context;
      paint = new Paint();
      paint.setAntiAlias(true);
      paint.setStyle(Paint.Style.FILL);
      pieRectangle = new RectF(0,0,0,0);
      ...
  }
  </code></pre>
  
  <p>Which is called from my activity like this:</p>
  
  <pre><code>// create the chart
  PieChart pieChart = new PieChart(this, null, categoriesChartData);
  // add the chart to the linearLayout
  linearLayout.addView(pieChart);
  </code></pre>
  
  <p>And my PieChart.onDraw starts like this:</p>
  
  <pre><code>protected void onDraw(Canvas canvasChart) {
      Log.d(TAG, "Size of data = " + data.size()); // crashes here
      ...
  }
  </code></pre>
  
  <p>Note that in the interface designer, the pie chart looks great, so I know the onDraw method works, it's simply that the data isn't making it there when the app is ran. </p>
  
  <p>Rather than adding in extra functions and calls, as I don't have a lot of experience in Android, I'd like to ask the community what the problem is and what the best approach would be here.</p>
  
  <p>Many thanks in advance!</p>