Null pointer exception from List in constructor parameter - java

I'm creating a class that has a List of objects as a constructor parameter, but I'll getting a null pointer exception when I try to use the initialized List. My class
public class ControlUnit {
private List<Sensor> sensors;
public void constructor(List<Sensor> sensorList) {
sensors = sensorList;
}
public void pollSensors() {
for (Sensor sensor : sensors) {
System.out.println("do something");
}
}
}
used like this:
List<Sensor> sensors = new ArrayList<Sensor>();
sensors.add(new FireSensor());
sensors.add(new SmokeSensor());
ControlUnit unit = new ControlUnit();
unit.pollSensors();
and I'm getting the error
java.lang.NullPointerException
at ControlUnit.pollSensors(ControlUnit.java:15)
What am I missing in my constructor?

The constructor is defined completely wrong. Check the following code snippet.
public class ControlUnit {
private List<Sensor> sensors;
public ControlUnit(List<Sensor> sensorList) {
sensors = sensorList;
}
public void pollSensors() {
for (Sensor sensor : sensors) {
System.out.println("do something");
}
}
}
And use it like this.
List<Sensor> sensors = new ArrayList<Sensor>();
sensors.add(new FireSensor());
sensors.add(new SmokeSensor());
ControlUnit unit = new ControlUnit(sensors);
unit.pollSensors();

public void constructor(List<Sensor> sensorList) {
This is not a constructor declaration. You need
public ControlUnit(List<Sensor> sensorList) {
and then call it with the list you want to use.

You're constructing your class wrongly.
A constructor in Java takes the form of a method with the name of the class and without any return type:
public ControlUnit(List<Sensor> sensorList) { ... }

You need to pass the list to the object when creating an instance of it as a parameter so like this: ControlUnit unit = new ControlUnit(sensors); and also change the constructor method to
public ControlUnit(List<Sensor> sensorList) {
sensors = sensorList;
}

For your class ControlUnit you have not got a constructor, so the Idea which you use will generate an empty constructor for your class that you call when you initialize your ControlUnit object here: ControlUnit unit = new ControlUnit()
So you will not initialize your List<Sensor> sensors list and you will not be able to iterate through it because it is pointing to null.
In order to do it properly, you have to write your constructor in the right way like this:
public class ControlUnit {
private List<Sensor> sensors;
public void pollSensors() {
for (Sensor sensor : sensors) {
System.out.println("do something");
}
}
public void ControlUnit (List<Sensor> sensorList) {
sensors = sensorList;
}
}
Your constructor method has to be the same name as your class.
When you call new ControlUnit(), you will call that constructor. But in this case, you have a parameter there, so we have to pass it at the calling like this: ControlUnit unit = new ControlUnit(sensors);
So when the constructor will run, it will assign the value to your list, so you can iterate through it.

Related

Efficient Way to Pass an Object Parameter in Java Method

I'm just looking some another efficient way to pass an object parameter to method.
So I have some method like this:
private void dashboardMenu() {
Dashboard dashboard = new Dashboard();
body.removeAll();
body.add(dashboard);
dashboard.setSize(body.getWidth(), body.getHeight());
dashboard.setVisible(true);
}
private void dataMenu() {
Data data = new Data();
body.removeAll();
body.add(data);
data.setSize(body.getWidth(), body.getHeight());
data.setVisible(true);
}
And I want an efficient method to call between this two method with object parameter (dashboard = new Dashboard(), and data = new Data()).
What I think it should be like this for example:
private void dasboardMenu() {
navigateMenu(Type object);
}
private void dataMenu() {
navigateMenu(Type object);
}
private void navigateMenu(Type object) {
object menu = new object();
body.removeAll();
body.add(menu);
menu.setSize(body.getWidth(), body.getHeight());
menu.setVisible(true);
}
Is it possible to do that?
Please give me an example. I don't even know what keyword should I do.
How about this (assuming your Dashboard and Data are Swing Components)?
private void dashboardMenu() {
navigateMenu(new Dashboard());
}
private void dataMenu() {
navigateMenu(new Data());
}
private void navigateMenu(JComponent c) {
body.removeAll();
body.add(c);
c.setSize(body.getWidth(), body.getHeight());
c.setVisible(true);
}

Java callback (in another class) to populate private member

Please forgive my Java syntax as I am a Java beginner.
I have 3 classes Main, Tool, ToolResultCallback.
class Main {
private DataList dl;
public doSomething() {
Tool t = new Tool();
ToolResultCallback TRC = new ToolResultCallback();
t.startSomething(TRC);
}
}
// in separate file
class Tool {
public void startSomething(ToolResultCallback TRC) {
}
}
// in separate file
class ToolResultCallback extends AbstractTRC {
#Override
public onEvent(SomeData d) {
// how to populate DataList of Main?
}
}
How do I populate DataList dl from callback function in another class/ file?
Pass dl to the ToolResultCallback constructor, and store it in a field.
Thanks #tgdavies

Update static object constantly in a thread and using in others activities

I have a static object in a class.
public class AppHelper {
public static MyObject CONSTANT_ = new MyObject();
}
// and my object
public class MyObject {
private Integer status;
// get and set for status
}
public class MyActivity extends Activity {
// oncreate()
// onresume()
public void OnUpdate() {
if (AppHelper.CONSTANT_.getStatus == 1) {
// doStuff
} else if (AppHelper.CONSTANT_.getStatus == 2) {
// doOtherStuff
}
}
}
public class MyService extends Service {
// oncreate()
public void callServer() {
// implementation of thread ommited
Endpoint.get(URL, new CallBack(Response response) {
AppHelper.CONSTANT_ = jsonToObj(reponse); // method for conversion is Ok
});
}
}
And activities have to call AppHelper.CONSTANT_.getStatus() for show a different view. My thread updates CONSTANT_ object constantly.
So, sometimes I use something like this:
MyObject obj = AppHelper.CONSTANT_;
When I set any field in obj, few seconds later the setted field come back to empty. Is obj linked with AppHelper.CONSTANT_ ? If so, have some other way to supply this status field without have a constant?

Trying to execute of a child element inside a parent array java

I have three classes.
public class PutController{
public PutController[] putControllerArray = new PutController[2];
public void controlar(int players) {
if(numeroJugadores==0){
putControllerArray[0] = new PutAutoController(tablero, tableroView, turno, turnoView);
putControllerArray[1] = new PutAutoController(tablero, tableroView, turno, turnoView);
}
if(numeroJugadores==1){
putControllerArray[0] = new PutManualController(tablero, tableroView, turno, turnoView);
putControllerArray[1] = new PutAutoController(tablero, tableroView, turno, turnoView);
}
}
}
public class PutManualController extends PutController {
public void methodToCall(){
.....
}
}
public class PutAutoController extends PutController {
public void methodToCall(){
.....
}
}
class Principal{
private PutController putController = new PutController(tablero, tableroView, turno, turnoView);
}
and in my Principal class i want to call a method of an element in the array of put class, like this.
putController.putControllerArray[0].methodToCall();
Hope you can help me. Thanks!
As long as PutController contains the method methodToCall() (either as an abstract method implemented by the sub classes, or with a concrete implementation in the base class), you can call it on any element of your array.
public class PutController
{
...
public void methodToCall ()
{
....
}
...
}
The sub-classes can override methodToCall() if they require different implementations.
This would make the code putControllerArray[0].methodToCall() valid. Of course, if you need to access that array from outside your class, you need to create an instance of your class, since it's not a static member. It would be better, though, to make the array private and access it via a method that returns the i'th element of the array.
public class PutController
{
...
public PutController getElement (int i)
{
if (i < 0 || i >= putControllerArray.length) {
// TODO throw some exception
}
return putControllerArray[i];
}
...
}
Then you can execute methodToCall() via putController.getElement(0).methodToCall();

Intellij IDEA plugin - PersistentStateComponent loadState not called

I am trying to develop a plugin for Intellij IDEA, I am working with SDK 129.451.
The issue I have is that I can't persist the user data like some list items he can input in the plugin and have the data back after the IDE restarts..
I am using PersistentStateComponent to persist the data, the getState() method seems to be called but the loadState() method doesn't.
Here is a sample class that extends PersistentStateComponent:
#State(name = "Test", storages = {#Storage(file = StoragePathMacros.APP_CONFIG+"/other.xml"
)})
public class Test implements PersistentStateComponent<Element> {
String ceva;
public Test() {
ceva = "sad";
System.out.println("constr");
}
public String getCeva() {
return ceva;
}
public void setCeva(String ceva) {
this.ceva = ceva;
}
public void loadState(Element state) {
System.out.println("cstate load");
ceva = (String) state.getContent().get(0);
}
public Element getState() {
System.out.println("cstate retu");
Element configurationsElement = new Element("testtt");
configurationsElement.addContent(ceva);
return configurationsElement;
}
}
Also I added this class in plugin.xml here:
<extensions defaultExtensionNs="com.intellij">
<applicationService serviceImplementation="ro.catalin.prata.testflightuploader.controller.Test"/>
<!-- Add your extensions here -->
<toolWindow id="TF Uploader" secondary="true" icon="/general/add.png" anchor="right"
factoryClass="ro.catalin.prata.testflightuploader.view.TFUploader">
</toolWindow>
</extensions>
And I also have a tool window class:
public class TFUploader implements ToolWindowFactory {
private JButton buttonAction;
private ToolWindow myToolWindow;
final Test test = ServiceManager.getService(Test.class);
public TFUploader() {
// I assume it should print the saved string but it doesn't
System.out.println(test.getCeva());
buttonAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// if I click a button I am setting some new value to the string I want to save
test.setCeva(test.getCeva() + "-dddddd+");
}
});
}
Ok so, if I close the app or minimize it, the getState method gets called as I expected.. but when I open the app, the loadState method doesn't get called.. can somebody help me how I can solve this?
I already read this but it doesn't seem to help me to much. Also I want to use PersistentStateComponent as I want to save objects more complex than a simple String.
Thank you in advance!
Ok, I made it! :)
I don't know exactly what the issue was but I changed the Test class to this:
#State(
name = "Test", storages = {
#Storage(
id = "other",
file = "$APP_CONFIG$/testpersist.xml")
})
public class Test implements PersistentStateComponent<Test> {
String ceva;
public Test() {
ceva = "sad";
System.out.println("constr");
}
public String getCeva() {
return ceva;
}
public void setCeva(String ceva) {
this.ceva = ceva;
}
public void loadState(Test state) {
System.out.println("cstate load");
XmlSerializerUtil.copyBean(state, this);
}
public Test getState() {
System.out.println("cstate retu");
return this;
}
}
And in the TFUploader I changed the way I loaded the Test class to this:
final Test test = ServiceManager.getService(Test.class);
I hope it helps others..
I have already commented here but will say again that in my case loadState(MyService state) wasn't called because of lack of getter and setter for stateValue from this example:
class MyService implements PersistentStateComponent<MyService> {
public String stateValue;
public MyService getState() {
return this;
}
public void loadState(MyService state) {
XmlSerializerUtil.copyBean(state, this);
}
}
In my case I was getting a NullPointerException even before loadState was getting called. Similar to your code above I used an Element class as the state class. I had a constructor with some parameters in Element class. This was the problem as the framework could not create an instance of my state class. I tried to add a blank constructor without any parameters. This worked.

Categories