How to access java class member in instance with a string - java

I have a small class with some data, called MyData:
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
....
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
}
Then I have a class with arrays of this class for specific type of people called AllMyData:
public class AllMyData {
public ArrayList<MyData> cli = new ArrayList<>();
public ArrayList<MyData> sub = new ArrayList<>();
public ArrayList<MyData> emp = new ArrayList<>();
public ArrayList<MyData> exp = new ArrayList<>();
public ArrayList<MyData> oex = new ArrayList<>();
public ArrayList<MyData> bin = new ArrayList<>();
public ArrayList<MyData> ven = new ArrayList<>();
....
}
in main class I need to add new items to specific array (if id does not exists) where I have a string representative of AllMyData array
public AllMyData elems = new AllMyData();
public void initArray(int id, String name, String tip) {
//this is an example just for "cli" element and "cli" is in String tip
if (!checkForId(elems.cli, id)) {
MyData element = new MyData(name, name, id);
elems.cli.add(element);
}
}
private boolean checkForId(ArrayList<MyData> a, int id) {
for (MyData e : a) {
if (e.id == id) return true;
}
return false;
}
Then I need just a call, for example:
initArray(5, "Test", "emp");
and would like to avoid switch statement and to repeat code for every single type. In this call, "emp" would be element elems.emp
Is there a way to access elems member with a string name instead of creating switch statement?

Create a map of lists in AllMyData instead.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
AllMyData data = new AllMyData();
data.add("foo", new MyData("Hello World", "", 1));
data.add("cli", Arrays.asList(new MyData("BASH", "", 2), new MyData("SHELL", "", 3)));
System.out.println(data);
}
}
AllMyData [map={cli=[MyData [name=BASH, nameonly=, id=2, earn=0.0, paid=0.0], MyData [name=SHELL, nameonly=, id=3, earn=0.0, paid=0.0]], sub=[], oex=[], bin=[], foo=[MyData [name=Hello World, nameonly=, id=1, earn=0.0, paid=0.0]], emp=[], exp=[], ven=[]}]
import java.util.*;
public class AllMyData {
private Map<String, List<MyData>> map;
public AllMyData() {
map = new HashMap<String, List<MyData>>();
map.put("cli", new ArrayList<>());
map.put("sub", new ArrayList<>());
map.put("emp", new ArrayList<>());
map.put("exp", new ArrayList<>());
map.put("oex", new ArrayList<>());
map.put("bin", new ArrayList<>());
map.put("ven", new ArrayList<>());
}
public void add(String key, List<MyData> data) {
List<MyData> list = get(key);
if (list == null) {
map.put(key, data);
} else {
list.addAll(data);
map.put(key, list);
}
}
public void add(String key, MyData data) {
List<MyData> list = get(key);
if (list == null) {
list = new ArrayList<>();
}
list.add(data);
map.put(key, list);
}
public List<MyData> get(String key) {
return map.get(key);
}
#Override
public String toString() {
return String.format("AllMyData [map=%s]", map);
}
}
public class MyData {
public String name = "";
public String nameonly = "";
public int id = 0;
public double earn = 0;
public double paid = 0;
public MyData(String name, String nameonly, int id) {
this.name = name;
this.nameonly = nameonly;
this.id = id;
}
#Override
public String toString() {
return String.format("MyData [name=%s, nameonly=%s, id=%s, earn=%s, paid=%s]", name, nameonly, id, earn, paid);
}
}

Consider the use of a Map from String to ArrayList.
It would look like this:
Map> allMyData = new HashMap<>();

Related

Adding An Object Onto ArrayList Between Two Classes

I'm trying to add order1 object to orderList in the Customer class, but it's not working. The toString() method returns zero items in the ArrayList. Does anyone have any idea of what else I can try doing instead?
public class Customer {
private ArrayList<Order> orderList;
private int numberOfOrders = 0;
public Customer(String name, Order firstElementInList) {
this(name);
this.orderList.add(0, firstElementInList);
}
public void setNumberOfOrders() {
this.numberOfOrders = orderList.size();
}
public String toString() {
return name + numberOfOrders;
}
}
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Order order1 = new Order( "bob", 1.1 );
Customer bob = new Customer( "Bobby Shmurda ", order1 );
System.out.println(bob.toString());
}
}
A String Object gets added to ArrayList and when toString() is invoked should return the length of the ArrayList.
Because your list is yet to be created as you have not created its object.
Use below code to create your list.
private ArrayList<Order> orderList = new ArrayList<>();
public class Customer {
private List<Order> orderList;
private int numberOfOrders = 0;
public Customer(String name, Order firstElementInList) {
this(name);
if(orderList == null) {
orderList = new ArrayList<Order>();
}
this.orderList.add(0, firstElementInList);
}
public void setNumberOfOrders() {
this.numberOfOrders = orderList.size();
}
public String toString() {
return "The length of the orderList: " + orderList != null ? orderList.size() : 0;
}
}
public class Main {
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
Order order1 = new Order( "bob", 1.1 );
Customer bob = new Customer( "Bobby Shmurda ", order1 );
System.out.println(bob.toString());
}
}

How to iterate over json data with gson

My json string is:
{
"recordsTotal":1331,
"data":[
{
"part_number":"3DFN64G08VS8695 MS",
"part_type":"NAND Flash",
"id":1154,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DPM0168-2",
"part_type":"System in a Package (SiP)",
"id":452,
"manufacturers":[
"3D-Plus"
]
},
{
"part_number":"3DSD1G16VS2620 SS",
"part_type":"SDRAM",
"id":269,
"manufacturers":[
"3D-Plus"
]
}
]
}
This code lets me access the two highest level elements:
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
System.out.println("data : " + jsonObject.get("data"));
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
But what I want to do is iterate over all the objects inside "data" and create a list of part_numbers. How do I do that?
JsonArray is an Iterable<JsonElement>. So you can use for in loop.
JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
final JsonArray data = jsonObject.getAsJsonArray("data");
System.out.println("data : " + data);
System.out.println("recordsTotal : " + jsonObject.get("recordsTotal"));
List<String> list = new ArrayList<String>();
for (JsonElement element : data) {
list.add(((JsonObject) element).get("part_number").getAsString());
}
Suppose class Name for Json Model is Example.
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Example {
#SerializedName("recordsTotal")
private Integer recordsTotal;
#SerializedName("data")
private List<Datum> data = null;
public Integer getRecordsTotal() {
return recordsTotal;
}
public void setRecordsTotal(Integer recordsTotal) {
this.recordsTotal = recordsTotal;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
And suppose List of Data class name is Datum :-
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Datum {
#SerializedName("part_number")
private String partNumber;
#SerializedName("part_type")
private String partType;
#SerializedName("id")
private Integer id;
#SerializedName("manufacturers")
private List<String> manufacturers = null;
public String getPartNumber() {
return partNumber;
}
public void setPartNumber(String partNumber) {
this.partNumber = partNumber;
}
public String getPartType() {
return partType;
}
public void setPartType(String partType) {
this.partType = partType;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getManufacturers() {
return manufacturers;
}
public void setManufacturers(List<String> manufacturers) {
this.manufacturers = manufacturers;
}
}
And then through Gson library we can convert json to java Model :
Example example = new Gson().fromJson(jsonString, new TypeToken<Example>() {}.getType());
Now we can get list of data though example model :-
List<Datum> dataList = example.getData();
From dataList you can traverse and get all info.
If partNmber List we need then we can get in this way :-
List<String> partNumberList = new ArrayList<>();
for (Datum data : dataList) {
partNumberList.add(data.getPartNumber());
}
The given code will not guaranteed to 100% equivalent but it will help you to work.
First you have to create the class for your data objects:
class mydata {
public String part_name;
public String part_type;
public int Id;
public String manufacturers;
}
Your main method should look like
public static void main(String[] args) {
JSONObject obj = new JSONObject();
List<mydata> sList = new ArrayList<mydata>();
mydata obj1 = new mydata();
obj1.setValue("val1");
sList.add(obj1);
mydata obj2 = new mydata();
obj2.setValue("val2");
sList.add(obj2);
obj.put("list", sList);
JSONArray jArray = obj.getJSONArray("list");
for(int ii=0; ii < jArray.length(); ii++)
System.out.println(jArray.getJSONObject(ii).getString("value"));
}
For futher exploration you can use that link:
https://gist.github.com/codebutler/2339666

TreeTableView: Displaying different data types

I have a Factory class which contains a list of employees. I want to use a TreeTableView to display the Factory data. It is pretty forward to display the name and the size of a Factory, but i don't know how to display the employees names!
public class Factory {
private String name;
private double size;
private List<Employee> employees;
public Factory(name, size){this.name=name; this.size=size}
// Getters & setters
}
I want to have the following output:
With the possibilty to fold the factory.
In a TreeView or TreeTableView all nodes in the tree have to be of the same type. This makes the kind of design you want (which is very natural) something of a pain. Basically, you have to make the type of the TreeView or TreeTableView the most specific superclass of all the types of rows you want in the tree: i.e. in this case the type of the TreeTableView needs to be a superclass of both Employee and Factory. Then the cell value factories on the columns would have to type test the row objects to determine what value to return.
It would be unusual to have an object model in which these were related by inheritance other than both being subclasses of Object, so you probably need a TreeTableView<Object> here.
So roughly speaking (if you are using plain old JavaBean style, instead of the recommended JavaFX properties), you would define something like
TreeTableView<Object> treeTable = new TreeTableView<>();
treeTable.setShowRoot(false);
TreeTableColumn<Object, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleStringProperty(f.getName());
} else {
return new SimpleStringProperty("");
}
});
TreeTableColumn<Object, Number> sizeColumn = new TreeTableColumn<>("Size");
sizeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleObjectProperty<Number>(Double.valueOf(f.getSize()));
} else {
return new SimpleObjectProperty<Number>(null);
}
});
TreeTableColumn<Object, String> employeeColumn = new TreeTableColumn<>("Employee");
employeeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Employee)) {
Employee emp = (Employee) rowItem.getValue() ;
return new SimpleStringProperty(emp.getName());
} else {
return new SimpleStringProperty("");
}
});
treeTable.getColumns().addAll(nameColumn, sizeColumn, employeeColumn);
and of course you populate it with
// fully initialized list of factories, with employee lists initialized:
List<Factory> factories = ... ;
TreeItem<Object> root = new TreeItem<>(null);
for (Factory factory : factories) {
TreeItem<Object> factoryItem = new TreeItem<>(factory);
root.getChildren().add(factoryItem);
for (Employee emp : factory.getEmployees()) {
TreeItem<Object> employeeItem = new TreeItem<>(emp);
factoryItem.getChildren().add(employeeItem);
}
}
treeTable.setRoot(root);
Here's a simple SSCCE using this:
import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.stage.Stage;
public class TreeTableExample extends Application {
#Override
public void start(Stage primaryStage) {
TreeTableView<Object> treeTable = new TreeTableView<>();
treeTable.setShowRoot(false);
TreeTableColumn<Object, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleStringProperty(f.getName());
} else {
return new SimpleStringProperty("");
}
});
TreeTableColumn<Object, Number> sizeColumn = new TreeTableColumn<>("Size");
sizeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Factory)) {
Factory f = (Factory) rowItem.getValue() ;
return new SimpleObjectProperty<Number>(Double.valueOf(f.getSize()));
} else {
return new SimpleObjectProperty<Number>(null);
}
});
TreeTableColumn<Object, String> employeeColumn = new TreeTableColumn<>("Employee");
employeeColumn.setCellValueFactory(cellData -> {
TreeItem<Object> rowItem = cellData.getValue();
if (rowItem != null && (rowItem.getValue() instanceof Employee)) {
Employee emp = (Employee) rowItem.getValue() ;
return new SimpleStringProperty(emp.getName());
} else {
return new SimpleStringProperty("");
}
});
treeTable.getColumns().addAll(nameColumn, sizeColumn, employeeColumn);
List<Factory> factories = createData();
TreeItem<Object> root = new TreeItem<>(null);
for (Factory factory : factories) {
TreeItem<Object> factoryItem = new TreeItem<>(factory);
root.getChildren().add(factoryItem);
for (Employee emp : factory.getEmployees()) {
TreeItem<Object> employeeItem = new TreeItem<>(emp);
factoryItem.getChildren().add(employeeItem);
}
}
treeTable.setRoot(root);
Scene scene = new Scene(treeTable, 800, 800);
primaryStage.setScene(scene);
primaryStage.show();
}
private List<Factory> createData() {
String[][] empNames = {
{"John", "Jane", "Mary"},
{"Susan", "Mike"},
{"Alex", "Francois", "Joanne"}
};
List<Factory> factories = new ArrayList<>();
for (String[] emps : empNames) {
int count = factories.size()+1 ;
Factory f = new Factory("Factory "+ count, count*10);
for (String empName : emps) {
f.getEmployees().add(new Employee(empName));
}
factories.add(f);
}
return factories ;
}
public static class Employee {
private String name ;
public Employee(String name) {
this.name = name ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Factory {
private String name ;
private double size ;
private List<Employee> employees ;
public Factory(String name, double size) {
this.name = name ;
this.size = size ;
this.employees = new ArrayList<>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSize() {
return size;
}
public void setSize(double size) {
this.size = size;
}
public List<Employee> getEmployees() {
return employees;
}
}
public static void main(String[] args) {
launch(args);
}
}
Another approach, which I think is a bit artificial, is to create a class representing the row in the table view, and then to make Factory and Employee subclasses of it:
public abstract class EmploymentEntity {
public String getName() {
return null ;
}
public Double getSize() {
return null ;
}
public String getEmployeeName {
return null ;
}
}
then
public class Employee extends EmploymentEntity {
private String name ;
public Employee(String name) {
this.name = name ;
}
#Override
public String getEmployeeName() {
return name ;
}
public void setEmployeeName(String name) {
this.name = name ;
}
}
and
public class Factory extends EmploymentEntity {
private String name ;
private double size ;
private List<Employee> employees ;
public Factory(String name, double size) {
this.name = name ;
this.size = size ;
this.employees = new ArrayList<>();
}
#Override
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
#Override
public Double getSize() {
return size ;
}
public void setSize(double size) {
this.size = size ;
}
public List<Employee> getEmployees() {
return employees ;
}
}
This object model is really unnatural (to me, anyway), but it does make the table a little easier:
TreeTableView<EmploymentEntity> treeTable = new TreeTableView<>();
TreeTableColumn<EmploymentEntity, String> nameColumn = new TreeTableColumn<>("Name");
nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValue().getName()));
TreeTableColumn<EmploymentEntity, Number> sizeColumn = new TreeTableColumn<>("Size");
sizeColumn.setCellValueFactory(cellData -> new SimpleObjectProperty<Number>(cellData.getValue().getValue().getSize()));
TreeTableColumn<EmploymentEntity, String> employeeColumn = new TreeTableColumn<>("Employee");
employeeColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValue().getEmployeeName()));
// etc...

How to populate a ChoiceBox with items from a database

I'm trying to populate a ChoiceBox with items(Countries) from a H2 database via Hibernate, but the ChoiceBox only gets populated with some strange items that don't make sense, instead of the actual countries names; something like this:
project.Forms.AddNew.DB.ItemsPOJO#5aa434
How can I get the actual countries names from the database instead of values like the above?
The classes look as follows:
The POJO class:
#Entity(name = "InitialDBItems")
public class InitialDBItemsPOJO implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int countriesListID;
private String countriesList;
public String getCountriesList() {
return countriesList;
}
public void setCountriesList(String countriesList) {
this.countriesList = countriesList;
}
public int getCountriesListID() {
return countriesListID;
}
public void setCountriesListID(int countriesListID) {
this.countriesListID = countriesListID;
}
}
The countries array that gets persisted into the database:
public class InitialDBItems {
static InitialDBItemsPOJO initialDBItemsPOJO = new InitialDBItemsPOJO();
public static void persistCountries() {
String[] countriesList = {
"Afghanistan",
"Albania",
"Algeria",
// More countries
};
for (String c : countriesList) {
initialDBItemsPOJO.setCountriesList(c);
new ManageItems().addItems(initialDBItemsPOJO);
System.out.println(c);
}
}
How I get the countries from the database:
public static ObservableList<InitialDBItemsPOJO> retrieveCountriesList() {
ObservableList<InitialDBItemsPOJO> data;
List countriesListListItems;
String countriesListListItemsQuery = "from InitialDBItems";
data = FXCollections.observableArrayList();
countriesListListItems = new ManageItems().listItems(countriesListListItemsQuery);
for (Iterator iterator = countriesListListItems.iterator(); iterator.hasNext();) {
InitialDBItemsPOJO countriesListListItemsIt = (InitialDBItemsPOJO) iterator.next();
data.add(countriesListListItemsIt);
}
return data;
}
}
Hope you can help. Thank you all in advance.
project.Forms.AddNew.DB.ItemsPOJO#5aa434 is the value of the default toString(); of your entity InitialDBItemsPOJO an easy work around is to override it
#Entity(name = "InitialDBItems")
public class InitialDBItemsPOJO implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int countriesListID;
private String countriesList;
public String getCountriesList() {
return countriesList;
}
public void setCountriesList(String countriesList) {
this.countriesList = countriesList;
}
public int getCountriesListID() {
return countriesListID;
}
public void setCountriesListID(int countriesListID) {
this.countriesListID = countriesListID;
}
public String toString(){
return countriesList;
}
}
or
public static ObservableList retrieveCountriesList() {
ObservableList<InitialDBItemsPOJO> data;
List countriesListListItems;
String countriesListListItemsQuery = "from InitialDBItems";
data = FXCollections.observableArrayList();
countriesListListItems = new ManageItems().listItems(countriesListListItemsQuery);
for (Iterator iterator = countriesListListItems.iterator(); iterator.hasNext();) {
InitialDBItemsPOJO countriesListListItemsIt = (InitialDBItemsPOJO) iterator.next();
data.add(countriesListListItemsIt.getCountriesList());
}
return data;
}

How to get data from another EntityProxy in GXT ColumnConfig?

Here is the thing: I have an application to manage user's tickets.
I have 2 basic classes : Ticket and User.
Using GXT I have some ColumnConfig class like this:
ColumnConfig<TicketProxy, String> dateColumn = new ColumnConfig<TicketProxy, String>(
new ValueProvider<TicketProxy, String>() {
public String getValue(TicketProxy object) {
Date initialDate = object.getInitialDate();
String date = "";
if (initialDate != null) {
date = dtFormat.format(initialDate);
}
return date;
}
public void setValue(TicketProxy object, String initialDate) {
if (object instanceof TicketProxy) {
object.setInitialDate(dtFormat.parse(initialDate));
}
}
public String getPath() {
return "initialDate";
}
}, 70, "Date");
columnsChamado.add(dateColumn);
but I want to get some data from UserProxy class, some like this:
ColumnConfig<UserProxy, String> userRoomColumn = new ColumnConfig<UserProxy, String>(
new ValueProvider<UserProxy, String>() {
public String getValue(UserProxy object) {
String userRoom = object.getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(UserProxy object, String userRoom) {
if (object instanceof UserProxy) {
object.setUserRoom(userRoom);
}
}
public String getPath() {
return "userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
But GWT doesn't allow me to change the "Proxy" parameter to another class in the same ColumnConfig.
How can I get data from other Proxy class in this ColumnConfig?
I use GXT 3.0 (Sencha) + Hibernate.
Proxy classes:
BaseEntityProxy:
package com.acme.ccc.shared;
import com.acme.ccc.server.locator.CCCLocator;
import com.acme.db.base.DatabaseObject;
import com.google.web.bindery.requestfactory.shared.EntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
import com.google.web.bindery.requestfactory.shared.SkipInterfaceValidation;
#SkipInterfaceValidation
#ProxyFor(value = DatabaseObject.class, locator = CCCLocator.class)
public interface BaseEntityProxy extends EntityProxy {
Long getId();
Long getVersion();
void setId(Long id);
void setVersion(Long version);
}
TicketProxy:
package com.acme.ccc.shared.entityproxy;
import java.util.Date;
import java.util.List;
import com.acme.ccc.db.Ticket;
import com.acme.ccc.server.locator.CCCLocator;
import com.acme.ccc.shared.BaseEntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
#ProxyFor(value = Ticket.class, locator = CCCLocator.class)
public interface TicketProxy extends BaseEntityProxy {
Date getPrazo();
void setPrazo(Date prazo);
TicketTipoProxy getTicketTipo();
void setTicketTipo(TicketTipoProxy chamadoTipo);
CanalOrigemProxy getCanalOrigem();
void setCanalOrigem(CanalOrigemProxy canalOrigem);
UserProxy getUser();
void setUser(UserProxy user);
CategoriaProxy getPedidoTipo();
void setPedidoTipo(CategoriaProxy pedidoTipo);
Date getInitialDate();
void setInitialDate(Date dt);
Long getTotal();
void setTotal(Long total);
}
UserProxy:
package com.acme.ccc.shared.entityproxy;
import java.util.List;
import com.acme.ccc.db.User;
import com.acme.ccc.server.locator.CCCLocator;
import com.acme.ccc.shared.BaseEntityProxy;
import com.google.web.bindery.requestfactory.shared.ProxyFor;
#ProxyFor(value = User.class, locator = CCCLocator.class)
public interface UserProxy extends BaseEntityProxy {
String getName();
String getUserRoom();
Long getTotal();
void setName(String name);
void setUserRoom(Sting room)
void setTotal(Long total);
}
An gxt grid is able to show the data only of one data type. If you put a single TicketProxy row, how do you expect to access a user object?
If you want to display both Tickets and Users independently (so a row is either a Ticket OR a User), you have to use BaseEntityProxy in your Grid: Grid<BaseEntityProxy>. Then you can define your columns as ColumnConfig<BaseEntityProxy, ?> and check the type within your getters and setter:
List<ColumnConfig<BaseEntityProxy, ?>> columnsChamado = new ArrayList<ColumnConfig<BaseEntityProxy, ?>>();
ColumnConfig<BaseEntityProxy, String> dateColumn = new ColumnConfig<BaseEntityProxy, String>(
new ValueProvider<BaseEntityProxy, String>() {
private final DateTimeFormat dtFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL);
public String getValue(BaseEntityProxy object) {
Date initialDate = ((TicketProxy) object).getInitialDate();
String date = "";
if (initialDate != null) {
date = dtFormat.format(initialDate);
}
return date;
}
public void setValue(BaseEntityProxy object, String initialDate) {
if (object instanceof TicketProxy) {
((TicketProxy) object).setInitialDate(dtFormat.parse(initialDate));
}
}
public String getPath() {
return "initialDate";
}
}, 70, "Date");
columnsChamado.add(dateColumn);
ColumnConfig<BaseEntityProxy, String> userRoomColumn = new ColumnConfig<BaseEntityProxy, String>(
new ValueProvider<BaseEntityProxy, String>() {
public String getValue(BaseEntityProxy object) {
String userRoom = ((UserProxy)object).getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(BaseEntityProxy object, String userRoom) {
if (object instanceof UserProxy) {
((UserProxy)object).setUserRoom(userRoom);
}
}
public String getPath() {
return "userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
ColumnModel<BaseEntityProxy> cm = new ColumnModel<BaseEntityProxy>(columnsChamado);
If, on the other hand, you want one grid row to display a User AND a Ticket, you have to use a wrapper class:
class TicketWithUserProxy extends BaseEntityProxy{
private UserProxy userProxy;
private TicketProxy ticketProxy;
public UserProxy getUserProxy() {
return userProxy;
}
public void setUserProxy(UserProxy userProxy) {
this.userProxy = userProxy;
}
public TicketProxy getTicketProxy() {
return ticketProxy;
}
public void setTicketProxy(TicketProxy ticketProxy) {
this.ticketProxy = ticketProxy;
}
}
and setup your grid (Grid<TicketWithUserProxy>) accordingly:
List<ColumnConfig<TicketWithUserProxy, ?>> columnsChamado = new ArrayList<ColumnConfig<TicketWithUserProxy, ?>>();
ColumnConfig<TicketWithUserProxy, String> dateColumn = new ColumnConfig<TicketWithUserProxy, String>(
new ValueProvider<TicketWithUserProxy, String>() {
private final DateTimeFormat dtFormat = DateTimeFormat.getFormat(DateTimeFormat.PredefinedFormat.DATE_FULL);
public String getValue(TicketWithUserProxy object) {
Date initialDate = object.getTicketProxy().getInitialDate();
String date = "";
if (initialDate != null) {
date = dtFormat.format(initialDate);
}
return date;
}
public void setValue(TicketWithUserProxy object, String initialDate) {
object.getTicketProxy().setInitialDate(dtFormat.parse(initialDate));
}
public String getPath() {
return "initialDate";
}
}, 70, "Date");
columnsChamado.add(dateColumn);
ColumnConfig<TicketWithUserProxy, String> userRoomColumn = new ColumnConfig<TicketWithUserProxy, String>(
new ValueProvider<TicketWithUserProxy, String>() {
public String getValue(TicketWithUserProxy object) {
String userRoom = object.getUserProxy().getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(TicketWithUserProxy object, String userRoom) {
object.getUserProxy().setUserRoom(userRoom);
}
public String getPath() {
return "userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);
ColumnModel<TicketWithUserProxy> cm = new ColumnModel<TicketWithUserProxy>(columnsChamado);
If you have a Column of TicketProxy, you can get the UserProxy from the TicketProxy ?
ColumnConfig<TicketProxy, String> userRoomColumn = new ColumnConfig<TicketProxy, String>(
new ValueProvider<TicketProxy, String>() {
public String getValue(TicketProxy object) {
String userRoom = object.getUser().getUserRoom();
String room = "";
if (userRoom != null) {
room = userRoom;
}
return room;
}
public void setValue(TicketProxy object, String userRoom) {
object.getUser().setUserRoom(userRoom);
}
public String getPath() {
return "user.userRoom";
}
}, 70, "User's Room");
columnsChamado.add(userRoomColumn);

Categories