Database add item to list view? - java

I download this database script and i was wondering how can i convert it to instead add a item to a list view.. its a really easy understandable database code..
http://www.anotherandroidblog.com/wp-content/uploads/2010/08/AABDatabase.zip
Thats the source for it..
also im guessing it could be in here??
/**
* retrieves a row from the database with the id number in the corresponding
* user entry field
*/
private void retrieveRow()
{
try
{
// The ArrayList that holds the row data
ArrayList<Object> row;
// ask the database manager to retrieve the row with the given rowID
row = db.getRowAsArray(Long.parseLong(updateIDField.getText().toString()));
// update the form fields to hold the retrieved data
updateTextFieldOne.setText((String)row.get(1));
updateTextFieldTwo.setText((String)row.get(2));
}
catch (Exception e)
{
Log.e("Retrieve Error", e.toString());
e.printStackTrace();
}
}

To add the items from database to a ListView you can have an ArrayList
1.) ArrayList<String> arrList = new ArrayList<String>();
2.) Fetch items from database and add them to ArrayList
if(c.getCount() > 0){
c.moveToFirst();
for (int i = 0; i < c.getCount() - 1; i++) {
arrList.add(c.getString(0));
c.moveToNext();
}
3.) Then populate the Adapter with the ArrayList(arrList).
4.) And fill the ListView with the Adapter.

Related

I can't re-reference a TableRow with findViewById

I have an activity where I create Tablerow programatically, as I don't know how many files I need.
Each TableRow has an ID starting by 100 and continue 200, 300 and so on.
When I create the row 3 the TableRow's ID is 300.
Then when someone edit other row I need to know what row is just to work with the elements of the row.
My problem: previous value:
trActiva.getId()=300
Then this is my code I put:
lineaActiva = (tv.getId()) / 100 * 100;
trActiva = findViewById(lineaActiva);
just on the point before these two lines trActiva.getId()=300
after the first row of the code lineaActiva = 200
That means after the second line trActiva.getId() should be 200 but it is still 300.
More weird things:
after these two lines:
trActiva.getId()=300
findViewById(lineaActiva).getId()=200
What is happening here? Why trActiva is not changing?
Thank you!!
We are unsure how you are increasing your Id and how you are storing your data as well how do you view 300 rows on a computer screen
So a lot of code is missing to give a very pointed answer to your question
Here is a table we populate from a Derby Database
The table is named ptable and we might also mention we are using a Model View Controller pattern to manage the data to GET and SET variables
First we read from the Database and populate the ptable with this code
private void ReadFromParent() throws SQLException{
ObservableList<ParentModel> TableData = FXCollections.observableArrayList();
stmnt = conn.createStatement();
ResultSet rs = stmnt.executeQuery("SELECT * FROM Parent");
while (rs.next()){// Add data to observableArrayList TableData to select a table ROW
TableData.add(new ParentModel(rs.getString("PID"),rs.getString("pMonth"),rs.getString("pYear")));
}
PropertyValueFactory<ParentModel, String> IDCellValueFactory = new PropertyValueFactory<>("PID");
colID.setCellValueFactory(IDCellValueFactory);
PropertyValueFactory<ParentModel, String> DateCellValueFactory = new PropertyValueFactory<>("pMonth");
colMonth.setCellValueFactory(DateCellValueFactory);
PropertyValueFactory<ParentModel, String> TypeCellValueFactory = new PropertyValueFactory<>("pYear");
colYear.setCellValueFactory(TypeCellValueFactory);
// ================================================================
// colTxDate are the ID's for the tableview columns
// sortDate are the Column Names for the Database TABLE CDBalance
// ================================================================
colMonth.setStyle("-fx-alignment: CENTER;");
colYear.setStyle("-fx-alignment:CENTER;");
Collections.sort(TableData, (p2, p1)-> p1.getPID().compareToIgnoreCase(p2.getPID()));
// Line of Code above Sorts Database Columns based on VARIABLE in ParentModel
// Change p2,p1 to sort Ascending or Descending
if(TableData.size() < 15) {// Format TableView to display Vertical ScrollBar
ptable.setPrefWidth(336);// 19 is the off set
}else {
ptable.setPrefWidth(355);
} ptable.setItems(TableData);
stmnt.close();
}
Then we write listener code to permit us to view the details of the row selected
Notice we get the ID from the row selected
This is where you can use that value to find the new entry that is greater than 300
OR you can write a Search query on the table that finds all records that have an ID greater than 300
Here is the code that permits you to click on a row in the table
private void showTableDataDetails(ParentModel info) throws IOException{
if (info != null) {
info = (ParentModel) ptable.getSelectionModel().getSelectedItem();
strID = info.getPID();
strMONTH = info.getPMonth();
strYEAR = info.getPYear();
toChildView();
System.out.println("########### PID "+strID);
}
}
#Override
public void initialize(URL url, ResourceBundle rb) {
ptable.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends ParentModel>
observable,ParentModel oldValue, ParentModel newValue) -> {
try {
showTableDataDetails((ParentModel) newValue); // When a row of the table is Selected call
// Proper Construction // showTableDataDetails method
} catch (IOException ex) {
Logger.getLogger(ParentTableViewController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
Hope this helps and Welcome to Stack Overflow
PLEASE post a little more code in the future so your question can have a more definitive answer

Printer won't print the entire jTable [duplicate]

Question Now once the data is fetched from the database and shown in the JTable object "table" embedded in the scrollPane, how do we create a print job that makes it possible to print the displayed table as such in A3 sized paper ?
My code to fetch the data from the database is shown below:
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/newb","root","pass");
Statement stat=con.createStatement();
ResultSet res=stat.executeQuery("select * from table where name = '"+name+"'");
ResultSetMetaData rsmd = res.getMetaData();
int colcount = rsmd.getColumnCount();
Vector columns = new Vector(colcount);
for(int i=3; i<=colcount; i++)
{
columns.add(rsmd.getColumnName(i));
}
Vector data = new Vector();
Vector row;
// Store row data
while(res.next())
{
row = new Vector(colcount);
for(int i=3; i<=colcount; i++)
{
row.add(res.getString(i));
}
data.add(row);
}
table = new JTable(data, columns);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
scrollPane.setViewportView(table);
}
catch(Exception ex)
{
System.out.println(ex);
}
I am using vector class to fetch the data from the table. How do we print the data shown in the displayed table to a paper?
just use JTable.print() method. here is an article about sending JTable into printer and another one with more parameters
You obviously didn't read the links provided in your previous question.
From the Printing section of How to use Tables
Printing
JTable provides a simple API for printing tables. The easiest way to
print out a table is to invoke JTable.print with no arguments:
try {
if (! table.print()) {
System.err.println("User cancelled printing");
}
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
Invoking print on a normal Swing application brings up a standard printing
dialog box. (On a headless application, the table is simply printed.)
The return value indicates whether the user went ahead with the print
job or cancelled it. JTable.print can throw
java.awt.print.PrinterException, which is a checked exception; that's
why the above example uses a try ... catch.
JTable provides several overloads of print with various options. The
following code from TablePrintDemo.java shows how to define a page
header:
MessageFormat header = new MessageFormat("Page {0,number,integer}");
try {
table.print(JTable.PrintMode.FIT_WIDTH, header, null);
} catch (java.awt.print.PrinterException e) {
System.err.format("Cannot print %s%n", e.getMessage());
}
For more sophisticated printing applications, use JTable.getPrintable to obtain
a Printable object for the table. For more on Printable, refer to the
Printing lesson in the 2D Graphics trail.
i hope help you with this code try it its for How to print JTable in Java netbeans
private void btn_printActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MessageFormat header = new MessageFormat("Print Report");
MessageFormat footer = new MessageFormat("Page{0,number,integer}");
try {
table_employee.print(JTable.PrintMode.FIT_WIDTH, header, footer);
} catch (java.awt.print.PrinterAbortException e) {
} catch (PrinterException ex) {
Logger.getLogger(employee_info.class.getName()).log(Level.SEVERE, null, ex);
}
}

Fixing some content at the end of first page aspose words java

I am working with apose words java recently.
In my first page I have a table need to merge, which can grow any size, no fixed number of rows and at the end of my first page, I want to keep some content (for example contact details) to be fixed. (Note: I can't keep contact details in Footer or in foot note section because of some formatting I need to ensure which can't maintain in footer or foot note section)
On growing of table as many rows, My content is going down, But I want to fix it at the end of my first page. if table grows bigger in size, wanted to skip the content and render table in next page.
is there any solution/work around for this?
My expected results are like below....
Page 1 Start
dynamic Table row1
dynamic Table row2
dynamic Table row3
Contact Details ,wanted to fix at the end of my first page
Page 1 end
Page 2 Start
dynamic table row 4
dynamic table row 5
........
For your scenario, ideally the contact details should be set in a footer. It is possible, but very risky.
First create a new document, either in Aspose.Words or MS Word, it will be used as a template.
Add a blank table on top
Add contact details, after the blank table
Add a bookmark, after the contact details
Now, using Aspose.Words, you can check the location of the bookmark, every time you are adding a new row in the table. If bookmark is at page 1, add new row to the first table. If bookmark is at page 2, add new row to the second table. Below is the sample code that adds rows to the table, keeping the contact details fixed on page 1.
Template document: Google drive link
Java source code is given below.
public static void main(String[] args)
{
try
{
String template = Common.DATA_DIR + "Contact Template.docx";
String saveDocument = Common.DATA_DIR + "Contact with tables.docx";
String bookmarkNameContact = "ContactEnd";
// Load the template
com.aspose.words.Document wordDoc = new com.aspose.words.Document(template);
DocumentBuilder builder = new DocumentBuilder(wordDoc);
// Find the contacts bookmark
com.aspose.words.Bookmark bookmarkContact = wordDoc.getRange().getBookmarks().get(bookmarkNameContact);
// Set the table with null
com.aspose.words.Table table = null;
// Add some rows
for (int i = 0; i < 50; i++)
{
// If contacts bookmark is on 1st page, add new rows to first table
if (getBookmarkPage(wordDoc, bookmarkContact) == 1)
{
table = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 0, true);
} else
{
// If the contacts bookmark is on second page, add rows to second table
table = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 1, true);
// If there is no second table, create it
if (table == null)
{
table = createNewTable(wordDoc, bookmarkContact);
}
}
// Add rows dynamically to either first or second table
addRow(wordDoc, table, "some text " + i);
}
// Save the document
wordDoc.save(saveDocument);
} catch (Exception ex)
{
System.err.println(ex.getMessage());
}
}
private static com.aspose.words.Table createNewTable(com.aspose.words.Document wordDoc, com.aspose.words.Bookmark bookmarkContact) throws Exception
{
// Get the first table and clone it to create the second one
com.aspose.words.Table firstTable = (com.aspose.words.Table) wordDoc.getChild(NodeType.TABLE, 0, true);
com.aspose.words.Table table = (com.aspose.words.Table) firstTable.deepClone(true);
// Add the second table after the bookmark
bookmarkContact.getBookmarkEnd().getParentNode().getParentNode().appendChild(table);
// Delete all its rows
table.getRows().clear();
return table;
}
// Add a new row to the table
private static void addRow(com.aspose.words.Document wordDoc, com.aspose.words.Table table, String text)
{
// Create a new row
com.aspose.words.Row row = new com.aspose.words.Row(wordDoc);
row.getRowFormat().setAllowBreakAcrossPages(true);
// Add it to the table
table.appendChild(row);
// Add cells to the row
for (int iCell = 0; iCell < 4; iCell++)
{
// Create a new cell and set text inside it
com.aspose.words.Cell cell = new com.aspose.words.Cell(wordDoc);
cell.appendChild(new com.aspose.words.Paragraph(wordDoc));
cell.getFirstParagraph().appendChild(new Run(wordDoc, text));
cell.getFirstParagraph().getParagraphFormat().setSpaceAfter(0);
row.appendChild(cell);
}
}
private static int getBookmarkPage(com.aspose.words.Document wordDoc, com.aspose.words.Bookmark bookmarkContact) throws Exception
{
// Find the page number, where our contacts bookmark is
LayoutCollector collector = new LayoutCollector(wordDoc);
return collector.getStartPageIndex(bookmarkContact.getBookmarkEnd());
}
I work with Aspose as Developer Evangelist.

Can't add a row to a jTable even when using getModel

I've been searching through this website for numerous hours now on how to get my button to an a row to an already existing table, this table created by simply clicking the swing Controls, and adding a table and altering the fields through the properties.
The table's variable name is 'table'.
And when confronted with this line of code:
table.getModel().insertRow(table.getRowCount(),new Object[]{nome[i],data[i]});
The 'insertRow' part is redded and I can't seem to fix it.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String direcdate=direc1.getText();
File folder = new File(direcdate);
File[] listOfFiles=folder.listFiles();
String[] nome = new String[250];
String[] data = new String[250];
int i=0;
for (File listOfFile : listOfFiles) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if (listOfFile.isFile()) {
nome[i]= listOfFile.getName ();
data[i] =sdf.format(listOfFile.lastModified());
i++;
}
else if (listOfFile.isDirectory()) {
nome[i]= "Folder: " + listOfFile.getName ();
data[i] =sdf.format(listOfFile.lastModified());
i++;
}
}
for(int increm=0;increm<i;increm++)
{
table.getModel().insertRow(table.getRowCount(),new Object[]{nome[i],data[i]});
}
}
Any ideas or suggestions?
EDIT: where the table model is located:
public class GAPAC_TESTE extends javax.swing.JFrame {
public GAPAC_TESTE() {
initComponents();
ultimaalt.setText("0");
jTextPane2.setText("Após escolher a diretoria, escolha uma das opções.");
DefaultTableModel model = new javax.swing.table.DefaultTableModel();
table = new javax.swing.JTable(model);
}
table.getModel().
That method return a TableModel. Did you look at the API for the TableModel interface? It does not contain an insertRow(...) method.
The DefaultTableModel has the insertRow(...) method. So assuming your table is using a DefaultTableModel the code would be:
DefaultTableModel model = (DefaultTableMode)table.getModel();
model.insertRow(...);
Don't always write you code in a single statmentment. Break the statement up into multiple statements so you understand exactly which part of the statement causes the problem and it makes sure you assign the variable to the proper class.
If you implement a TableModel, you will be able to exactly determine how data is added and which data types are displayed in your table.

How to show data from database to jtable with checkboxes in the first column in jtable?

I know how to populate jtable and i had prepared the code for the above which works fine. But the problem is that it is working in another project but bot in my current project. The code for both the project is same. Here is the code... purchaswtab is the table name which has been already created using swing palette. And this function is executed in the event of the exit button of the Item Master.
the array elements of an array ap are defined as i have to fetch them from the given position from the resultset.
public void populatetable(ItemMaster imm)
{
imm.dispose();
String t[][]=new String [30][10];
int[] ap={19,1,2,4,18,16,17};
Object[] h1=new Object[7];
String a1,a2;
int j=0,i=1;
int len=0;
try
{
st=fun.connect1();
String query="select * from Temp_Purchase";
ResultSet rs=st.executeQuery(query);
ResultSetMetaData rsmd=rs.getMetaData();
while(rs.next())
{
int k=0;
for(i=1;i<=7;i++,k++ )
{
t[j][i-1]=rs.getString(ap[k]);
System.out.println(t[j][i-1]);
}
j++;
len++;
}
fun.close();
}
catch(Exception e)
{
fun.close();
System.out.println("Exception:"+e);
}
DefaultTableModel de=(DefaultTableModel)purchaseTab.getModel();
purchaseTab=new JTable(de);
//Code for filling data into table
for(i=0;i<len;i++)
{
for(j=1;j<=7;j++)
{
h1[j-1]=t[i][j-1];
}
if(h1[0]=="0")
{
h1[0]=Boolean.FALSE;
}
de.insertRow(i,h1);
}
//jsp.setViewportView(Table);
}
replace evetything inside while(rs.next()) to de.addRow(new Object[..., ..., ...]);
you have to declare DefaultTableModel de as local variable, initialized before fun is called
then to pass DefaultTableModel de to JTable, e.g. myTable(de); or myTable.setModel(de)
use Object[] instead of limitations for String[], then you can to store various data type in DefaultTableModel
From #mKorbel's answer
Create and add a DefaultTableModel like:
DefaultTableModel model=new DefaultTableModel(data,header);
JTable table = new JTable(model);
Here data is double vector and header is single vector.
data = get(field);
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};
model.addRow(d);
Get data from database
get(field){
//Your Database connection
//Get data into vector
//return vector
}

Categories