LayoutCollector.getStartPageIndex(para) is throwing Null Pointer Exception on the first try, and returns result on retry

Hey, Please find my code below

    LayoutCollector lc = new LayoutCollector(doc);

    for (Paragraph para : paragraphs) {
            if (lc.getStartPageIndex(para) > pageNumber || para.isEndOfDocument()) {
               // some action
            }
    }

Here, lc.getStartPageIndex(para) s throwing Null Pointer Exception, i also tried evaluating lc.getStartPageIndex(paragraphs.get(0)) and lc.getStartPageIndex(paragraphs.get(1)) … etc

Every time when i evaluate first, it throws exception, but when i re-evaluate the same line it works fine.

It Does not happen with all the document.

PFAoriginal-upload (22).docx (6.5 MB)

@1623751199347 I was unable to reproduce the specified issue on the latest version of Aspose.Words with the following code

for (Paragraph para : document.getFirstSection().getBody().getParagraphs()) {
	int paraInd = lc.getStartPageIndex(para);
	System.out.println(paraInd);
	System.out.println(para.isEndOfDocument());
}

Could you please explain how you get paragraphs in your piece of code?

This is how i collect paragraphs

NodeCollection paragraphs = (NodeCollection) doc.getChildNodes(NodeType.PARAGRAPH, true);

i also tried with doc.getFirstSection().getBody().getParagraphs() , it throws exception, we are using aspose version 20.2

@1623751199347 Unfortunately, I was unable to reproduce the issue. Please try to run your code with the latest 22.1 version.

we dont have the latest version now, can you try it in my version and check the issue is reproducible ?

@1623751199347 Yes, on 20.2 release this error is reproduced.

Do you know why its happenin?
In Debug mode, when i try to evaluate the statement it errored with NPE, but when re-evaluate the same thing it is getting succeeded,

is there any workaround for this ?

@1623751199347 You can close LayoutCollector first call in try{} block and the second one in catch{}. But this is a weird workaround. I would recommend you to update to the newest version.

okay, i will do that…Thank you

Can you please provide an example here?

@ashishb888

LayoutCollector lc = new LayoutCollector(doc);
for (Paragraph para : paragraphs) {
  int paraInd;
  try{
    paraInd = lc.getStartPageIndex(para);
  } catch (Exception e)  {
    paraInd = lc.getStartPageIndex(para);
  }
  System.out.println(paraInd);
}

Once again, this is a weird workaround. I would recommend you to update to the newest version.

1 Like