So I'm porting my Swing Java database application to Java FX (still a beginner here, I recently just learned the basics of FXML and the MVC pattern, so please bear with me).
I intend to load the data from my existing database to the "students" ObservableList so I can show it on a TableView, but on my original Swing code, I have a search TextField, and when the user clicks on a button or presses Enter, the program:
Executes an SQLite command that searches for specific records, and retrieves the RecordSet.
Creates a DefaultTableModel based on the RecordSet contents
And throws that TableModel to the JTable.
However, Java FX is a completely different beast (or at least it seems so to me--don't get me wrong, I love Java FX :D ) so I'm not sure what to do.
So, my question is, do I have to load ALL the students in the database, then use some Java code to filter out students that don't fit the search criteria (and display all students when the search text is blank), or do I still use SQLite in filtering and retrieving records (which means I need to clear the list then add students every time a search is performed, and maybe it will also mess up with the bindings? Maybe there will be a speed penalty on this method also? Besides that, it will also reset the currently selected record because I clear the list--basically, bad UI design and will negatively impact the usability)
Depending on the right approach, there is also a follow-up question (sorry, I really can't find the answer to these even after Googling):
If I get ALL students from database and implement a search feature in Java, won't it use up more RAM than it should, because I am storing ALL the database data in RAM, instead of just the ones searched for? I mean, sure, even my lowly laptop has 4GB RAM, but the feeling of using more memory than I should makes me feel somewhat guilty LOL
If I choose to just update the contents of the ObservableList every time a new search has been performed, will it mess up with the bindings? Do I have to set up bindings again? How do I clear the contents of the ObservableList before adding the new contents?
I also have the idea of just setting the selected table item to the first record that matches the search string but I think it will be difficult to use, since only one record can be highlighted per search. Even if we highlight multiple rows, it'd be difficult to browse all selected items.
Please give me the proper way, not the "easy" way. This is my first time implementing a pattern (MVC or am I actually doing MVP, I don't know) and I realized how unmaintainable and ugly my previous programs are because I used my own style. This is a relatively big project that I need to support and improve for several years so having clean code and doing stuff the right way should help in maintaining the functionality of this program.
Thank you very much in advance for your help, and I hope I don't come off as a "dumb person who can't even Google" in asking these questions. Please bear with me here.
Basic design tradeoffs
You can, of course, do this either of the ways you describe. The basic tradeoffs are:
If you load everything from the database, and filter the table in Java, you use more memory (though not as much as you might think, as explained below)
If you filter from the database and reload every time the user changes the filter, there will be a bigger latency (delay) in displaying the data, as a new query will be executed on the database, with (usually) network communication between the database and the application being the biggest bottleneck (though there are others).
Database access and concurrency
In general, you should perform database queries on a background thread (see Using threads to make database requests); if you are frequently making database queries (i.e. filtering via the database), this gets complex and involves frequently disabling controls in the UI while a background task is running.
TableView design and memory management
The JavaFX TableView is a virtualized control. This means that the visual components (cells) are created only for visible elements (plus, perhaps, a small amount of caching). These cells are then reused as the user scrolls around, displaying different "items" as required. The visual components are typically quite memory-consumptive (they have hundreds of properties - colors, font properties, dimensions, layout properties, etc etc - most of which have CSS representations), so limiting the number created saves a lot of memory, and the memory consumption of the visible part of the table view is essentially constant, no matter how many items are in the table's backing list.
General memory consumption computations
The items observable list that forms the table's backing list contains only the data: it is not hard to ballpark-estimate the amount of memory consumed by a list of a given size. Strings use 2 bytes per character, plus a small fixed overhead, doubles use 8 bytes, ints use 4 bytes, etc. If you wrap the fields in JavaFX properties (which is recommended), there will be a few bytes overhead for each; each object has an overhead of ~16 bytes, and references themselves typically use up to 8 bytes. So a typical Student object that stores a few string fields will usually consume of the order of a few hundred bytes in memory. (Of course, if each has an image associated with it, for example, it could be a lot more.) Thus if you load, say 100,000 students from a database, you would use up of the order of 10-100MB of RAM, which is pretty manageable on most personal computer systems.
Rough general guidelines
So normally, for the kind of application you describe, I would recommend loading what's in your database and filtering it in memory. In my usual field of work (genomics), where we sometimes need 10s or 100s of millions of entities, this can't be done. (If your database contains, say, all registered students in public schools in the USA, you may run into similar issues.)
As a general rule of thumb, though, for a "normal" object (i.e. one that doesn't have large data objects such as images associated with it), your table size will be prohibitively large for the user to comfortably manage (even with filtering) before you seriously stretch the memory capacity of the user's machine.
Filtering a table in Java (all objects in memory)
Filtering in code is pretty straightforward. In brief, you load everything into an ObservableList, and wrap the ObservableList in a FilteredList. A FilteredList wraps a source list and a Predicate, which returns true is an item should pass the filter (be included) or false if it is excluded.
So the code snippets you would use might look like:
ObservableList<Student> allStudents = loadStudentsFromDatabase();
FilteredList<Student> filteredStudents = new FilteredList<>(allStudents);
studentTable.setItems(filteredStudents);
And then you can modify the predicate based on a text field with code like:
filterTextField.textProperty().addListener((obs, oldText, newText) -> {
if (newText.isEmpty()) {
// no filtering:
filteredStudents.setPredicate(student -> true);
} else {
filteredStudents.setPredicate(student ->
// whatever logic you need:
student.getFirstName().contains(newText) || student.getLastName().contains(newText));
}
});
This tutorial has a more thorough treatment of filtering (and sorting) tables.
Comments on implementing "filtering via queries"
If you don't want to load everything from the database, then you skip the filtered list entirely. Querying the database will almost certainly not work fast enough to filter (using a new database query) as the user types, so you would need an "Update" button (or action listener on the text field) which recomputed the new filtered data. You would probably need to do this in a background thread too. You would not need to set new cellValueFactorys (or cellFactorys) on the table's columns, or reload the columns; you would just call studentTable.setItems(newListOfStudents); when the database query finished.
I currently have a ContentProvider that manages access to a database, which has several tables linked through foreign keys. One table maintains a list of (app-specific) audio files. There is also a table of sets; rows in the audio table must have an associated row in the set table (many-to-one).
ON CASCADE DELETE is active on the tables, so when rows in the set table are deleted, the rows in the audio table that referenced the set are also deleted.
My ContentProvider also deletes the referenced file when a call to delete() is made that targets the audio table.
The database side, therefore, works well. However, if the rows in the audio table are deleted, the files remain. I'd like to find a way of automatically removing those files.
One possible options seems to be to use a SQL trigger to run the undocumented _DELETE_FILE() function, a function apparently available in Android SQLite. Apparently the Android MediaProvider class uses this approach to delete files automatically.
Is using the _DELETE_FILE() function likely to work at all?
Would using _DELETE_FILE() be a violation of good practice, or indeed safe practice?
Is there a better, or more advisable way to achieve this automatic deletion of unreferenced files, perhaps through the ContentProvider? Approaches that require periodic scanning for unreferenced files strike me as inelegant, and ones that require manually performing cascades as cumbersome.
Similar question: How can I automatically delete a file referenced by a SQLite Database item when this item gets deleted from the database (in Android)?
In the context of displaying databases rows in an SWT VIRTUAL Table I am wondering if created TableItems are ever released by SWT in order for them to be garbage collected ?
Using virtual table allows us not to load the full model into memory by asking on the fly data to the database each time SWT needs it (through the SWT.setData listener). I am now wondering if an out of memory error can occur if the user scrolls for a very long time in a big table and thus all TableItem that have been displayed are somewhere in memory ?
Thanks in advance
Manu
After several investigations I confirm that SWT never releases the created TableItem. But, this is not a problem because of the Virtual style and SWT's power, a small amount of such items is created even if the user performs quick scrolling over all the table.
I am using Entity bean in NetBeans, to develop some master/detail forms. When I run the forms, I click the Delete JButton, and the row dissapears from the JTable.
But when I click on "Reload", the supposedly deleted row shows up again. I don't know why is this happening; why does the Entity doesn't erase all the way to the database table, and just deletes it out of the JTable?
This sort of issue sounds like it's related to the separation of the data (the model) from the view. I don't have specific knowledge regarding your technologies used, but hopefully I can provide some insight into what is the root of your problem.
In your case, it sounds like when you "Delete" you're only removing it from the view; you're not actually manipulating the data in any way (i.e. the model is not aware of this deletion).
Therefore once you "Reload" - which usually means that the view asks the model for what data to present - your "deletion" is lost since the model hasn't changed at all, and thus provides the exact same data to the view.
This sort of behavior is likely to occur when you're manipulating the data (i.e. deleting things) via the JTree itself or even the contained TreeNode objects, rather than the underlying TreeModel.
Hopefully this information helps you, sorry I don't have a more specific answer.
The JTable when reloaded, brought the record deleted because it had a foreign key link and couldn't deleted it at database level.
I am using 2 Tables (JTable) with their DefaultTableModels.
The first table is already populated.
The second table is populated for each row of the first table (using an SQL Query).
My purpose is to export every line of the first table with it's respective lines of the second in an Excel File.
I am doing it with a for (for each line of 1st table), in which I write a line of the 1st table in the Excel File, then I populate the 2nd table (for this line of 1st Table), I get every line from the Table (from it's Model actually) and put it in the Excel File under the current line of 1st table.
This means that if I have n lines in first table I will clear and populate again the second table n times.
All this code is called in a seperate thread.
THE PROBLEM IS:
Everything works perfectly fine ecxept that I am getting some exceptions.
The strange thing is that I'm not getting anything false in my result.
The Excel file is perfect.
Some of the lines of the exceptions are:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
at java.util.Vector.elementAt(Vector.java:427)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:632)
at javax.swing.JComponent.paint(JComponent.java:1017)
at javax.swing.RepaintManager.paint(RepaintManager.java:1220)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:803)
I am assuming that the problem lies in the fact that the second table needs some more time to be populated before I try to get any data from it. That's why I see RepaintManager and paintDirtyRegions in my exceptions.
Another thing I did is that I ran my program in debug mode and I put a breakpoint after each population of the 2nd table. Then I pressed F5 to continue for each population of 2nd table and no exception appeared. The program came to it's end without any exceptions.
This is another important fact that tells me that maybe in this case I gave the table enough time to be populated.
Of course you will ask me:
If your program works fine, why do you care about the exceptions?
I care for avoiding any future problems and I care to have a better understanding of Java and Java GUI and threads.
Why do you depend on a GUI component (and it's model) to get your information and why don't you recreate the resultset that populates your tables using an SQL Query and get your info from the resultset?
That would be the best and the right way. The fact is that I have the tables code ready and it was easier for me to just get the info from them. But the right way would be to get everything direct from database. Anyway what I did brought out my question, and answering it would help me understand more things about java. So I posted it.
The Swing API is not thread-safe except for a few method calls: repaint, revalidate, and invalidate. All other calls unless otherwise noted for a specific class must be made on the Event Dispatch Thread.
Transferring such call processing from a spawned background/worker thread can be done via SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait().
There is also some specific discussion regarding both JTable and any TableModel that has been attached to an instance of it in the javax.swing package summary javadocs. Neither is thread-safe, so any calls accessing data from them must be performed on the Event Dispatch Thread.
This is the most probable cause of the exceptions you are encountering, and the different behavior that you experience when running in a debugger is a classic sign of a race condition. There is also no reliable way to hack around this via introducing your own locks, etc. Such practices invariably lead to trouble (such as deadlocks with the Event Dispatch Queue lock deep inside the Swing library) in the long run since Swing really, truly was not designed to be thread-safe.
The exception is happening because one of the table models is returning null for a getValueAt(int row,int column) call. The reason for this is probably an internal issue in swing or the data model due to the fact that you are using a secondary thread to access the data models. The swing api specifically states that you can not use a secondary thread in the way you described.
The following article provides further details on the single thread rule in swing.
http://java.sun.com/products/jfc/tsc/articles/threads/threads3.html