I can't re-reference a TableRow with findViewById - java

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

Related

Can I gain granular control of how a row is rendered in JAVA?

I am building a table in JAVA but some rows need to be completely different than most based on options.
In PHP I could loop a data set and apply an IF statement and change how a row is renedred in a webpage
while($r = $sth->fetch()){
if ($r['status']=='good'){
echo '<tr><td>This is good</td><td>yes it is</td></tr>';
}
else{
echo '<tr><td colspan="2">this is bad</td></tr>';
}
}
I only know one way to render a table in JAVA:
TableView<StatuTable> table = new TableView();
TableColumn<StatuTable, String> statusColumn = new TableColumn<>("Status");
statusColumn .setCellValueFactory(new PropertyValueFactory<>("status"));
TableColumn<StatuTable, String> noteColumn = new TableColumn<>("Note");
noteColumn .setCellValueFactory(new PropertyValueFactory<>("note"));
//loop the statusGroup defined elsewhere
ObservableList<StatusTable> statusList = FXCollections.observableArrayList();
for (Status status: statusGroup.getStatusRows()){
Can I alter the table row here:
if (status.getStatusType.equals("good")){
//make a different kind of row.
}
statusList.add(status);
}
table .setItems(statusList);
//this part is black magic as far as i am concerned
scheduleTable.getColumns().addAll(statusColumn, noteColumn);
Borrowing off of the example in this answer (https://stackoverflow.com/a/16864130/866021), you can do this via the getStyleClass() function on your TableRow.
Add an appropriate style class to your row:
nameRow.getStyleClass().add("italic");
Add a stylesheet to your scene which defines the italic style for table cells:
.italic.table-cell { -fx-font-style: italic; }

How to update a Bound JTable via code

I have a JTable bound with my database using Netbeans Wizard. Everything works fine but when I try to change the query and results based on filtering the table stops displaying the new results.
private static void updateResults() {
if (complaintList != null) {
LOG.log(Level.FINE, getQuery());
complaintList.clear();
complaintQuery = entityManager.createQuery(getQuery())
.setMaxResults(1000);
complaintList = complaintQuery.getResultList();
LOG.log(Level.INFO, "Result size: {0}", complaintList.size());
complaints.firePropertyChange(null, true, false);
}
}
Where:
complaintList is the list containing the results which is bound to the table.
complaintQuery is the bound Query.
I verified that the result has a size > 0. The contents of the table only update when I click/move one of the scroll bars.
Might not be pretty, but made it work by selecting the last row on the table after the change.
if (!complaintList.isEmpty()) {
complaints.changeSelection(complaintList.size() - 1, 0,
false, false);
}

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.

itextpdf: how to insert a new page when a table splits?

I'm using iTextPdf 5.4.1.
I have a table with many rows in it, and when the table auto-splits to the next page, I want to insert an Image and then another page break to continue the table's rows.
For example: say a table will take up 2 pages based on the number of rows it has.
The final output should be:
page 1: table rows that fit on first page
page 2: image
page 3: remaining table rows.
So, each time the table splits, i want to insert an image and then a page break.
I'm trying to use the PdfPTableEventSplit interface, as follows:
public class TableSplitEvent implements PdfPTableEventSplit
{
private Image pageImage;
private Document pdfDoc;
public TableSplitEvent( Image pageImage, Document pdfDoc )
{
super();
this.pageImage = pageImage;
this.pdfDoc = pdfDoc;
}
#Override
public void splitTable( PdfPTable table )
{
try
{
pdfDoc.add( pageImage );
pdfDoc.newPage();
}
catch ( DocumentException e )
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void tableLayout( PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart,
PdfContentByte[] canvases )
{
}
}
However, that doesn't seem to work as the event seems to get called after the table is rendered and before it is written to the pdf.
I'm getting:
page 1: image
page 2: table rows
page 3: table rows
Does anyone know how to do this?
If I'm not mistaken, we've received a code contribution for an event called PdfPTableEventAfterSplit. It will be integrated into iText in a couple of weeks and released by the end of July. Before that date, iText can't meet your needs. Thank you for your patience.

Database add item to list view?

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.

Categories