Intellij Insertion of a block of code using PsiClass

Hi all,
I am trying to insert a code after a method. When I execute my code it gets inserted in the correct position but also at the end of my program it is getting added one more time.
This is my first project and I am stuck in clearing this bug for the past 3 days. Any solution for this will be helpful to me and Thanks in advance.

This is my code for adding:


//If matched I am adding it to the corresponding position:
private void generateNexpayHelper(PsiClass psiClass, PsiElement psiElement) {
StringBuilder builder = new StringBuilder("if (BILLING_STORE == \"NEXVA\") { \n");
builder.append("NexvaHelper = new NexvaXPayHelper (this, this);\n");
builder.append("NexvaHelper.startSetup();\n } \n");
PsiElement nexvaHelperElement = JavaPsiFacade.getElementFactory(psiClass.getProject()).createStatementFromText(builder.toString(), psiClass);
PsiElement method=psiClass.add(nexvaHelperElement);
psiClass.addAfter(nexvaHelperElement, psiElement.getParent().getParent().getContext());
JavaCodeStyleManager.getInstance(psiClass.getProject()).shortenClassReferences(method)

}

OTUPTUT:
//Inserting at correct position:

mHelper = new IabHelper (this,base64EncodedPublicKey);
if (BILLING_STORE == "NEXVA") {
NexvaHelper = new NexvaXPayHelper(this, this);
NexvaHelper.startSetup();
}


//Inserting at the end of program:

//End of program
}if (BILLING_STORE == "NEXVA") {
NexvaHelper = new NexvaXPayHelper(this, this);
NexvaHelper.startSetup();
}


One Error:
Throwable: Assertion failed: anchorBefore == null || anchorBefore.getTreeParent() == parent

Please sign in to leave a comment.