I am trying to create a constructor for a class
// Variables to send to Host
private class ParameterClass {
public String parameter;
public int value;
public Boolean sended;
}
public class SendToHostClass {
private int sizeBuffer;
public ParameterClass[] parameterList;
SendToHostClass(int sizeBufferConf) {
sizeBuffer = sizeBufferConf;
parameterList = new ParameterClass[sizeBuffer];
}
public void Put (String parameter, int valuePut, Boolean sendedPut) {
for (int index=0; index<sizeBuffer; index++) {
if (parameter == parameterList[index].parameter) {
parameterList[index].value = valuePut;
parameterList[index].sended = sendedPut;
exit();
}
}
}
}
so I declare the varible
SendToHostClass sendToHost;
and instantiate sendToHost in setup() Processing method using
sendToHost = new SendToHostClass(10);
sendToHost.parameterList[0].value = 0;
As I run the code, it returns me the error message
Exception in thread “Animation Thread” java.lang.NullPointerException
at sketch_gui.setup(sketch_gui.java:273) at
processing.core.PApplet.handleDraw(PApplet.java:2117) at
processing.opengl.PGL$PGLListener.display(PGL.java:2472) at
jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:548)
at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:533)
at
jogamp.opengl.GLAutoDrawableBase$2.run(GLAutoDrawableBase.java:280)
at
jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:904)
at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:822)
at com.jogamp.newt.opengl.GLWindow.display(GLWindow.java:543) at
processing.opengl.PGL.requestDraw(PGL.java:814) at
processing.opengl.PGraphicsOpenGL.requestDraw(PGraphicsOpenGL.java:1566)
at processing.core.PApplet.run(PApplet.java:2020) at
java.lang.Thread.run(Thread.java:662)
So what am I doing wrong?
I also discovered that if I instantiate each list object separately, it gives no error:
sendToHost = new SendToHostClass(10);
sendToHost.parameterList[0] = new ParameterClass();
sendToHost.parameterList[0].value = 0;
but it seems wrong, due to it looks that parameterList members are being instantiated twice.
Thanks in advance.
The above statement is only creating an array, but not initializing the array elements. The array elements are initialized by their default value, which is
null, in case you have the array of somecustom typeor some reference. So, you need to initialize the array elements separately using for loop.So, in your constructor you need to add a loop:
But of course, first you need to make your class
public, and prefer to make your fieldsprivateinstead ofpublic, and provide public accessors to make them accessible from outside.