I have a table 2×2 (2 columns and 2 rows filled) on my database, I’m trying to get the entire table to my array, but when I try to print the result on the console I get NullPointerException. I can’t figure out what I am missing.
Main code:
public static void main(String[] args) {
mySQLManager Manager = new mySQLManager();
Manager.Connect();
String[] Dispositivos = null;
Dispositivos = Manager.GetDevices();
for (int i = 0; i < Dispositivos.length; i++){
System.out.println(Dispositivos[i]);
}
Manager.Disconnect();
}
Method:
public String[] GetDevices(){
String[] Devices = null;
String query = "SELECT * FROM devices";
int index = 0;
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while(resultSet.next()){
Devices[index + 0] = resultSet.getString(1);
Devices[index + 1] = resultSet.getString(2);
index+=2;
}
} catch (SQLException ex) {
System.out.println("\nNão foi possivel ler os dispositivos do database");
System.out.print(ex.getMessage());
}
return Devices;
}
Error I am getting:
Exception in thread “main” java.lang.NullPointerException at
logictesting.mySQLManager.GetDevices(mySQLManager.java:130) at
logictesting.LogicTesting.main(LogicTesting.java:29) Java Result: 1
The problem is that
Devicesisnullin:The easiest fix might be to turn
Devicesinto anArrayListsince then it would be easy to grow it dynamically.