Search code examples
javachartsapache-poiapache-poi-4

apache-poi 4.0 NullPointer for series setTitle


Exception in thread "main" java.lang.NullPointerException at org.apache.poi.xddf.usermodel.chart.XDDFChartData$Series.setTitle(XDDFChartData.java:122)

The code follows as below:

CellReference cellref = new CellReference("A6"); 

//A6 value = "My Title"

XDDFLineChartData.Series series3 = (XDDFLineChartData.Series)data.addSeries(xs, ys3);
series3.setMarkerSize((short) 6);
series3.setMarkerStyle(MarkerStyle.DIAMOND);

series3.setTitle("My Title",cellref);

I checked the documentation, it required a string for arg0 and a CellReference for arg1.

I keep ending up with a NullPointerException. Am I missing something??

Thanks for the replies.


Solution

  • To answer the question how to repair the bug in XDDFChartData.Series.setTitle:

    In XDDFChartData.Series.setTitle getSeriesText() is used without null check. But XDDFLineChartData.Series.getSeriesText() of course may return null since series.getTx() may return null. So we need make sure, that there is a series text element already before using XDDFChartData.Series.setTitle.

    ...
    XSSFChart chart = drawing.createChart(anchor);
    ...
    XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
    XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
    ...
    XDDFChartData data = chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
    data.addSeries(...);
    data.addSeries(...);
    chart.plot(data);
    
    if (chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).getTx() == null) 
     chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(0).addNewTx();
    data.getSeries().get(0).setTitle("Series 1 Title", null);
    
    if (chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(1).getTx() == null)
     chart.getCTChart().getPlotArea().getLineChartArray(0).getSerArray(1).addNewTx();
    data.getSeries().get(1).setTitle("Series 2 Title", null);
    ...
    //setting the axis Ids to the LineChart
    chart.getCTChart().getPlotArea().getLineChartArray(0).addNewAxId().setVal(bottomAxis.getId());
    chart.getCTChart().getPlotArea().getLineChartArray(0).addNewAxId().setVal(leftAxis.getId());
    ...