bzc0fq
bzc0fq

Reputation: 719

loading data into combo object with sql query result in Java

I would like to load a combo object with a result of sql query. I do not know how to convert List into String[]. My source is bellow:

public static void loadJadlospis() {
    List<String[]> ans1= null;
    String[] comboData=null;

    MySQL.Connect();
    ans1 = MySQL.sqlQuery("SELECT NazwaJadlospisu FROM Jadlospis GROUP BY NazwaJadlospisu");
    MySQL.Close();

    int a=0;
    for( String[] row: ans1 ){
        a=a+1;
        System.out.print( row[0] );
        comboData[a]=(row[0] + ",");
    }
    combo.setItems(comboData);  
}

This code does not work. I got an error: Exception in thread "main" java.lang.NullPointerException Could you please give me any suggestions on how to have it working?


UPDATE1: Bellow you can see MySQL.sqlQuery source:

public static List<String[]> sqlQuery(String sql){
    List<String[]> table= new ArrayList<>();

    try{
        state = con.createStatement();
        result = state.executeQuery(sql);
        int nCol = result.getMetaData().getColumnCount();
        while(result.next()){
            String[] row = new String[nCol];
            for( int iCol = 1; iCol <= nCol; iCol++ ){
                    Object obj = result.getObject( iCol );
                    row[iCol-1] = (obj == null) ?null:obj.toString();
                }
            table.add( row );
            }    
        }
    catch(SQLException e){
        System.err.println("Query error. " +e);
        }
    catch(NullPointerException e){
        System.err.println("Element not found." +e);
        }
    return table;
    }

UPDATE 2

I use the following code to check the ans1:

List<String[]> ans1= null;


MySQL.Connect();
ans1 = MySQL.sqlQuery("SELECT NazwaJadlospisu FROM Jadlospis GROUP BY NazwaJadlospisu");
for( String[] row: ans1 ){
    System.out.print( row[0] );
    System.out.println();
}
MySQL.Close();

It prints this:

Successfully connected to database. 
dieta 1500 kcal 
dieta testowa1 
test1 
Database closed successfully.

Upvotes: 1

Views: 55

Answers (1)

PythonLearner
PythonLearner

Reputation: 1466

You can do in the following manner. Here I assume that ans1 is having a list of String type values and you can convert list to strings like list.toArray(new String[0]).

public static void loadJadlospis() {
    List<String[]> ans1= null;
    MySQL.Connect();
    ans1 = MySQL.sqlQuery("SELECT NazwaJadlospisu FROM Jadlospis GROUP BY NazwaJadlospisu");
    MySQL.Close();
    List<String> rowsList = new ArrayList<>()   
    for(String[] rows: ans1) {
      for(String str: rows) {
         rowsList.add(str);
       }
    }   
    String[] comboData=rowsList.toArray(new String[0]);
    combo.setItems(comboData);  
}

Upvotes: 1

Related Questions