BEE
BEE

Reputation: 107

Add items to jList

I am trying to create a method that will update a list that has already been created. Im not sure why this is not working?

It throws a null pointer exception.

This is my code:

private void UpdateJList(){
    String query = "SELECT * FROM names WHERE TYA=?";
    String partialSearch = "Sales";
    try{
        connect.pst = connect.con.prepareStatement(query);
        connect.pst.setString(1, partialSearch);
        connect.pst.execute();
        ArrayList<String> add = new ArrayList<String>();
        String[] items = {};
        while (connect.rs.next()){
            String result = connect.rs.getString("ACNO");
            add.add(result);
            int length = add.size();
            DefaultListModel<String> model;
            model = new DefaultListModel<String>();
            for (int i=0; i<length; i++){
                model.add(i, result);
            }
            jList1.setModel(model);     
            jList1.setSelectedIndex(0);
       }
   }catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
   }
} 

Thank you in advance!!

Upvotes: 0

Views: 94

Answers (1)

SME_Dev
SME_Dev

Reputation: 1890

There are 2 major problems with that code:

  1. In the while loop, you are creating many instances of DefaultListModel. That means, for each entry of the query result, you are restarting the list.
  2. A nullpointer exception is produced by the line: connect.rs.next() because you didn't assign connect.rs with the query's resultset.

Upvotes: 1

Related Questions