57613

Java SwingWorker load data from database to List

Question:

I have a problem with my MVC application that displays data in a JTable. Everything worked fine, but I decided to add a SwingWorker to retrieve data from the database.

My controller calls the model with data from the database. It looks like this.

Model.java

public class Model { private List<Category> people = new Vector<Category>(); public List<Category> getPeople() { return new ArrayList<Category>(people); } public void load() throws Exception { people.clear(); DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL); CategoryDAO personDAO = factory.getCategoryDAO(); people.addAll(personDAO.getCategory()); } }

I add SwingWorker to getCategory class

MySQLCategodyDAO.java

public class MySQLCategoryDAO extends SwingWorker<Void, Vector<Object>> implements CategoryDAO{ private Job job; private List<Category> cat; public MySQLCategoryDAO(Job job){ this.job = job; } @Override protected Void doInBackground() throws Exception { // TODO Auto-generated method stub if(job == Job.SELECT){ getCategory(); System.out.println("Table selected"); } return null; } @Override() public void done(){ } public List<Category> getCategory() throws SQLException { cat = new ArrayList<Category>(); Connection conn = Database.getInstance().getConnection(); System.out.println(conn); String sql = "select id, name from kategorie"; Statement selectStatement = conn.createStatement(); ResultSet results = selectStatement.executeQuery(sql); while(results.next()) { int id = results.getInt("id"); String name = results.getString("name"); Category category = new Category(id, name); cat.add(category); } results.close(); selectStatement.close(); return cat; } }

View just retrieves the data from the model:

people = model.getPeople(); for (Category person : people) { tablemodel .addRow(new Object[] { person.getId(), person.getName() }); }

The problem comes when you call SwingWorker in class Model.java

public void load() throws Exception { people.clear(); DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL); CategoryDAO personDAO = factory.getCategoryDAO(); people.addAll(new MySQLCategoryDAO(Job.SELECT).execute()); - ERROR }

Error:-

The method addAll(Collection<? extends Category>) in the type List<Category> is not applicable for the arguments (void)

I know SwingWorker returns nothing, because there is an error. I should write the code in the method done(), but I have no idea how to solve it.

Answer1:

execute does not have a return value so it can't be used in the way you are trying to use it. The idea of SwingWorker is that the task should be executed asynchronously so you need to rework your design.

The SwingWorker bears a result (the List<Category>) and you either need to:

<ul><li>put the result somewhere from inside the SwingWorker (such as with the publish mechanism)</li> <li>or call get from the outside to wait for the task to finish and return.</li> </ul>

Here is the tutorial for review: <a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html</a>

Quick example:

class MySQLCategoryDAO extends SwingWorker<Void, Category> { // ... private List<Category> list; // do not modify inside doInBackground MySQLCategoryDAO(Job job, List<Category> list) { this.list = list; // ... } @Override protected Void doInBackground() { // ... while(results.next()) { int id = results.getInt("id"); String name = results.getString("name"); publish(new Category(id, name)); // publish results to the EDT } // ... return null; } @Override protected void process(List<Category> chunks) { list.addAll(chunks); // add results to the list on the EDT // add to the JTable (?) } } public void load() throws Exception { people.clear(); DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL); CategoryDAO personDAO = factory.getCategoryDAO(); // just execute new MySQLCategoryDAO(Job.SELECT, people).execute(); }

If you want to populate the entire table at once then you can also publish a List after the loop instead of one Category at a time. process would receive a List<List<Category>> with a singular element.

Answer2:

<strong>Sorry my mistake.</strong> From the view gets to model.getPeople (), but nothing is returned. I did a test:

But nothing is returned

public class Model { private List<Category> people = new Vector<Category>(); public List<Category> getPeople() { for (Category person : people) { System.out.println(person.getName()); //no data } return new ArrayList<Category>(people); } public void load() throws Exception { people.clear(); DAOFactory factory = DAOFactory.getFactory(DAOFactory.MYSQL); new MySQLCategoryDAO(Job.SELECT,people).execute(); } }

Recommend

  • Problems only in deleting and upgrading table rows using Hibernate on Spring Application [duplicate]
  • Getting a generic method to infer the type parameter from the runtime type
  • Finding parents in a tree hierarchy for a given child LINQ (lambda expression)
  • Time taken for Hadoop job to execute
  • Catch 500 internal server error with System.WebClient
  • SSH in Bash Script Messing Up File Read
  • Yii2: Using Kartik Depdrop Widget?
  • How to determine the CCSID used in CPYFRMIMPF command?
  • Is there any way to use wpdb prepare statements for array implode(' OR ', $myArray)?
  • Cannot invoke my method on the array type int[]
  • php is_file always return false
  • Most efficient way to move table rows from one table to another
  • How do I get the list of bad records that didn't load in Bigquery?
  • Regarding starting the threads on a condition
  • Autofac with Web API 2 - Parameter-less constructor error
  • Laravel: Getting Session ID oddly truncates when using foreach
  • Bypass multiple inheritance in Java
  • GridView breaks while scrolling
  • Could not find rake using whenever rails
  • Highlight and Bold text in JTextPane
  • NHibernate Validation Localization with S#arp Architecture
  • Q promise. Difference between .when and .then
  • Recording logins for password protected directories
  • How to access EntityManager inside Entity class in EJB3
  • how to do an event when i swipe from fragment to the other
  • Update CALayer sublayers immediately
  • JFileChooser in front of fullscreen Swing application
  • Opengl-es onTouchEvents problem or a draw problem? [closed]
  • Knitr HTML Loop - Some HTML output, some R output
  • what is the difference between the asp.net mvc application and asp.net web application
  • Akka Routing: Reply's send to router ends up as dead letters
  • AT Commands to Send SMS not working in Windows 8.1
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How do I configure my settings file to work with unit tests?
  • Is it possible to post an object from jquery to bottle.py?
  • unknown Exception android
  • EntityFramework adding new object to nested object collection
  • Checking variable from a different class in C#
  • failed to connect to specific WiFi in android programmatically
  • How can I use threading to 'tick' a timer to be accessed by other threads?