unknown
unknown

Reputation: 343

JDBC: java.lang.NullPointerException

I was trying to read records from MySQL database and put it in a class variable in JDBC but it throws exception The Error is: java.lang. NullPointerException.

What is it that I am doing wrong here?

Code:

 try {
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "root", "password");
        st = conn.createStatement();
        rs = st.executeQuery("SELECT * FROM tablename");
        kids records = new kids();
        int i = 0;
        while (rs.next()) {
            records.id[i] = rs.getInt("id");
            records.name[i] = rs.getString("name");
            records.user_id[i] = rs.getInt("user_id");
            System.out.println("id: " + records.id[i] + "name: " + records.name[i] + "user_id" + records.user_id[i]);
            i++;
        }

    } catch (Exception e) {
        System.err.println("The Error: " + e);
    }

The kid class, which is supposed to store the records is as follows.

  public class kids{
    public int id[];
    public String name[];
    public int user_id[];
    public kids(){
        for (int x=0;x<100;x++){
         this.id[x]=0;
         this.name[x]="";
         this.user_id[x]=0;
        }
    }
}    

Upvotes: 1

Views: 155

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

The problem is that the arrays inside your kids class are null since that's the default value for objects (an array is an object). You should initialize them in the class constructor:

private static final int MAX_ARRAY = 100;
public kids(){
    this.id = new int[MAX_ARRAY];
    this.name = new String[MAX_ARRAY];
    this.user_id= new int[MAX_ARRAY];
    for (int x=0; x<MAX_ARRAY; x++){
        this.id[x]=0;
        this.name[x]="";
        this.user_id[x]=0;
    }
}

There are other several problems with your current design that you should work on:

  • Use the Java Code Conventions, so rename your class kids to Kid, your variable kids records to Kid kid, and on...
  • A class should store the data for an entity, your kid class is currently storing parallel arrays for data. It would be better to have a Kid class with int id; String name; int user_id; fields and KidHolder class which contains a Kid[] kidHolder instead.
  • Arrays have a static size and cannot be changed, so if you don't know how many elements will retrieve and hold (e.g. when retrieving data from database), use a List instead.
  • Do not open database connections manually, instead use a database connection pool that will enhance the database access by opening lot of connections and keeping them sleep, because opening a database connection has a high cost.

Taking into account all these advices, your design should be like this:

public class Kid {
    private int id;
    private String name;
    private int userId;
    //getters and setters
}

public class KidHolder {
    private List<Kid> kidHolder;
    public KidHolder() {
        kidHolder = new ArrayList<Kid>();
    }
    public void add(Kid kid) {
    }
}

//...

List<Kid> kidList = new ArrayList<Kid>();
try {
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "root", "password");
    st = conn.createStatement();
    rs = st.executeQuery("SELECT * FROM tablename");
    //kids records = new kids();
    //int i = 0;
    while (rs.next()) {
        Kid kid = new Kid();
        //records.id[i] = rs.getInt("id");
        //records.name[i] = rs.getString("name");
        //records.user_id[i] = rs.getInt("user_id");
        kid.setId(rs.getInt("id"));
        kid.setName(rs.getInt("name"));
        kid.setUserId(rs.getInt("user_id"));
        System.out.println("id: " + kid.getId() + "name: " + kid.getName() + "user_id" + kid.getUserId());
        kidList.add(kid);
    }
} catch (Exception e) {
    System.err.println("The Error: " + e);
} finally {
    closeResource(rs);
    closeResource(st);
    closeResource(conn);
}
//probably you should return kidList to display it in your view

//method to close the connection
//create two more similar methods to close ResultSet and Statement...
public void closeResource(Connection con) {
    if (con != null) {
        try {
            con.close();
        } catch (SQLException silent) {
            //...
        }
    }
}

Upvotes: 3

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8411

You have not instantiated any of the members,

public int id[];
public String name[];
public int user_id[];

Even the constructor would fail at this.id[x]=0;

Upvotes: 1

Related Questions