Refresh a table after adding data - java

I am building a football league management system, I built the user interface using javaFx, I created this class to populate the table using a database.
public class TableHandler {
public static ObservableList<Team> getTeams() {
ObservableList<Team> list = FXCollections.observableArrayList();
DBConnection db;
try {
db = new DBConnection();
String sql = "Select * from teams";
ResultSet result = db.read(sql);
while (result.next()) {
list.add(new Team(result.getInt(1), result.getString(2), result.getString(3), result.getInt(4),
result.getDouble(5)));
}
} catch (Exception e) {
e.getMessage();
}
return list;
}
public static TableView<Team> getTable(ObservableList<Team> list) {
TableView<Team> table;
TableColumn<Team, String> idColumn = new TableColumn<>("ID");
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
TableColumn<Team, String> nameColumn = new TableColumn<>("Name");
nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
TableColumn<Team, String> phoneNumberColumn = new TableColumn<>("phoneNumber");
phoneNumberColumn.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
TableColumn<Team, Integer> pointsColumn = new TableColumn<>("Points");
pointsColumn.setCellValueFactory(new PropertyValueFactory<>("points"));
TableColumn<Team, Double> budgetColumn = new TableColumn<>("Budget");
budgetColumn.setCellValueFactory(new PropertyValueFactory<>("budget"));
table = new TableView<>();
table.setItems(list);
table.getColumns().addAll(idColumn, nameColumn, phoneNumberColumn, pointsColumn, budgetColumn);
return table;
}
and I created a button to add teams to the table by the user, what I can't figuer out is how to refresh the table when the user hit the add button, any help would be appriciated.

You don't have to. The very idea of an observable list is that the TableView observes for changes in it and renders the value change accordingly.
The thing you have to make sure of is that you're adding elements to the collection that was actually bound to the TableView and not some other one. You didn't post the code that adds the items, so it's hard to tell, but if you're using getTeams() and then adding to that, then it's wrong (since it's a new ObservableList and not the one bound to the TableView). You should always be using table.getItems().add(...) to add items to a TableView.

Related

How to give DynamoDB update expression(if_not_exists) in TransactionaWriteRequest

I am new to DynamoDB and working on a dynamo project. I am trying to update the item amount in a transaction with condition if_not_exists() with TransactionWriteRequest in DynamoDB Mapper.
As per the Doc, transactionWriteRequest.updateItem() takes DynamoDBTransactionWriteExpression which doesn't have any UpdateExpression. Class definition is attached bellow.,
Wanted to know How can i provide the if_not_exists() in DynamoDBTransactionWriteExpression to update the item in a transaction. Or there is no way to do this in a transactionWrite.
Please help here.
Thanks in advance
Judging from the snippet you shared it seems you are using Java SDK v1. Below is a code snippet which has 1 PutItem and 1 UpdateItem combined in a single TransactWrite request.
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
final String ORDER_TABLE_NAME = "test1";
/*
Update Item with condition
*/
HashMap<String,AttributeValue> myPk =
new HashMap<String,AttributeValue>();
myPk.put("pk", new AttributeValue("pkValue1"));
Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
expressionAttributeValues.put(":new_status", new AttributeValue("SOLD"));
Update markItemSold = new Update()
.withTableName(ORDER_TABLE_NAME)
.withKey(myPk)
.withUpdateExpression("SET ProductStatus = if_not_exists(createdAt, :new_status)")
.withExpressionAttributeValues(expressionAttributeValues)
.withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD);
/*
Put Item
*/
HashMap<String, AttributeValue> orderItem = new HashMap<>();
orderItem.put("pk", new AttributeValue("pkValue2"));
orderItem.put("OrderTotal", new AttributeValue("100"));
Put createOrder = new Put()
.withTableName(ORDER_TABLE_NAME)
.withItem(orderItem)
.withReturnValuesOnConditionCheckFailure(ReturnValuesOnConditionCheckFailure.ALL_OLD);
/*
Transaction
*/
Collection<TransactWriteItem> actions = Arrays.asList(
new TransactWriteItem().withUpdate(markItemSold),
new TransactWriteItem().withPut(createOrder));
TransactWriteItemsRequest placeOrderTransaction = new TransactWriteItemsRequest()
.withTransactItems(actions)
.withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL);
try {
client.transactWriteItems(placeOrderTransaction);
System.out.println("Transaction Successful");
} catch (ResourceNotFoundException rnf) {
System.err.println("One of the table involved in the transaction is not found" + rnf.getMessage());
} catch (InternalServerErrorException ise) {
System.err.println("Internal Server Error" + ise.getMessage());
} catch (TransactionCanceledException tce) {
System.out.println("Transaction Canceled " + tce.getMessage());
} catch (AmazonServiceException e){
System.out.println(e.getMessage());
}
With the v2 version of the SDK you can do it like this
var table =
enhancedClient.table(<table name>, TableSchema.fromClass(DynamoEntity.class));
var transactWriteItemsEnhancedRequest = TransactWriteItemsEnhancedRequest
.builder()
.addUpdateItem(table,
TransactUpdateItemEnhancedRequest.builder(LoadTestEntity.class)
.item(<entity>)
.conditionExpression(Expression.builder().expression("attribute_not_exists(ID)").build())
.build())
.build();
enhancedClient.transactWriteItems(transactWriteItemsEnhancedRequest);
You might need to play around with the expression builder, I haven't tested it.

Vaadin 14 LTS Grid refresh after adding new data not working

I'm trying to refresh grid after adding an row into it, but it's not working. Here is my Event Listener on my UI Code : Edited Full code.
Grid<TransactionModel> transactionData = new Grid<>(TransactionModel.class);
try {
// transactionData.setItems(transactionServices.getTransactionTable());
List<TransactionModel> transactionList = transactionServices.getTransactionTable();
ListDataProvider<TransactionModel> transactionDataProvider = new ListDataProvider<>(transactionList);
transactionData.setDataProvider(transactionDataProvider);
transactionData.setColumns("id", "transactionTimestamp", "srcAccountId", "dstAccountId", "amount");
Grid.Column<TransactionModel> idColumn = transactionData.getColumnByKey("id");
Grid.Column<TransactionModel> srcAccountIdColumn = transactionData.getColumnByKey("srcAccountId");
Grid.Column<TransactionModel> dstAccountIdColumn = transactionData.getColumnByKey("dstAccountId");
HeaderRow filterRow2 = transactionData.appendHeaderRow();
TransactionFilterModel transactionFilterModel = new TransactionFilterModel();
transactionDataProvider.setFilter(transaction -> transactionFilterModel.find(transaction));
// Filter srcAccountId
TextField idField = new TextField();
idField.addValueChangeListener(event -> {
transactionFilterModel.setId(event.getValue());
transactionDataProvider.refreshAll();
});
idField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow2.getCell(idColumn).setComponent(idField);
idField.setSizeFull();
idField.getElement().setAttribute("focus-terget", "");
// Filter srcAccountId
TextField srcAccountIdField = new TextField();
srcAccountIdField.addValueChangeListener(event -> {
transactionFilterModel.setSrcAccountId(event.getValue());
transactionDataProvider.refreshAll();
});
srcAccountIdField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow2.getCell(srcAccountIdColumn).setComponent(srcAccountIdField);
srcAccountIdField.setSizeFull();
srcAccountIdField.getElement().setAttribute("focus-terget", "");
// Filter dstAccountId
TextField dstAccountIdField = new TextField();
dstAccountIdField.addValueChangeListener(event -> {
transactionFilterModel.setDstAccountId(event.getValue());
transactionDataProvider.refreshAll();
});
dstAccountIdField.setValueChangeMode(ValueChangeMode.EAGER);
filterRow2.getCell(dstAccountIdColumn).setComponent(dstAccountIdField);
dstAccountIdField.setSizeFull();
dstAccountIdField.getElement().setAttribute("focus-terget", "");
transactionData.setWidth("50%");
} catch (JsonProcessingException | EndpointException ex) {
Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ex);
}
// Event Listener
submitButton.addClickListener(e -> {
System.out.println("Submitted !");
AccountModel submittedModel = new AccountModel();
if (accountModelBinder.writeBeanIfValid(submittedModel)) {
try {
accountServices.registerAccount(submittedModel);
accountIdTextField.clear();
nameTextField.clear();
addressTextField.clear();
birthDateDatePicker.clear();
allowNegativeBalanceButtonGroup.clear();
} catch (EndpointException | JsonProcessingException ez) {
Logger.getLogger(MainView.class.getName()).log(Level.SEVERE, null, ez);
}
}
accountData.getDataProvider().refreshAll(); // <- REFRESH
});
And for service I'm using rest, here is the accountservice code:
public List<AccountModel> getAccountTable() throws JsonProcessingException, EndpointException {
List<AccountModel> datalog = new JsonResponseReader(restMockvaEndpoint.send(new EndpointRequestBuilder()
.method("GET")
.resource("/account")
.build()
)).getContentTable(AccountModel.class).getData();
return datalog;
}
public AccountModel registerAccount(AccountModel accountModel) throws JsonProcessingException, EndpointException{
AccountModel account = new JsonResponseReader(restMockvaEndpoint.send(new EndpointRequestBuilder()
.method("POST")
.content(Json.getWriter().writeValueAsBytes(accountModel), MediaType.APPLICATION_JSON)
.resource("/account")
.build())).getContentObject(AccountModel.class);
return account;
}
Edited : Add registerAccount.
The problem is when I click submitButton for adding new data, the grid doesn't refresh. Any ideas?
For this to work with a ListDataProvider, you would have to modify the underlying list (add/remove items).
Now that you call refreshAll(), it just reads the list you passed again, and as it still contains the same items, nothing changes. It does not know to fetch the items from your service again.
There are a few solutions that I can think of:
1. Manually add the new item to the list (it will then appear at the end of the grid):
accountList.add(submittedModel);
...
// This instructs the grid to read the list again
accountData.getDataProvider().refreshAll();
If your accountServices.registerAccount method returns the newly saved item, you might want to add that one instead.
2. Set the items again
You could fetch the items again and set a new data provider. You can just use setItems(...) then, which uses a ListDataProvider under the hood.
// Run this both when first creating the grid, and again after the new item is saved.
// This time you don't need to call refreshAll()
List<AccountModel> accountList = accountServices.getAccountTable();
accountData.setItems(accountList);
3. Use a lazy data provider
When you use a lazy data provider, for example from callbacks, then calling refreshAll() executes those callbacks again to fetch new items.
In this case you need to implement the needed service methods, and it requires a bit more work if you need sorting or filtering.
this.setDataProvider(DataProvider.fromCallbacks(
query -> myAccountService.getAccounts(query.getOffset(), query.getLimit()).stream(),
query -> myAccountService.countAccounts()
));

Scrolling the listview to position of the newly added item

I have a custom adapter with a listview. I query the items from SQL Server and display them as a list using my listview. I have item click listener on my list view in order to get the item position.
public void getData() {
String query = "SELECT * FROM Table";
List<Map<String, String>> data = new ArrayList<>();
data = filterData(query);
adapter = new ContactListAdapter(this, data, R.layout.items, from, to);
listView.setAdapter(adapter);
listView.invalidateViews();
listView.setOnItemClickListener((adapterView, view, i, l) -> {
HashMap<String, String> retreive = (HashMap<String, String>) adapterView.getAdapter().getItem(i);
callerID = retreive.get("CallerDetailID");
.
.
});
}
I store the values using hashmap strings in a list as follows.
// filter the contact details from sql server
List<Map<String, String>> filterData(String query) {
List<Map<String, String>> contact_details = new ArrayList<>();
try {
connect = connectionClass.CONN(); // Connect to database
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String, String> datanum = new HashMap<>();
datanum.put("CallerDetailID", rs.getString("CallerID"));
.
.
.
contact_details.add(datanum);
}
} catch (Exception e) {
e.printStackTrace();
}
return contact_details;
}
I am aware that I can get the items to the position by clicking on it (since I already use setOnItemClickListener). But my question here is how can I scroll to the newly added item's position in my list view, without clicking the item?
Once I get the position of the item, I can use one of the following methods in the listview to scroll.
listView.smoothScrollToPosition();
listView.smoothScrollToPosition();
listView.smoothScrollToPositionFromTop();
Is it possible to get the item's to position without clicking on the item in the listview? Any ideas folks.
To achieve the behaviour you need to add a property to scroll listview automatically.
android:transcriptMode="alwaysScroll"
You just have to call notifyDataSetChanged() and your list will be auto scrolled.

how to map a list of pojos in jdbcTemplate query without using a RowMapper class or BeanRowMapper

i'm trying to fill a list pojos using jdbcTemplate but i dont want to create a RowMapper class for every pojo in my domain,also i have less atributes in my domain classes and i have more in my tables in the databases so i can't use BeanRowMapper, i found a example in this website http://www.mkyong.com/spring/spring-jdbctemplate-querying-examples/
but my problem is that this example didn't worked at firts
the example is the following one:
public List<Customer> findAll(){
String sql = "SELECT * FROM CUSTOMER";
List<Customer> customers = new ArrayList<Customer>();
List<Map> rows = getJdbcTemplate().queryForList(sql);
for (Map row : rows) {
Customer customer = new Customer();
customer.setCustId((Long)(row.get("CUST_ID")));
customer.setName((String)row.get("NAME"));
customer.setAge((Integer)row.get("AGE"));
customers.add(customer);
}
return customers;
}
but this example was giving me a error in this line
List<Map> rows = getJdbcTemplate().queryForList(sql);
the error was this:
Error incompatible types: java.util.List<java.util.Map<java.lang.String,java.lang.Object>> cannot be converted to java.util.List<java.util.Map>
so netbeans after i right clicked the line, netbeans changed the line to this
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
so i didn't longer have that error, but now i method returns a list full of null objects, here is my method after the changes
#Override
public ArrayList<Rol> findAll() {
ArrayList<User> listOfUsers= null;
try
{
String sql = "select * from User";
listOfUsers = new ArrayList<User>();
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
for (Map row : rows)
{
User user= new User ();
user.setName((String)(row.get("name")));
user.setLastName((String)row.get("lastName"));
user.setType((String)row.get("type"));
listOfUsers .add(user);
}
}
catch (DataAccessException dataAccessException)
{
dataAccessException.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
return listOfUsers;
}
This code is working in one of my projects:
List<Map<String, Object>> rows = administradoresDao.list();
List<Administrador> usuarios = new ArrayList<>();
for (Map<String, Object> row : rows) {
Administrador usuario = new Administrador();
usuario.setId(Integer.valueOf(row.get("id").toString()));
usuario.setNombre(row.get("nombre").toString()+ " "+row.get("a_pat").toString()+" "+row.get("a_mat").toString());
usuario.setDependencia(row.get("dependencia").toString());
usuario.setEmail(row.get("email").toString());
usuario.setTelefono(row.get("telefono").toString());
usuario.setExtension(row.get("extension").toString());
usuarios.add(usuario);
}
The DAO:
public List<Map<String, Object>> list() {
return jdbcTemplate.queryForList("Select * from Administradores");
}

ExtGWT StoreFilterField input doesn't react

I'm trying to build grid with build in column filtering (using sencha gxt), here is my code:
public Grid<Stock> createGrid() {
// Columns definition
ColumnConfig<Stock, String> nameCol = new ColumnConfig<Stock, String>(props.name(), 100, "Company");
// Column model definition and creation
List<ColumnConfig<Stock, ?>> cl = new ArrayList<ColumnConfig<Stock, ?>>();
cl.add(nameCol);
ColumnModel<Stock> cm = new ColumnModel<Stock>(cl);
// Data populating
ListStore<Stock> store = new ListStore<Stock>(props.key());
store.addAll(TestData.getStocks());
// Grid creation with data
final Grid<Stock> grid = new Grid<Stock>(store, cm);
grid.getView().setAutoExpandColumn(nameCol);
grid.setBorders(false);
grid.getView().setStripeRows(true);
grid.getView().setColumnLines(true);
// Filters definition
StoreFilterField<Stock> filter = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock item, String filter) {
// Window.alert(String.valueOf("a"));
String name = item.getName();
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter.bind(store);
cm.addHeaderGroup(0, 0, new HeaderGroupConfig(filter, 1, 1));
filter.focus();
return grid;
}
My problem is: after I run this code, I cannot write anything to filter input, I'm using test data and classes (Stock.java and StockProperties.java) from this example: http://sencha.com/examples-dev/#ExamplePlace:filtergrid
I try to put allert in doSelect method to check if this function was called, but it wasn't.
Any idea will be welcome. Thanks.
I was able to make your code work. I observed that there were compiler errors in the code for StoreFilterField class. Here is the code that filters the grid based on the values in the first column, that is, name field in the Stock model.
StoreFilterField<Stock> filter1 = new StoreFilterField<Stock>() {
#Override
protected boolean doSelect(Store<Stock> store, Stock parent, Stock record, String property, String filter) {
String name = record.get("name");
name = name.toLowerCase();
if (name.startsWith(filter.toLowerCase())) {
return true;
}
return false;
}
};
filter1.bind(store);
Btw, I tested this with GXT 2.2.5 and GWT 2.4.
Thanks,
Ganesh
I solve this problem according to this paper http://www.sencha.com/forum/archive/index.php/ … but I replace disableTextSelection(false) with setAllowTextSelection(true);

Categories