Assuming I have two methods. One that creates an arraylist and returns it, the other retrieving that list to process. both methods are in different classes:
public ArrayList getSocialUsers() throws SQLException
{
Connection conn=DriverManager.getConnection("jdbc:mysql:///socialsystemtest1?user=root&password=");
Statement stmt= null;
String query="SELECT FORE_NAME FROM socialsystemtest1.socialworkers";
stmt= conn.createStatement();
ArrayList<String> socialWorkers= new ArrayList<String>();
try{
ResultSet rs= stmt.executeQuery(query);
while(rs.next())
{
String user= rs.getString("Fore_Name");
socialWorkers.add(user);
}
}
catch(SQLException e) {
//do nothing
}
finally{
if(stmt != null) {
stmt.close();
}
}
return socialWorkers;
}
public void processArray(){
try{
ArrayList<String>= db.getSocialUsers();
//code ommitted
}
catch(SQLException e){
//deal with it here
}
}
db is an instance of the class that returns the arraylist already instantiated. I recieve a null pointer error at the first line of the second classes method: db.getSocialUsers();
when calling the getSocialUsers() method on its own this works and an ArrayList is indeed returned with the correct elements but when calling it from another class gives a null pointer and I don’t know why
This means that the
dbobject isnull, not theArrayList. Where are you instantiating it?Edit: I recommend you replace the instantiation in the constructor with a member initialization: