This question already has answers here:
JavaFX - Background Thread for SQL Query
(2 answers)
Closed 8 years ago.
I have a question. How can I do asynchrous database in JavaFX. I know that exist SwingWoker but I read that I can't use this in JavaFX. I read about Task but I can do convert the result to ObservableList but I need normal LinkedList.
I'm trying conntect to mysql database
I know that this forum has a lot of answering about database in javafx but all results are converted to ObservableList
Thank you for all the answers.
FlightControllerTask.java
public class FlightControllerTask extends Task<LinkedList<Flight>>{
private final static int MAX=10000;
ArrayList<Airport> airportList=new ArrayList<>()
#Override
protected LinkedList<Flight> call() throws Exception {
for (int i = 0; i < MAX; i++) {
updateProgress(i, MAX);
Thread.sleep(5);
}
LinkedList<Flight> flightList = new LinkedList<>();
Connection c ;
c = DBConnector.connect();
String SQL = "SELECT flight.idflight, airport.nameAirport, airport.nameAirport, flight.departureTime FROM flight INNER JOIN airport";
ResultSet rs = c.createStatement().executeQuery(SQL);
while(rs.next()){
flightList.add(new Flight(rs.getInt("idflight"), rs.getString("flightFrom"), rs.getString("flightTo"), rs.getTime("departureTime")));
}
return flightList;
}
FlightControllerService
public class FlightControllerService extends Service<LinkedList<Flight>>{
#Override
protected Task<LinkedList<Flight>> createTask() {
return new FlightControllerTask();
}
}
MainController.java
final FlightControllerService service= new FlightControllerService();
ReadOnlyObjectProperty<LinkedList<Flight>> flightList =service.valueProperty();
flightList.get();
public class FlightControllerTask extends Task<LinkedList<Flight>>{
#Override
protected LinkedList<Flight> call() throws Exception {
// load data
return data;
}
}
// usage:
FlightControllerTask task = new FlightControllerTask();
task.setOnSucceeded(ev -> task.getValue());
new Thread(task).start();
Now the part with task.getValue() is the crucial part, with this method you can retrieve the value that was computed with the task as soon as is is ready (thus the succeeded hook).
Related
I have some code that generates answers based on the user input. But in somecases i need to update the values later by calling SetAnswers But when i compile my code i get the following error:
NullReferenceException: Object reference not set to an instance of an object
I get this error on the line marked by the arrow.
See below for my code:
public class Generate_Questions : MonoBehaviour{
public Question q5, q4;
void Start(){
q4 = create_question("Select object to edit", EXTERNAL);
Visual_Question vq1 = new Visual_Question(1, q4, new vector(1,1,1), Ui, Canvas);
vq1.draw_question();
}
void Update(){
}
public class Visual_Question : Generate_Questions{
public Visual_Question(int order_id, Question q, Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas){
}
public void draw_question(){
q4.SetAnswers(new Answer[]{ <--------- this generates the error.
new Answer(null, "Select an option")
});
}
}
public class Question{
public string text;
public int answers_loc;
public List<Answer> answers;
public Question(string q_text, int answers_loc){
answers = new List<Answer>();
this.text = q_text;
this.answers_loc = answers_loc;
}
public void SetAnswers(Answer[] c_answers){
foreach(Answer answer in c_answers){
this.answers.Add(answer);
}
}
public bool CheckIfAnswersAvailable(){
if(answers.Count > 0){
return true;
}else{
return false;
}
}
public int QuestionLocation(){
return answers_loc;
}
}
public Question create_question(string text, int a_type){
Question Q = new Question(text, a_type);
return Q;
}
public interface IAnswer{
string GetText();
string GetDataType();
object GetValue();
Question GetNextQuestion();
}
public class Answer : IAnswer{
public string text;
public Question next = null;
public int? action = null;
public Element obj = null;
public string property = null;
public float? value = null;
public Answer(Question next, string text){
this.text = text;
this.next = next;
}
public Answer(Question next, string text, Element obj, int? action){
this.action = action;
this.text = text;
this.next = next;
this.obj = obj;
}
public Answer(Question next, string text, Element obj, int? action, string property, float? value){
this.action = action;
this.next = next;
this.text = text;
this.obj = obj;
this.property = property;
this.value = value;
}
public string GetText(){
return text;
}
public string GetDataType(){
throw new System.NotImplementedException();
}
public object GetValue(){
return value;
}
public Question GetNextQuestion(){
return next;
}
}
}
how would i go about fixing this problem? I am a complete newbie to c#. So my question may be already answered but i just dont know what i am looking for.
I assume that IAnswer[] is an interface and since you are trying to initialize an abstract object you get that runtime exception
NullReferenceException: Object reference not set to an instance of an object
if you want to create instance of IAnswer object you have to restructure it like class or structure.
Your class Visual_Question derives from Generate_Questions, so the member q4 that you use en draw_question is not initialized. This is not the member of Generated_Questions but a member of Visual_Question that is not initialized.
In Generate_Questions you are creating a new instance of Visual_Question and then immediately calling draw_question on that new instance. You now have 2 instances of a question (both derive from Generate_Questions), but only one of them has had the Start method, which initializes q4 called. If, however, you attempt to call Start from your second instance, you're going to find yourself in an infinite series of recursive calls and quickly crash with a different error (a stack overflow in this case).
One issue with the current code is that Generate_Questions sounds more like an action than a class. I'd suggest removing the inheritance from Visual_Question and make that an interface that you would implement on Question. Question should probably have the create_question method removed. That probably belongs in a MonoBehavior script (technically it's a factory method -- look up the factory pattern -- I'm not going to go into it here since this is a beginner topic).
Something like (obviously not complete):
public class Generate_Questions : MonoBehaviour
{
private IVisualQuestion q4;
void Start()
{
q4 = new Question("Select object to edit", EXTERNAL);
q4.DrawQuestion(new vector(1,1,1), Ui, Canvas)
}
void Update() {}
}
public interface IVisualQuestion
{
void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas);
}
public class Question : IVisualQuestion
{
// ... insert the Question constructor and code here ...
// Implement VisualQuestion interface
public void DrawQuestion(Vector2 loc, Dictionary<string, RectTransform> ui, RectTransform canvas)
{
this.SetAnswers(new Answer[]{new Answer(null, "Select an option")});
}
}
In general, you probably don't need inheritance. As you learn more C#, you'll discover that when inheritance is going to help it will be clear. More often than not, using an interface is a far better and flexible approach. As a commenter noted, you probably don't want to inherit from MonoBehavior. You really only need that for classes that the Unity Engine is going to directly handle.
Another note: the convention in C# is to name methods, variables, etc. in PascalCase, not using underscores to separate words.
I'm using JavaFX to create a basic GUI. I have a database created in MySQL to store the data. (DBConnect) (connector/j)
This is my very first attempt at connecting the two, as well as using ResultSets/DBConnect
Currently, I have 3 Classes: my Game class, my GameUI class (main), and my DBConnect class.
I am attempting to Reference the ResultSet in my GameUI class, that was originally declared in Game class.
public class Game {
private static DBConnect dbc;
private static Connection conn;
public ResultSet rs;
int id;
String name;
float price;
String vendor;
int rating;
public Game() {
try {
conn = dbc.connect();
String SQL = "Select * from Person";
rs = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE).executeQuery(SQL);
System.out.println("list result set for record..");
printRs(rs);
} catch(SQLException ignore) {
}
}
My User Defined moveNext() method:
public Game moveNext() {
Game g = new Game();
try {
if(rs.next() == false)
rs.previous();
g.setGameId(rs.getInt("gameId"));
g.setGameName(rs.getString("gameName"));
g.setPrice(rs.getFloat("price"));
g.setVendor(rs.getString("vendor"));
g.setRating(rs.getInt("rating"));
} catch(SQLException e) {
e.printStackTrace();
}
return g;
}
The GameUI class i am trying to reference it in:
public class GameUI extends Application {
private Button firstButton = new Button("First");
private Button createButton = new Button("Create");
private Button updateButton = new Button("Update");
private Button deleteButton = new Button("Delete");
private Button lastButton = new Button("Last");
private Button nextButton = new Button("Next");
private Button prevButton = new Button("Prev");
GridPane grid = new GridPane();
HBox hbox = new HBox(14);
private static DBConnect dbc;
private static Connection conn;
// private static
private Pane initButtons() {
hbox.getChildren().addAll(firstButton, createButton, updateButton, deleteButton, lastButton, nextButton, prevButton);
nextButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
Game.rs.moveNext();
}
});
return hbox;
}
My Question is, can I Reference my ResultSet (Game class) in my nextButton event handler (my GameUI class) OR do I have to declare a new result set?
Is this the right place for my user defined moveNext() method, or should I use next()?
I will post more code on request.
You can pass the result set further, but it is bad practice (See Is it Ok to Pass ResultSet?). From what I see from the code you posted it is mainly an issue with the layering of the different parts of the application, that should be separated:
Database related code belong into one layer. No other layer should directly talk to the DB or handle any DB specific objects. To achieve this the DBConnection class should handle all database related stuff. To pass data from the database to the other layers and vice versa you use a data transfer object (DTO) which is basically an object representation of a specific result set. Usually this boils down to one DTO per database table.
Then you have an intermediate layer, lets call it service layer, which is used to communicate from the UI to the database and do some computation.
On top of that you have the UI layer where your application lives. Here you have to consider which actions belong into that layer and what should better be delegated to the service layer.
Take also a look at this wikipedia article: https://en.wikipedia.org/wiki/Multitier_architecture
I use Spring and Hibernate for my application and want to load some configuration data from DB when the application launches. But the question is how I can update the preloaded data in case the record in DB is updated (btw, I use mysql for the DB).
I found some solutions said using the trigger in mysql, but I don't know whether the trigger can call some WebService all send some events to tell the application.
Are there some more solutions or good ideas for the case?
Here's the sample code of preloading data:
#Service
public class PreloadService {
#Autowired
private ConfigurationDao configurationDao;
private Map<String, String> preloadConfs = null;
#PostConstruct
public void getConfigurations() {
Map<String, String> results = new HashMap<String, String>();
List<Configuration> confs = configurationDao.findConfigurations(null, null);
for (Configuration c: confs) {
results.put(c.getCode(), c.getDescription());
}
preloadConfs = results;
}
public String getDescription(String code) {
return preloadConfs.get(code);
}
}
and other class should use the class like this
#Autowired
private PreloadService preloadService;
public void foo() {
preloadService.getDescription("code");
}
So the question is how I can update the preloadConfs object if the configuration table was changed?
I have created a universalrepository that takes the type passed to it and when I create data entry method, the entity is created fine, but when I create a linked entity to it, i get the base entity created again. Any ideas why?
Details..
I have divided a specification into multiple tables to manage stuff...
Now I have got a person entity, an applicant entity...(in reality applicant and person are the same), a contractor entity. A contractor can only be created by an applicant and therefore an applicant will always be created and therefore a person will always be created.
When I go on creating a person, it creates a person fine, but when I create an applicant it creates a person again. Likewise when I create a contractor it creates a person and multiple applicants for some reason.
Here is my LINQ to SQL. If you notice in anyway I can improve this code, I will appreciate that too.
here is the repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;
namespace ParkingPermit.Models
{
public class UniversalManagerRepository<T> :IRepositoryT<T>
where T:class
{
private Table<T> _table;
private readonly DB _db ;//= new DB();
public UniversalManagerRepository()
{
_db = new DB();
_table = _db.GetTable<T>();
}
#region IRepositoryT<T> Members
public T Create(T create)
{
// _table = new DB().GetTable<T>();
//_db.GetTable(typeof(T)).InsertOnSubmit(create);
_table.InsertOnSubmit(create);
Save();
return create;
}
public void Delete(T delete)
{
throw new NotImplementedException();
}
public T Edit(T edit)
{
throw new NotImplementedException();
}
public T GetItem(int id)
{
throw new NotImplementedException();
}
public T Update(T update)
{
throw new NotImplementedException();
}
public IEnumerable<T> List()
{
//IQueryable i = _db.GetTable(typeof(T)).AsQueryable() ;
return _db.GetTable(typeof(T)) as IEnumerable<T>;
//throw new NotImplementedException();
}
public void Save()
{
//_db.SubmitChanges();
_table.Context.SubmitChanges();
//throw new NotImplementedException();
}
#endregion
}
}
I can post an image of the linq to sql designer if that helps, but I cant see the feature here...
Many thanksalt text http://img509.imageshack.us/img509/2072/linq.jpg
the thing is that when applicant is added and an applicant.Person is assigned from the session(in model binder), it creates a new person, which is actually the original person created in the beginning. How can I avoid that.
protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var personType = (Person)controllerContext.HttpContext.Session[PersonSessionKey];
controllerContext.HttpContext.Session[CurrentApplicantSessionKey] = null;
var av = new ApplicantValidator(new ModelStateWrapper(bindingContext.ModelState));
var newApplicant = bindingContext.Model as Applicant;
if (personType == null)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"Cannot Update this Instance directly, please restart the application");
// controllerContext.HttpContext.Session[PersonSessionKey] = personType;
}
else if (newApplicant != null)
{
if (newApplicant.Person != null)
{
if (newApplicant.Person.Equals(personType as Person))
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName,
"A person with these details already exists, please restart the application...");
//return
controllerContext.HttpContext.Session[PersonSessionKey] = null;
personType = null;
}
}
else if (av.Validate(newApplicant))
{
if (newApplicant.Person == null)
{
newApplicant.Person = personType as Person;
newApplicant.PersonId = personType.PersonId;
}
}
}
}
I have resolved this part and apparently its now giving issued with update, can anbody find anything unusual.
Answer to my first problem, was that in Model Binders the entity is being manipulated from sessions and the created back to the service layer.
Apparently it seems that because its all happening outside linq orm framework, this entity needs to be recreated as "From clause ...from ..in db." and then linq correctly recognizes it and does the correct job of insertion.
Can anyone help me with the update/edit..please
This question already has answers here:
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException
(2 answers)
Closed 5 years ago.
i am trying to create a mock shopping cart for a uni project. im using two java classes Item and shoppingCart, shopping cart uses a vector to store Items and then writes them to a file. i am trying to use the classes on a jsp page but when i try to write to the file i get an java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: cart.Item... any ideas how i could fix this??
From the javadoc on NotSerializableException... "Thrown when an instance is required to have a Serializable interface."
This means that your class that you're serializing need to implement the Serializable marker interface.
Here is a small Example to you...
import java.io.*;
class player implements Serializable{
String name;
double health;
double positionX;
double positionY;
int weapon;
}
class game{
public static void main(String[] args) throws Exception{
player character1 = new player();
character1.name = "Inukz";
character1.health = 82.62;
character1.positionX = 80;
character1.positionY = 33;
character1.weapon = 2;
player character2 = new player();
character2.name = "Prasad";
character2.health = 32.62;
character2.positionX = 40;
character2.positionY = 63;
character2.weapon = 3;
player character3 = new player();
character3.name = "Thilan";
character3.health = 12.62;
character3.positionX = 10;
character3.positionY = 83;
character3.weapon = 1;
FileOutputStream fileStream = new FileOutputStream("myGame.js",true);
ObjectOutputStream os = new ObjectOutputStream(fileStream);
os.writeObject(character1);
os.close();
}
}
To avoid NotSerializableException make sure:
your class implements Serializable
all non primitive members implement Serializable (or are transient instead)
if your class is an inner class it's either static or the outer class implements
Serializable
Besides that you also need to define serialVersionUID for every Serializable class. Check all 3 cases above plus:
all Serializable superclasses
if your class is an anonymous class, define it there too
Note: your code may run without serialVersionUID sometimes but read the last paragraph in Serializable's javadoc to understand why it will be a problem depending on the environment.
There's a VM option to add details to the exception. It shows the root and nested classes failing to serialize:
-Dsun.io.serialization.extendedDebugInfo=true