Put firebase data in a JTable - java

I am struggling to put some firebase data into a jtable in java swing.
As seen in photo I've been able to retrieve the data from firebase but for some reason the data won't be displayed in the JTable field(table1)
I looks like the getID(), getName()... methods didn't get any value, since I tried to print row[i] to see if there is any value.
There is a screenshot of the actual program
Could any of you tell what's the problem?
addNewCaseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database = FirebaseDatabase.getInstance();
ref = database.getReference("NewCases");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
ArrayList<Object[]> myList = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) table1.getModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("City");
tableModel.addColumn("TimeStamp");
tableModel.addColumn("Disease");
tableModel.addColumn("Risk");
Object[] row = new Object[6];
tableModel.setNumRows(0);
myList.clear();
CasesList casesList = new CasesList();
for (DataSnapshot ds : dataSnapshot.getChildren()){
casesList.setID((Integer)ds.child("ID").getValue());
casesList.setName(ds.child("Name").getValue().toString());
casesList.setAge((Integer)ds.child("Age").getValue());
casesList.setCity(ds.child("City").getValue().toString());
casesList.setTimeStamp(ds.child("TimeStamp").getValue().toString());
casesList.setDisease(ds.child("Disease").getValue().toString());
casesList.setRisk(ds.child("Risk").getValue().toString());
// myList.add(ds.getKey());
row[0] = casesList.getID();
row[1] = casesList.getName();
row[2] = casesList.getAge();
row[3] = casesList.getCity();
row[4] = casesList.getTimeStamp();
row[5] = casesList.getDisease();
row[6] = casesList.getRisk();
myList.add(row);
System.out.println(myList);
tableModel.addRow(row);
}
table1.setModel(tableModel);
Thanks in advance!

Have you defined the table columns with lines like these?
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
Also, the method setModel should be called after the for:
for... {
//add row to tableModel
}
table1.setModel(tableModel);
EDIT:
Analyzing in more detail, I also verify that you have 7 fields but your array has only space for 6. In this line row [6] = casesList.getRisk (); throws an exception at runtime. Expand the size of your array to solve this.
Object[] row = new Object[7];
To display the column names it is convenient to add your table to a scroll panel.
JScrollPane scrollPane = new JScrollPane(table1);
frame.getContentPane().add(scrollPane);
This works for me:
ArrayList<Object[]> myList = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) table1.getModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("City");
tableModel.addColumn("TimeStamp");
tableModel.addColumn("Disease");
tableModel.addColumn("Risk");
Object[] row = new Object[7];
tableModel.setNumRows(0);
myList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CasesList casesList = new CasesList();
casesList.setID((Integer) ds.child("ID").getValue());
casesList.setName(ds.child("Name").getValue().toString());
casesList.setAge((Integer) ds.child("Age").getValue());
casesList.setCity(ds.child("City").getValue().toString());
casesList.setTimeStamp(ds.child("TimeStamp").getValue().toString());
casesList.setDisease(ds.child("Disease").getValue().toString());
casesList.setRisk(ds.child("Risk").getValue().toString());
row[0] = casesList.getID();
row[1] = casesList.getName();
row[2] = casesList.getAge();
row[3] = casesList.getCity();
row[4] = casesList.getTimeStamp();
row[5] = casesList.getDisease();
row[6] = casesList.getRisk();
myList.add(row);
System.out.println(myList);
tableModel.addRow(row);
}
table1.setModel(tableModel);

Related

Codename one a loop inside a TableModel

i'm trying to place a loop inside a TableModel to loop all the articles inside an arraylist to insert all the rows inside the table so i can add it to the form and show all the articles to the user
public class ListArticlesForm extends Form {
public ListArticlesForm(Form previous) {
setTitle("List all articles");
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"},
new Object[][]{
{
// I WANT TO PLACE A FOR HERE (this is showing only the first row !
articles.get(0).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
},});
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
}
You can't create an array as a for loop inside the array. You need to do it a line sooner.
Object[][] rows = new Object[articles.size()][];
for(int iter = 0 ; iter < rows.length ; iter++) {
rows[iter] = new Object[] {
articles.get(iter).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);
now after i Run the project the table rows are displayed correctly except the rank stars
the show outside the table and inside the colonne a text appears:
the function for the star rank creation is :
private Slider createStarRankSlider(int id) {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
int fontSize = Display.getInstance().convertToPixels(3);
Font fnt = Font.createTrueTypeFont("Handlee", "Handlee-Regular.ttf").
derive(fontSize, Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte) 0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
starRank.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ServiceTask.getInstance().UpdateRank(id,starRank.getIncrements());
Dialog.show("Success","thank you for rating our product",new Command("OK"));
}
});
return starRank;
}

How to add this array without adding columns again in the array

I want to remove this code and set to default values in the table
model2.setColumnIdentifiers(new
Object[]{"Order_ID","Description","Quantity","Amount","Order_Time","Cost"});
public void finduserday(){
ArrayList<dayday> list = userlistdaysearch (((JTextField)jDateChooser_searchdate.getDateEditor().getUiComponent()).getText());
DefaultTableModel model2 = new DefaultTableModel();
model2.setColumnIdentifiers(new Object[]{"Order_ID","Description","Quantity","Amount","Order_Time","Cost"});
Object [] row= new Object[6];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getOrder_ID();
row[1]=list.get(i).getDescription();
row[2]=list.get(i).getQuantity();
row[3]=list.get(i).getAmount();
row[4]=list.get(i).getOrder_Time();
row[5]=list.get(i).getCost();
model2.addRow(row);
}
jTable_dayday.setModel(model2);
}

Binary file proplem with jTableModel

i am writing in binary file objects by gui and when i list them in table only one line appears like this
not all data appers
and here is the code to list
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object rowData[] = new Object[5];
model.setRowCount(0);
Apparels a = new Apparels();
ArrayList<Apparels> app = new ArrayList<Apparels>();
app = a.listApparels();
for (Apparels x : app) {
rowData[0] = x.getStockid();
rowData[1] = x.getPricePerItem();
rowData[2] = x.getQuantity();
rowData[3] = x.getType();
rowData[4] = x.getCateogryname();
model.addRow(rowData);
}
You're re-using rowData to fill the properties, which means that for each row, it will have the same data
Maybe try using something more like...
for (Apparels x : app) {
Object rowData[] = new Object[5];
rowData[0] = x.getStockid();
rowData[1] = x.getPricePerItem();
rowData[2] = x.getQuantity();
rowData[3] = x.getType();
rowData[4] = x.getCateogryname();
model.addRow(rowData);
}
The primary issue is, the reference to rowData never changes, but the content in each element does, so once you've finished looping the, model will have a list of references all pointing to the same instance of rowData

adding rows with data from a Mysql table to jtable

Adding the colums works, but i am stuck when i want to add the data of the columns stored in a mysql database to the jtable. it ask for a object vector[][] but i have no clue what to give
Connection con;
DefaultTableModel model = new DefaultTableModel();
public Hoofdscherm() {
initComponents();
uitvoerSpelers.setModel(model);
try {
con = DriverManager.getConnection("jdbc:mysql://localhost/fullhouse", "root", "hamchi50985");
// selecteer gegevens uit fullhouse.speler tabel
PreparedStatement stat = con.prepareStatement("SELECT * FROM fullhouse.speler");
// sla deze GEGEVENS op in een resultset
ResultSet resultaat = stat.executeQuery();
// haal alle kolomnamen op PUUR VOOR DE MODEL VAN JTABLE
ResultSetMetaData data = resultaat.getMetaData();
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens[0]);
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
I think you need something like this.
Note
1. Also add your columns separate to resultset data. Like I showed in my code below.
Vector<String> rowOne = new Vector<String>();
rowOne.addElement("R1C1");
rowOne.addElement("R1C2");
Vector<String> rowTwo = new Vector<String>();
rowTwo.addElement("R2C1");
rowTwo.addElement("R2C2");
Vector<String> cols = new Vector<String>();
Vector<Vector> vecRow = new Vector<Vector>();
vecRow.addElement(rowOne);
vecRow.addElement(rowTwo);
cols.addElement("Col1");
cols.addElement("Col2");
JTable table = new JTable(vecRow, cols);
Edit
For you convenience and requirement You can follow code structure below.
Vector<String> rows = new Vector<String>();
Vector<Vector> dBdata = new Vector<Vector>();
// Add Columns to table
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
}
while (resultaat.next()) {
// add column data to rows vector
// Make sure that all data type is in string because of generics
rows.add(resultaat.getString("columnName1"));
rows.add(resultaat.getString("columnName2"));
rows.add(resultaat.getString("columnName3"));
// add whole row vector to dBdata vector
dBdata.addElement(rows);
}
model.addRow(dBdata);
Vector implements a dynamic array. It is similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
Class Vector Javadoc
I hope this will help you.
The line model.addRow(gegevens[0]);is incorrect.
You should do something like this:
String[] colum = new String[15];
for (int i = 1; i < data.getColumnCount(); i++) {
colum[i] = data.getColumnName(i);
model.addColumn(colum[i]);
while (resultaat.next()) {
Object[] gegevens = new String[] {resultaat.getString(1)};
model.addRow(gegevens);
}
}
Also you need to check DefaultTableModel
According to the documentation of DefaultTableModel:
This is an implementation of TableModel that uses a Vector of Vectors
to store the cell value objects.

JTable 3 fields arrayList

I am trying to add values to a Jtable, the values are fetched from arrayList,
How do you do that
I tried making Object[][] data; and the populate it inside a loop, but it does not work, How do you fix this?
String[] columns = {"Field String","Field Double"," Field Double"};
Object[][] data;
Iterator<Node> itr = arrayList.iterator();
while (itr.hasNext()) {
Node el = itr.next();
double a = el.getval();
data[i][1] = el.getstring();
data[i][2] = a;
data[i][3] = a*4;
i++;
}
JFrame frame = new JFrame("Title ");
JTable tablE = new JTable(data, columnas);
JPanel panel = new JPanel();
panel.add(table);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
How do you populate "data" inside a while loop?
Use a DefaultTableModel and add rows of data using its addRow(Object[]) or addRow(Vector) method. Set this as your JTable's model. The API and the JTable tutorial can get you started.
For e.g.,
ArrayList arrayList = new ArrayList();
String[] columns = {"Field String","Field Double"," Field Double"};
DefaultTableModel model = new DefaultTableModel(columns, 0);
for (Object item : arrayList) {
Object[] row = new Object[3];
//... fill in row with info from item
model.addRow(row);
}
JTable table = new JTable(model);
This demonstrates doing it with a for loop, but a while loop would be similar.

Categories