Adding a database ID to an Eclipse Combo - java

I'm working on a Java application in Eclipse that pulls data out of a MySQL database. I'm populating a combo box with data. So far I can get the value of a field to show up but I can't figure out how to store the database row's unique ID value. One suggestion I found was to create a custom class that could store both the display value and the id value. However, this doesn't appear to work with the Eclipse widget combo object. This is what I have
import org.eclipse.swt.widgets.Combo;
class myClass {
public static void createCombo(ResultSet rs) {
Combo c = new Combo();
while(rs.next()) {
int id = rs.getInt("id");
int display = rs.getString("display");
comboitem ci = new comboitem(id,display);
c.add(ci);
}
}
}
class comboitem {
private int _id;
private String _display;
public comboitem(int id, String display) {
this._id = id;
this._display = display;
}
public int getID(){
return _id;
}
public String toString(){
return _display;
}
}
The above errors at c.add(ci). It's expecting a string, not an object. Is there a way to do this?

No idea but, I've always felt it was a bad move anyway.
Create a collection/list of comboitems, populate the widget from comboitem.display.
Index in the combo is index in your collection.
Means you can unit test lots of things without a UI or with simple mock, and it keeps you away from desktop specific implementations in your data models.

The combo widget displays an array of String's, so simply concatenate the two values if you want to display them both. I am not sure what your end goal is from your question. If it is to select the appropriate comboitem based on the combo selection, then store the comboitems in a Map and use the combo values as the keys.
Another approach is to use a jface ComboViewer which allows you to set the input to a complex object, provide a label provider and more complex controls around the Combo widget.
You should also look up some information on java coding conventions and not access your database directly from the UI unless this is a very simple application.
You can find some examples on using most SWT widgets here.

Related

Want to convert java struts 2 static code into dynamic

I have been assign to one struts2 project and its one of jsp contains more than 100 radio buttons and they have handled in statically not dynamically. As jsp contains 100 radio buttons so I am able to see the below list of radio buttons catches in actions with their getter and setter
List selectRadioList001
List selectRadioList002
List selectRadioList003
List selectRadioList004
etc
List selectRadioList100
I want to add these radio button in a list dynamically iterating through 1 to 100 something like below but when I try to access the variable like "searchBoxSelectRadioList"+i then it is pretending like a simple string. I want it to be like a List as shown above.
public class SelectRadioListPOJO {
private List<TicketDesignUtil> selectRadioList;
public List<TicketDesignUtil> getSelectRadioList() {
return selectRadioList;
}
public void setSelectRadioList(List<TicketDesignUtil> selectRadioList) {
this.selectRadioList = selectRadioList;
}
}
Action code:
List<SelectRadioListPOJO> selectRadioListPOJOList = new ArrayList<>();
SelectRadioListPOJO selectRadioListPOJO;
for (int i = 1; i <= 100; i++) {
selectRadioListPOJO = new SelectRadioListPOJO();
selectRadioListPOJO.setSelectRadioList("searchBoxSelectRadioList"+i);// ERROR
selectRadioListPOJOList.add(selectRadioListPOJO);
}
It's not clear what you're asking.
You can't pass arbitrary values to methods; setSelectRadioList takes a list of TicketDesignUtil.
If your action doesn't have getters and setters for all of those radio buttons then you should resort to accessing the request parameters directly, for example, via ParameterAware.
You would then access the radio button parameters by name from the injected parameter map.
Notes:
It's not "pretending" to be a simple string, it is a simple string, because... well, because it is.
Your for loop is wrong; I corrected it in your question to avoid others commenting on it. The POJO should be added to the POJOList inside the loop.
Naming is funky; just call it selectRadioListPojos. Better yet, name it something domain-specific: variables should be semantically meaningful, not just a description of the class(es) involved.
These shouldn't be static in the first place, but a map or array.

Table storage for strings and booleans

I've implemented in-app-billing v3 and I'd like a way to keep some sort of table which contains 3 columns
(String) Name of product, (String) sku, (boolean) true/false
What is the best way to do this? The best way would (in my opinion) allow me to keep a static easily readable list of values where the first two were strings, the third a boolean. At the start all the values for the boolean column were false, but as I query purchases I am able to easily reset the value.
Just to add,
I'm against SQLite databases for the reason that they're just too easy to hack. I'd rather create it in code and thus I'm debating between an ArrayList within an arraylist or matrices or something like the following:
private static class CatalogEntry {
public String sku;
public String name;
public CatalogEntry(String sku, String name) {
this.sku = sku;
this.name = name;
}
}
private static final CatalogEntry[] CATALOG = new CatalogEntry[] {
new CatalogEntry("android.test.purchased", "Item1"),
new CatalogEntry("android.test.canceled", "Item2"),
new CatalogEntry("android.test.refunded", "Item3"),
new CatalogEntry("android.test.item_unavailable", "Item4")
};
Is there a way to reset values in the CATALOG array if I add a third column, otherwise I'm considering using both that and standard arraylists.
Use sqlite with FOUR columns:
sku
name
purchaseDate (or null if not purchased)
md5Hash
When a purchase is made, you just concatenate the sku, name, purchaseDate, device-id, and a PSK, make an md5Hash and store it along with the other data in the row. When you check the contents of the table, you compare the md5 stored against the data, and you can verify whether the purchase was valid, or the table has been tampered with. You can even let the user back up the purchase table to sdcard (or use Android backup).

Find items by property in JLIST

I have a JList peopleList populated with a objects of Person class
class Person
{
private String name;
private String age;
private void setName(String value)
{
name = value;
}
private String getName()
{
return name;
}
}
Current to find a person with name I do
public boolean personByNameExists(String name)
{
for(int index = 0 ; index < peopleList .getModel().getSize() ; index ++)
{
Person pl = (Person) peopleList .getModel().getElementAt(index);
if( p1.getName().equals(name))
{
return true;
}
}
}
I am wondering if there is way to do the same operation with out going through the whole list. I am from .Net back ground and in C# I would use LINQ is there something similar in Java?
It depends a bit on the use-case. If you just want to find an entry on the model side, you can keep looping over your ListModel, or loop over the data structure behind the ListModel which can be a regular List implementation, and then you can use the methods suggested by haylem.
If you want to search on your JList, and present the search result visually to the user (for example highlight them and scroll to the relevant entry) I would highly recommend taking a look at the SwingX project which supports this out-of-the-box
You're looking for a typical filter functionality.
I'd recommend you look at Google Guava's:
Collections2.filter(Collection, Predicate),
Iterables.filter(Iterable, Class),
or Iterables.filter(Iterable, Predicate)
You can find more info here or even look at this SO question (your question is a duplicate):
filter and sort list using google collections
Update: As kleopatra made me realize, you might be using a normal ListModel.
You could specifiy a custom model when creating your JList, that either:
implements a Collection or Iterable interface,
or provides a method to return a view of the data filtered by the property you want.

Need to know if each field has changed, how should I model this in Hibernate

So I have a class with three fields that maps to a table using hibernate
Class Widget
{
String field1;
String field2;
String field3;
}
On application startup a number of instances these widgets will be added to the database from an external files, but when I exit the application I need to know which (if any) of these fields have been changed by the user since the application was started, so the changes can be saved back to the files. I also need to store the original value for logging purposes.
I can't work whether I need a status field in the table or whether there is already a way of doing this using Hibernate/Database.
EDIT:A good solution to the program was given below . however the main reason I am using Hibernate is to reduce memory consumption so storing the original values when changed is not a good solution for me , I want everthing stored in the database. So I have create this new question How do I store a copy of each entity I add to database in Hibernate
Given an entity like the following you can track changes on one of it's field (while preserving its original value too).
#Entity
#Table(schema = "test", name = "test")
public final class Test {
private static final int ORIGINAL = 0;
private static final int CURRENT = 1;
private Integer id;
// holds the original and current state of the field
private final AtomicReferenceArray<String> field = new AtomicReferenceArray<>(2);
#Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Transient
public String getOriginalField() {
return field.get(ORIGINAL);
}
#Basic
public String getField() {
return field.get(CURRENT);
}
public void setField(String field) {
this.field.compareAndSet(ORIGINAL, null, field);
this.field.set(CURRENT, field);
}
#PreUpdate
public void preUpdate() {
System.out.format("Original: %s, New: %s\n", getOriginalField(), getField());
}
...
}
If there is a single row in a database like this:
id: 1
field: a
version: 2011-12-02 11:24:00
before the field gets updated (say, from a to b) you'll get the following output.
Original: d, New: b
The original value gets preserved even if the the entity is updated multiple times and both state can be accessed through the corresponding getters (getField and getOriginalField—you can get more creative than me in the naming :).
This way, you can spare yourself from creating version columns in your database and also can hide the implementation details from clients.
Instead of an AtomicReferenceArray you could use arrays, lists, etc, to track all changes like this way.
The #PreUpdate isn't necessary of course, but this way you can be notified of changes in the entity's state and atomically save the updated fields into file. There more annotations like these: see the documentation for javax.persistence for other annotation types.
If you are using MySql then you can get table's last update time from information_schema database like
SELECT UPDATE_TIME FROM `information_schema`.`tables`
WHERE TABLE_SCHEMA = 'dbName' AND TABLE_NAME = 'tableName'
Or else simple solution will be to add a column for update time stamp. By this you can even monitor which particular row has been updated.
If you need to synchronize with files as soon as you save into database, You can use the Hibernate event mechanism to intercept any save to database and save it to file, here's a sample doing that.

Most efficient way to manage a master table in a Java based parser

I'm working on a Swing based project that will display large amounts of data using a Table component. I'm trying to decide what are the best alternatives in terms of efficiency and management of the parsed data. The master table can be manipulated (i.e. views of the complete data can be created, or removed),so the complete data needs to be hold in memory
I know these kind of problems can have many different solutions. I thought of creating a class representing one entry on the log, with properties representing each 'property' on it. I can possible use Comparator objects to sort based on these fields, and use these objects to build a table component.
This might not be a good idea if the total number of entries is in the order of 5000-10000 lines
Any suggestion on good practices to manage this kind of data and perform manipulations to it to render a graphic component are received.
Not many details have been provided, so I'm basically looking for general ideas on how to approach the problem.
I'm presuming that the files are all parsed and an in memory representation of parsed data
is available when the table is displayed. You need to have your own tablemodel which gets data from the parsed files.
Something like below can be your table model:
class MyTableModel extends AbstractTableModel {
private final List<String> columnNames;
private List<RowData> rows;
MyTableModel() {
columnNames = new ArrayList<String>();
columnNames.add("Name");
//...
rows = new ArrayList<RowData>();
}
// populate the table data model with a List
// that contains parsed data, each list element
// could correspond to a record or line (say)
void setCoreData(final List<RowData> data) {
this.rows = data;
}
public Object getValueAt(final int pRow, final int pCol) {
if (getColumnName(pCol).equals("Name")) {
return rows.get(pRow).getName();
}
//... .
}
// corresponds to the rows of table instances of which
// are created by output of parsing
private class RowData {
private String name;
public Object getName() {
return name;
}
}
// table instantitaion can be as below (say)
JTable myTable = new JTable(new MyTableModel());

Categories

Resources