How to display arraylist in jtable dynamically - java

I am new to Java so please bare with me :).
I created a function that fetch the records from the table.
public ArrayList<Object> getAll() {
try {
ArrayList<Object> resultList = new ArrayList<>();
query = this.conn.prepareStatement("select * from " +
this.currentTable + this.tableClass.getWhere());
ResultSet result = query.executeQuery();
ResultSetMetaData meta = result.getMetaData();
int totalColumn = meta.getColumnCount();
while(result.next()) {
ArrayList<Object> obj = new ArrayList<>();
for (int x = 1; x < totalColumn; x++) {
obj.add(result.getObject(x));
}
resultList.add(obj);
}
result.close();
query.close();
return resultList;
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
return null;
}
Now, I want to display the ArrayList above in my JTable.
DefaultTableModel model = new DefaultTableModel();
ArrayList<Object> obj = this.getAll(); //call the method above
// How to insert the records above.
tableResult.setModel(model);
The problem is, there is an error while inserting an ArrayList in a JTable. I tried to cast ArrayList to Object[] but it has also an error.
Does anybody know?

Related

using where in mysql query when populating jtree from DB

I'm populating jtree from mysql DB which is working fine but my problem is that when i use select .... where condition is then the condition after where ... is ignored and the tree is populated with all data from the table!
public void PopoultateTree(){
try {
ArrayList list = new ArrayList();
list.add("Chart of Accounts");
String sql = "select * from accounts where AccountCompanyCode = '" + General.BaseForm.LoggedCompanyCode + "' and AccountFinYear = '" + CompanyData[1] + "'";
con = ConnectDataBase.ConnectDataBase_Method(); // receive the DB connection from another general class
statement = con.prepareStatement(sql);
rslt = statement.executeQuery();
while (rslt.next()){
Object value[] = {rslt.getString("AccountName")};
list.add(value);
}
Object hierarchy[] = list.toArray();
DefaultMutableTreeNode root = processHierarchy(hierarchy);
DefaultTreeModel treeModel = new DefaultTreeModel(root);
ChartOfAccountsTree.setModel(treeModel);
// expand the tree
for (int i = 0; i < ChartOfAccountsTree.getRowCount(); i++) {
ChartOfAccountsTree.expandRow(i);
}
disconnect();
} catch (SQLException ex) {
Logger.getLogger(ChartOFAccountsDisplay.class.getName()).log(Level.SEVERE, null, ex);
}
}

Take data from a Varray of oracle with java

So I need to to take data from a Varray I created on Oracle with java program. If someone knows. I tried this
My VArray.
CREATE OR REPLACE TYPE cancion IS VARRAY(13) of VARCHAR2(20);/
My function in java.
private ArrayList<String> getCanciones(int codDisco) {
this.open();//open connection
ArrayList<String> x = new ArrayList<String>();
String util;
String sql = "SELECT canciones from TDisco where codDisco = "+codDisco;
try {
PreparedStatement select = con.prepareStatement(sql);
System.out.println(sql);
ResultSet rs = select.executeQuery(sql);
while(rs.next()){
util=rs.getString(1);
x.add(util);
};
} catch (SQLException e) {
e.printStackTrace();
}
this.close();//close connection
return x;
}
Using a simple array doesn´t give problems to take all the data. So I just do it this way and working fine.
private ArrayList<String> getCanciones(int codDisco) {
// TODO Auto-generated method stub
ArrayList<String> x=new ArrayList<String>();
String[] values = null;
ARRAY array;
String sql = "SELECT canciones from TDisco where codDisco = "+codDisco;
try {
PreparedStatement select = con.prepareStatement(sql);
System.out.println(sql);
ResultSet rs = select.executeQuery(sql);
while(rs.next()){
array = (ARRAY) rs.getArray(1);
values = (String[]) array.getArray();
};
} catch (SQLException e) {
e.printStackTrace();
}
for (int i = 0; i < values.length; i++) {
x.add(values[i]);
}
return x;
}

Build map with column name and column values from java.sql.ResultSet

I have the following snippet:
Connection connection = getConnection(schemaName);
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM " + tableName;
ResultSet rs = stmt.executeQuery(sql);
now what I want to achieve is building a
Map<String , List<String>>
where key is the columnName and value is list of columnValues. Here is my code:
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
List<String> columnNames = new LinkedList<>();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(rsmd.getColumnName(i));
}
Map<String, List<String>> columnNameToValuesMap = new HashMap<String, List<String>>();
for (String columnName : columnNames) {
List<String> values = new ArrayList<>();
try {
while (rs.next()) {
values.add(rs.getString(columnName));
}
} catch (SQLException e) {
e.printStackTrace();
}
columnNameToValuesMap.put(columnName, values);
}
The issue is that after the first columnName iteration, rs.next() is empty. So basically The result map contains the values for only the first column. How can I reuse the same resultSet for each iteration ? Why its empty after the first one ?
You can follow the below steps:
(1) Initialise the columnNameToValuesMap with empty list objects with column name as key
(2) Iterate the resultset using rs.next()
(3) Get each column data using a for loop and add to list values object
(4) Add the list of columns data to columnNameToValuesMap object
You can refer the below code with comments:
List<String> columnNames = new LinkedList<>();
Map<String,List<String>> columnNameToValuesMap=new HashMap<String, List<String>>();
for (int i = 1; i <= columnCount; i++) {
String columnName = rsmd.getColumnName(i);
columnNames.add(columnName);
//Load the Map initially with keys(columnnames) and empty list
columnNameToValuesMap.put(columnName, new ArrayList());
}
try {
while (rs.next()) { //Iterate the resultset for each row
for (String columnName : columnNames) {
//Get the list mapped to column name
List<String> columnDataList = columnNameToValuesMap.get(columnName);
//Add the current row's column data to list
columnDataList.add(rs.getString(columnName));
//add the updated list of column data to the map now
columnNameToValuesMap.put(columnName, columnDataList);
}
}
} catch (SQLException e) {
e.printStackTrace();
}

How to create a list using PreparedStatement?

I have following codes:
-------class------------
private class SystemHealthAlert implements Work {
List<MonitorAlertInstance> systemHealthAlertList;
private String queryString;
// private java.util.Date startDate;
// private java.util.Date endDate;
#Override
public void execute(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(queryString);
int index = 1;
ResultSet rs = ps.executeQuery();
int columnCount = rs.getMetaData().getColumnCount();
while(rs.next())
{
//String[] row = new String[columnCount];
//results.set(index, element);
//for (int i=0; i <columnCount ; i++)
// {
// row[i] = rs.getString(i + 1);
// }
systemHealthAlertList.add(row);
}
rs.close();
ps.close();
}
}
---------Method-----------
public List<MonitorAlertInstance> getSystemHealthAlert(Long selectedSensorId) {
List<MonitorAlertInstance> systemHealthAlertList;
try {
// Add SELECT with a nested select to get the 1st row
String queryString = "select min(MONITOR_ALERT_INSTANCE_ID) as MONITOR_ALERT_INSTANCE_ID, description" +
" from ems.monitor_alert_instance " +
" where description in (select description from monitor_alert_instance" +
" where co_mod_asset_id = " + selectedSensorId +
" )" +
" group by description";
SystemHealthAlert work = new SystemHealthAlert();
// work.coModAssetId = coModAssetId;
work.queryString = queryString;
getSession().doWork(work);
systemHealthAlertList = work.systemHealthAlertList;
} catch (RuntimeException re) {
// log.error("getMostRecentObservationId() failed", re);
throw re;
}
//log.info("End");
return systemHealthAlertList;
}
My query returns three rows from DB. How can I return systemHealthAlertList from the class that will have all the three rows of the query.
In method execute, you should fill your List<MonitorAlertInstance> systemHealthAlertList with instances of MonitorAlertInstance. Create a new instance of MonitorAlertInstance inside the while loop where you retrieve the data:
//You don't need this line, remove it
//int columnCount = rs.getMetaData().getColumnCount();
while(rs.next()) {
//create a new instance of MonitorAlertInstance per ResultSet row
MonitorAlertInstance monitor = new MonitorAlertInstance();
//set the fields from the ResultSet in your MonitorAlertInstance fields
//since I don't know the fields of this class, I would use field1 and field2 as examples
monitor.setField1(rs.getInt(1));
monitor.setField2(rs.getString(2));
//and on...
systemHealthAlertList.add(monitor);
}
Apart from this problem, you should initialize your List<MonitorAlertInstance> systemHealthAlertList variable before use it:
systemHealthAlertList = new ArrayList<MonitorAlertInstance>();
while(rs.next()) {
//content from previous code...
}
Define a class/bean to hold the data from one given row. Loop through your rows, and create one instance of that class for each row you have. Add these instances to some List. Return the List of these 3 instances.

INSERT row does not update JTable in GUI

As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. When I restart, the new row is there and everything is as it should be. I have tried revalidating/repainting the panel and frame, I have tried the fire methods. I'm at a loss. Thanks in advance
ActionListener (in adminGUI class) for 'Add' button:
if(source.equals(add2)){
String c = itb.getText();
int a = main.getResults();
boolean matches = Pattern.matches("[A-Z][a-z]+", c);
if(matches == true){
main.addGenre(a, c);
}
String Method(in main class) to add a row to the database table:
public static void addGenre(int a, String b){
int rowsAdded;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
Statement stmt = connect.createStatement();
String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
rowsAdded = stmt.executeUpdate(query);
}catch(Exception exc){}
}
Method(also in main class) to increment the auto-increment-key column:
public static int getResults(){
int a = 0;
ResultSet ints = main.getResults("Select genre_id from Genres");
try {
while(ints.next()){
int d = ints.getInt("genre_id");
if(d>a){
a = d;
}
a++;
}
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
JTable details:
ResultSet rs1 = main.getResults("Select * from Genres");
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));
DbUtils.resultSetToTableModel details :
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
"I cannot get my JTable to update with a new row unless I restart the program."
I think what you're expecting is that when the database table update, so should your JTable. It doesn't really work like that. You need to update the TableModel, and the JTable will be automatically updated
Since resultSetToTableModel returns a DefuaultTableModel, you can use either of the two methods from DefaultTableModel:
public void addRow(Object[] rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
public void addRow(Vector rowData) - Adds a row to the end of the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
So when your are adding the data to the database, you also want to update the DefaultTableModel like this
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer instead of int so it will fit with the Object[] passed to addRow. The int you pass to it will get autoboxed to Integer
SIDE NOTES
Don't swallow you exception by putting nothing in the catch block. Put something meaningful that will notify you of any exceptions that may occur, like
catch(Exception ex) {
ex.printStackTrace();
}
You should also close your Connections, Statements, and ResultSets
You should use PreparedStatement instead of Statement, to avoid SQL injection.
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
Use this code. so you can insert one row at the end of Jtable without restarting application.,
Thanks..

Categories

Resources