Populating a table from a file only last column is populated JavaFX [duplicate] - file

This has baffled me for a while now and I cannot seem to get the grasp of it. I'm using Cell Value Factory to populate a simple one column table and it does not populate in the table.
It does and I click the rows that are populated but I do not see any values in them- in this case String values. [I just edited this to make it clearer]
I have a different project under which it works under the same kind of data model. What am I doing wrong?
Here's the code. The commented code at the end seems to work though. I've checked to see if the usual mistakes- creating a new column instance or a new tableview instance, are there. Nothing. Please help!
//Simple Data Model
Stock.java
public class Stock {
private SimpleStringProperty stockTicker;
public Stock(String stockTicker) {
this.stockTicker = new SimpleStringProperty(stockTicker);
}
public String getstockTicker() {
return stockTicker.get();
}
public void setstockTicker(String stockticker) {
stockTicker.set(stockticker);
}
}
//Controller class
MainGuiController.java
private ObservableList<Stock> data;
#FXML
private TableView<Stock> stockTableView;// = new TableView<>(data);
#FXML
private TableColumn<Stock, String> tickerCol;
private void setTickersToCol() {
try {
Statement stmt = conn.createStatement();//conn is defined and works
ResultSet rsltset = stmt.executeQuery("SELECT ticker FROM tickerlist order by ticker");
data = FXCollections.observableArrayList();
Stock stockInstance;
while (rsltset.next()) {
stockInstance = new Stock(rsltset.getString(1).toUpperCase());
data.add(stockInstance);
}
} catch (SQLException ex) {
Logger.getLogger(WriteToFile.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Connection Failed! Check output console");
}
tickerCol.setCellValueFactory(new PropertyValueFactory<Stock,String>("stockTicker"));
stockTableView.setItems(data);
}
/*THIS, ON THE OTHER HAND, WORKS*/
/*Callback<CellDataFeatures<Stock, String>, ObservableValue<String>> cellDataFeat =
new Callback<CellDataFeatures<Stock, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<Stock, String> p) {
return new SimpleStringProperty(p.getValue().getstockTicker());
}
};*/

Suggested solution (use a Lambda, not a PropertyValueFactory)
Instead of:
aColumn.setCellValueFactory(new PropertyValueFactory<Appointment,LocalDate>("date"));
Write:
aColumn.setCellValueFactory(cellData -> cellData.getValue().dateProperty());
For more information, see this answer:
Java: setCellValuefactory; Lambda vs. PropertyValueFactory; advantages/disadvantages
Solution using PropertyValueFactory
The lambda solution outlined above is preferred, but if you wish to use PropertyValueFactory, this alternate solution provides information on that.
How to Fix It
The case of your getter and setter methods are wrong.
getstockTicker should be getStockTicker
setstockTicker should be setStockTicker
Some Background Information
Your PropertyValueFactory remains the same with:
new PropertyValueFactory<Stock,String>("stockTicker")
The naming convention will seem more obvious when you also add a property accessor to your Stock class:
public class Stock {
private SimpleStringProperty stockTicker;
public Stock(String stockTicker) {
this.stockTicker = new SimpleStringProperty(stockTicker);
}
public String getStockTicker() {
return stockTicker.get();
}
public void setStockTicker(String stockticker) {
stockTicker.set(stockticker);
}
public StringProperty stockTickerProperty() {
return stockTicker;
}
}
The PropertyValueFactory uses reflection to find the relevant accessors (these should be public). First, it will try to use the stockTickerProperty accessor and, if that is not present fall back to getters and setters. Providing a property accessor is recommended as then you will automatically enable your table to observe the property in the underlying model, dynamically updating its data as the underlying model changes.

put the Getter and Setter method in you data class for all the elements.

Related

Retrieving every field of a database row as object in zend framework 2

I know we have result set to get a row as object But How can I get every field as a separate object ? consider of this database row :
user_id address_id product_id shop_id
5 3 134 2
I want to retrieve and save the row as follows :
userEntity AddressEntity ProductEntity ShopEntity
This is not how the TableDataGateway is supposed to be used, since what you are looking for are more complex features such as the ones of Doctrine 2 ORM and similar data-mappers.
Here is one possible solution to the problem, which involves using a custom hydrator (docs). My example is simplified, but I hope it clarifies how you are supposed to build your resultset.
First, define your entities (I'm simplifying the example assuming that UserEntity is the root of your hydration):
class UserEntity {
/* fields public for simplicity of the example */
public $address;
public $product;
public $shop;
}
class AddressEntity { /* add public fields here for simplicity */ }
class ProductEntity { /* add public fields here for simplicity */ }
class ShopEntity { /* add public fields here for simplicity */ }
Then, build hydrators specific for the single entities:
use Zend\Stdlib\Hydrator\HydratorInterface as Hydrator;
class AddressHydrator implements Hydrator {
// #TODO: implementation up to you
}
class ProductHydrator implements Hydrator {
// #TODO: implementation up to you
}
class ShopHydrator implements Hydrator {
// #TODO: implementation up to you
}
Then we aggregate these hydrators into one that is specifically built to hydrate a UserEntity:
class UserHydrator extends \Zend\Stdlib\Hydrator\ObjectProperty {
public function __construct(
Hydrator $addressHydrator,
Hydrator $productHydrator,
Hydrator $shopHydrator
) {
$this->addressHydrator = $addressHydrator;
$this->productHydrator = $productHydrator;
$this->shopHydrator = $shopHydrator;
}
public function hydrate(array $data, $object)
{
if (isset($data['address_id'])) {
$data['address'] = $this->addressHydrator->hydrate($data, new AddressEntity());
}
if (isset($data['product_id'])) {
$data['product'] = $this->productHydrator->hydrate($data, new ProductEntity());
}
if (isset($data['shop_id'])) {
$data['shop'] = $this->shopHydrator->hydrate($data, new ShopEntity());
}
return parent::hydrate($data, $object);
}
}
Now you can use it to work with your resultset. Let's define the service for your UserEntityTableGateway:
'UserEntityTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new UserHydrator());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
These are all simplified examples, but they should help you understanding how powerful hydrators can be, and how you can compose them to solve complex problems.
You may also check the chapters in the documentation about the Aggregate Hydrator and Hydration Strategies, which were designed specifically to solve your problem.

Autofixture test for invalid constructor parameter

I have the following class and test. I want to test passing a null value as a parameter to the constructor and are expecting an ArgumentNullException. But since I use the Autofixture's CreateAnonymous method I get a TargetInvocationException instead.
What is the correct way to write those kinds of tests?
public sealed class CreateObject : Command {
// Properties
public ObjectId[] Ids { get; private set; }
public ObjectTypeId ObjectType { get; private set; }
public UserId CreatedBy { get; private set; }
// Constructor
public CreateObject(ObjectId[] ids, ObjectTypeId objectType, UserId createdBy) {
Guard.NotNull(ids, "ids");
Guard.NotNull(objectType, "objectType");
Guard.NotNull(createdBy, "createdBy");
Ids = ids;
ObjectType = objectType;
CreatedBy = createdBy;
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void constructor_with_null_ids_throw() {
fixture.Register<ObjectId[]>(() => null);
fixture.CreateAnonymous<CreateObject>();
}
IMO, Ruben Bartelink's comment is the best answer.
With AutoFixture.Idioms, you can do this instead:
var fixture = new Fixture();
var assertion = new GuardClauseAssertion(fixture);
assertion.Verify(typeof(CreateObject).GetConstructors());
The Verify method will provide you with a quite detailed exception message if any constructor argument in any constructor is lacking a Guard Clause.
FWIW, AutoFixture extensively uses Reflection, so I don't consider it a bug that it throws a TargetInvocationException. While it could unwrap all TargetInvocationException instances and rethrow their InnerException properties, that would also mean disposing of (potentially) valuable information (such as the AutoFixture stack trace). I've considered this, but don't want to take AutoFixture in that direction, for exactly that reason. A client can always filter out information, but if information is removed prematurely, no client can get it back.
If you prefer the other approach, it's not too hard to write a helper method that unwraps the exception - perhaps something like this:
public Exception Unwrap(this Exception e)
{
var tie = e as TargetInvocationException;
if (tie != null)
return tie.InnerException;
return e;
}
I came across this while I was searching for something similar. I would like to add that, combined with automoqcustomization and xunit, below code also works and its much cleaner.
[Theory, AutoMoqData]
public void Constructor_GuardClausesArePresent(GuardClauseAssertion assertion)
{
assertion.Verify(typeof(foo).GetConstructors());
}
You just need to create the AutoMoqData attribute as follows.
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute() : base(() => new Fixture().Customize(new AutoMoqCustomization()))
{
}
}

One-way updates of columns using EntityFramework

EntityFramework 4.3.1.
What is the best way to have calculated properties which should be stored in db, but are not intended to be retrieved from db?
E.g.
[Column("SOME_COLUMN")]
public ulong SomeColumn
{
get { return /*calculate here*/; }
}
I want the value to be persisted when I'm saving to db. But of course - not getting updated when I load from db. I can have an empty setter alongside... But it doesn't seem to work when the column is Key.
Can I have such a Key-column?
Now I'm getting this error:
EntityFramework error: The value of a property that is part of an object's key does not match the corresponding property value stored in the ObjectContext. This can occur if properties that are part of the key return inconsistent or incorrect values or if DetectChanges is not called after changes are made to a property that is part of the key.
Firstly, make the setter private:
[Column("SOME_COLUMN")]
public ulong SomeColumn { get; private set; }
Secondly, add a calculation method in the object (so it can access the private setter):
public void CaculateSomeColumn(){
this.SomeColumn = /* some calculation */;
}
Thirdly, add a SavingChanges callback to the Repository context object (MyEntities). This callback can be defined in the context constructor, and it should set the calculated field for items of your type (MyPoco) that were added or modified:
public MyEntities(){
this.SavingChanges += (sender, eventArgs) => {
ObjectContext context = sender as ObjectContext;
if (context != null)
{
foreach (ObjectStateEntry entry in
context.ObjectStateManager.GetObjectStateEntries(
EntityState.Added | EntityState.Modified))
{
if (!entry.IsRelationship && (entry.Entity.GetType() == typeof(MyPoco)))
{
var myObject = entry.Entity as MyPoco;
myObject.CalculateSomeColumn();
}
}
}
};
}

Override two collection - pattern

I have Model like this
interface IStudent {
string Name;
List<Subjects> Marks;
int RollNumber;
}
class ViewModel {
ObservableCollection<IStudent> FromExcel;
ObservableCollection<IStudent> FromDB;
}
I need to bind the union of both collection on UI. Whats the best way. I was thinking of having another property ObservableCollection<IStudent> FromBoth; generated using LINQ Union method with comparer. My question is
Is it fine to have three collection to bind on UI? Note: I need to remove duplicates, giving priority to data from excel.
I need to pick some data from DB rather than excel in certain case.
For example: name="hungrymind" in fromExcel and name="hungrymind concepts" on fromDB collection. By default, grid on UI should show hungrymind (priority to excel), but if user uncheck column(aka property) from UI, then priority to data for that column becomes DB, i.e, UI should show "hungrymind concepts"
What should be approach to achieve this. My approach would be on user event, pick data from FromDB or FromExcel for each items in the collection and assign it to property in FromBoth collection. Since there are more than 100 columns, I had to use reflection, but wouldn't be slow down the performance? If I avoid reflection, then I have to write a method for each column. Any suggestion on pattern or approach ?
I solved the issue like this
interface IStudent {
string Name { get; set; }
List<Subjects> Marks { get; set; }
int RollNumber { get; set; }
}
class EntityViewModel: IStudent {
IStudent FromExcel;
IStudent FromDB;
public string Name {
get { return Choose("Name").Name; }
set { Choose("Name").Name = value; }
}
public string RollNumber{
get { return Choose("RollNumber").RollNumber; }
set { Choose("RollNumber").RollNumber = value; }
}
internal IStudent Choose(string propertyName){
if(IsOveridable(propertyName))
return this.FromExcel;
else
return this.FromDB
}
}
class ViewModel{
ObservableCollection<EntityViewModel> Entities;
}
In that case why don't you build a meta-model which would help you in organizing the data, like for instance
String objectName
String dataType
String defaultName
String displayName
String userSelectedName
boolean isUserOvverride
String viewType // (i.e. Text Input, Combo Box, Text Area, Radio Button, Multi Line List)
String viewElementTypeId // (i.e. for Combo Box,Radio Button this refers to user options available and for Text Input or Area it would be null)
Though the above approach decreases the performance but you can adopt to any number of types that might come in tomorrow.

NHibernate, WinForms, and DataBinding - do they play well together?

I've been using WinForms databinding to display data from a database mapped with Fluent NHibernate, and that's been working great.
For example, I can just set a DataGridView's DataSource property from an entity's IList property, and voila - there's all the data!
But now I need to start adding and saving new data rows, and that's not going so well. I thought I'd be able to just enable the grid's AllowUserToAddRows property, and new rows would get added to the underlying IList in the entity, but that didn't work.
Then, after a little searching, I tried setting the DataSource property to a BindingList that was populated from the IList, but that's not being updated with new rows either.
During the course of my searches, I also came upon a few people reporting difficulty with WinForms and DataBinding in general, which makes me wonder if I should pursue that approach any further.
Is the DataBinding approach worth continuing? If so, can anyone suggest where I'm going wrong?
Or is it better to just handle all the DataGridView events associated with adding a new row, and writing my own code to add new objects to the IList property in my entity?
Other suggestions? (though I don't think switching to WPF is going to be an option, no matter how much better the databinding may be)
Can you load (or copy) your nHibernate entities into a generic List? If so, I have had good success in with two-way binding using a DataGridView bound to a generic List.
The key points are:
The generic list contains list objects where each is an instance of your custom class.
Your custom class must implement public properties for each of the fields to bind. Public fields didn't work for me.
Use a BindingSource to wrap the actual generic list.
The BindingSOurce allows you to set the AllowNew property to true. Binding directly to the List almost works, but the DataGridVieww does not display the "New row" line, even if AllowUsersToAddRows = true.
For example, add this code to a Form with a dataGridView1:
private List<MyObject> m_data = new List<MyObject>();
private BindingSource m_bs =new BindingSource();
private void Form1_Load(object sender, EventArgs e)
{
m_data.Add(new MyObject(0,"One",DateTime.Now));
m_data.Add(new MyObject(1, "Two", DateTime.Now));
m_data.Add(new MyObject(2, "Three", DateTime.Now));
m_bs.DataSource = m_data;
m_bs.AllowNew = true;
dataGridView1.DataSource = m_bs;
dataGridView1.AutoGenerateColumns = true;
dataGridView1.AllowUserToAddRows = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
for (int i = 0; i < m_data.Count ; i++)
{
Console.WriteLine(string.Format("{0} {1} {2}", m_data[i].ID, m_data[i].Name, m_data[i].DOB));
}
}
}
public class MyObject
{
// Default ctor, required for adding new rows in DataGridView
public MyObject()
{
}
public MyObject(int id, string name, DateTime dob)
{
ID = id;
Name = name;
DOB = dob;
}
private int m_id;
public int ID
{
get
{
return m_id;
}
set
{
m_id = value;
}
}
private string m_name;
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
private DateTime m_dob;
public DateTime DOB
{
get
{
return m_dob;
}
set
{
m_dob = value;
}
}
}
When the form closes, the contents of the bound List are printed to the Output window.

Resources