Issue
my problem is easy normally but i just don't see where is the problem. -i am declaring an array of a class as a global variable that i reuse in multiple functions inside this other class. the class instantiated is:
public class Service {
int numticketsin;
String name="mi";
int[] perhour={0,0,0,0,0,0,0,0,0,0};
int moyenneticketperday;
int[] moyenneticketperdayperhour={0,0,0,0,0,0,0,0,0,0};
public Service(){}
}
global var:
Service[] services=new Service[10];
the function where i use try to fill the array:
public void getnamesofservices(){
int x=0;
Connection conn=db.java_db();
try {
Statement stmt = conn.createStatement();
String qry = "SELECT service_name from service ";
ResultSet rs = stmt.executeQuery(qry);
int i=0;
while (rs.next()) {
String namee=rs.getString("service_name");
System.out.println(namee);
services[i].name = namee;
i++;
}
conn.close();
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex);
}
}
the error:
''' Exception in thread "main" java.lang.NullPointerException: Cannot assign field "name" because "this.services[i]" is null
at com.mycompany.stats.NewJFrame.getnamesofservices(NewJFrame.java:195)
at com.mycompany.stats.NewJFrame.<init>(NewJFrame.java:122)
at com.mycompany.stats.Main.main(Main.java:16)'''
thank you in advance!!
Solution
Service[] services=new Service[10];
This means you created and array with 10 positions, but all those positions are empty (meaning they have null
inside each and every position of the array).
So, when trying services[i].name
you get the NullPointerException
because services[i]
is null
.
There are plenty of ways to do the initialization, that depends on your business cases. But just to name two possibilities:
- Initialize it at the declaration:
Service services[] = new Service[] {
new Service(),new Service(), new Service(), new Service(),new Service(),
new Service(),new Service(), new Service(), new Service(),new Service()
};
- Or just before using it, in case you are not overriding it:
services[i] = new Service();
services[i].name = namee;
Answered By - gmanjon