I got a tableview with a tablecolumn ("ID").
How can i link the ID to show the value?
For example: ID 90 has to be "Shop" and ID 91 has to be "Wallmart"..
I'm using 2 tables:
Person(id, personName, personShopID)
Items(id, shopName)
PersonShopID links to ITEMS id and i have to show the shopName instead of the ID..
Note: I'm using JavaFX and i'm getting data from mysql database and i'm using tcShopName.setCellValueFactory(new PropertyValueFactory<>("personShopID"));
kind regards !
package databag;
import java.sql.Timestamp;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import vivesgoal.controller.CustomDate;
/**
*
* #author Lowie Menu
*/
public class PersoonBag {
private int id;
private String naam;
private String voornaam;
private Date geboortedatum;
private String opmerking;
private boolean isTrainer;
private int ploeg_id;
public PersoonBag(int id, String naam, String voornaam, Date geboortedatum, String opmerking,boolean isTrainer, int ploeg_id){
this.id=id;
this.naam=naam;
this.voornaam=voornaam;
this.geboortedatum=geboortedatum;
this.opmerking=opmerking;
this.isTrainer=isTrainer;
this.ploeg_id=ploeg_id;
}
public PersoonBag()
{
}
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public String getVoornaam() {
return voornaam;
}
public Date getGeboortedatum() {
return geboortedatum;
}
public String getGeboortedatumAlter(){
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
String datum = df.format(geboortedatum);
return datum;
}
public CustomDate getMyDate(){
return new CustomDate(geboortedatum.getTime());
}
public java.util.Date getGeboortedatumUtil(){
return geboortedatum;
}
public String getOpmerking() {
return opmerking;
}
public boolean isIsTrainer() {
return isTrainer;
}
public int getPloeg_id() {
return ploeg_id;
}
public void setId(int id) {
this.id = id;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setVoornaam(String voornaam) {
this.voornaam = voornaam;
}
public void setGeboortedatum(Date geboortedatum) {
this.geboortedatum =geboortedatum;
}
public void setOpmerking(String opmerking) {
this.opmerking = opmerking;
}
public void setIsTrainer(boolean isTrainer) {
this.isTrainer = isTrainer;
}
public void setPloeg_id(int ploeg_id) {
this.ploeg_id = ploeg_id;
}
}
and class Team (dutch ploeg)
package databag;
/**
*
* #author Lowie Menu
*/
public class PloegBag {
private int id;
private String naam;
private String niveau;
private int trainer_id;
public PloegBag(int id, String naam, String niveau, int trainer_id){
this.id = id;
this.naam = naam;
this.niveau = niveau;
this.trainer_id = trainer_id;
}
public PloegBag(){
}
public void setId(int id) {
this.id = id;
}
public void setNaam(String naam) {
this.naam = naam;
}
public void setNiveau(String niveau) {
this.niveau = niveau;
}
public void setTrainer_id(int trainer_id){
this.trainer_id=trainer_id;
}
public int getId() {
return id;
}
public String getNaam() {
return naam;
}
public String getNiveau() {
return niveau;
}
public int getTrainer_id(){
return trainer_id;
}
}
Note: i'm trying to link ploeg_id from PersoonBag to the name of PloegBag(ploegnaam).
This sql code gets me the name of the club matching the id
select * from persoon AS p INNER JOIN ploeg AS ploeg ON p.ploeg_id =ploeg.id where ploeg.naam=?"
Update: no value in ploeg.naam? maybe issue here
p
ublic ArrayList<PersoonBag> zoekAlleSpelers() throws DBException, ApplicationException {
ArrayList<PersoonBag> pb = new ArrayList<>();
try (Connection conn = ConnectionManager.getConnection();) {
try(PreparedStatement stmt = conn.prepareStatement(
"select * from persoon inner join ploeg where persoon.ploeg_id = ploeg.id");) {
// execute voert elke sql-statement uit, executeQuery enkel de eenvoudige
stmt.execute();
// result opvragen (en automatisch sluiten)
try (ResultSet rs = stmt.getResultSet()) {
// van alle rekennigen uit de database,
// RekeningBag-objecten maken en in een RekeningVector steken
while (rs.next()) {
PersoonBag p = new PersoonBag();
PloegBag ploeg = new PloegBag();
// ploeg.setId(rs.getInt("id"));
ploeg.setNaam(rs.getString("naam"));
p.setId(rs.getInt("id"));
p.setNaam(rs.getString("naam"));
p.setVoornaam(rs.getString("voornaam"));
p.setGeboortedatum(rs.getDate("geboortedatum"));
p.setOpmerking(rs.getString("opmerking"));
p.setIsTrainer(rs.getBoolean("isTrainer"));
p.setPloeg_id(ploeg);
pb.add(p);
}
return pb;
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - resultset");
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - statement");
}
} catch (SQLException sqlEx) {
throw new DBException(
"SQL-exception in zoekAlleRekeningen - connection");
}
}
Still have'nt found the issue.. this is function to store the data from the sql query in the table note: this works only ploegname isn't showing
PersoonDB pdb = new PersoonDB();
ArrayList<PersoonBag> persoonbag = new ArrayList<>();
try {
ArrayList<PersoonBag> spelersLijst = pdb.zoekAlleSpelers();
for (PersoonBag r : spelersLijst) {
PersoonBag speler = new PersoonBag(r.getId(),r.getNaam(), r.getVoornaam(),r.getMyDate(),r.getOpmerking(), r.isIsTrainer(),r.getPloeg_id());
persoonbag.add(speler);
}
ObservableList<PersoonBag> spelers = FXCollections.observableArrayList(persoonbag);
taSpelers.setItems(spelers);
Cell items:
#FXML
private TableView<PersoonBag> taSpelers;
#FXML
private TableColumn tcFamilienaam;
#FXML
private TableColumn tcVoornaam;
#FXML
private TableColumn tcOpmerking;
#FXML
private TableColumn<PersoonBag, CustomDate> tcGeboortedatum;
#FXML
private TableColumn<PersoonBag, PloegBag> tcPloeg;
#Override
public void initialize(URL url, ResourceBundle rb) {
tcFamilienaam.setCellValueFactory(new PropertyValueFactory<>("naam"));
tcVoornaam.setCellValueFactory(new PropertyValueFactory<>("voornaam"));
tcGeboortedatum.setCellValueFactory(new PropertyValueFactory<PersoonBag, CustomDate>("geboortedatum"));
tcOpmerking.setCellValueFactory(new PropertyValueFactory<>("opmerking"));
tcPloeg.setCellValueFactory(new PropertyValueFactory<>("ploeg"));
tcPloeg.setCellFactory(tc -> new TableCell<PersoonBag, PloegBag>() {
#Override
public void updateItem(PloegBag ploeg, boolean empty) {
if (empty || ploeg ==null){
setText("");
} else{
setText(ploeg.getNaam());
}
}
});
UPDATE!!! i'm almost there! It's getting the 'naam' data from persoon instead of 'naam' from ploeg!
issue:
while (rs.next()) {
PloegBag ploeg = new PloegBag();
ploeg.setId(rs.getInt("id"));
ploeg.setNaam(rs.getString("naam"));
PersoonBag p = new PersoonBag();
p.setId(rs.getInt("id"));
p.setNaam(rs.getString("naam"));
p.setVoornaam(rs.getString("voornaam"));
p.setGeboortedatum(rs.getDate("geboortedatum"));
p.setOpmerking(rs.getString("opmerking"));
p.setIsTrainer(rs.getBoolean("isTrainer"));
p.setPloeg(ploeg);
pb.add(p);
}
when i'm putting niveau instead of 'naam' it's get me the correct matching result! now i need the name..!
Instead of storing the id of the linked item, store a reference to the item itself. So your PersoonBag class will look like:
public class PersoonBag {
private int id;
private String naam;
private String voornaam;
private Date geboortedatum;
private String opmerking;
private boolean isTrainer;
private PloegBag ploeg;
public PersoonBag(int id, String naam, String voornaam, Date geboortedatum, String opmerking,boolean isTrainer, PloegBag ploeg){
this.id=id;
this.naam=naam;
this.voornaam=voornaam;
this.geboortedatum=geboortedatum;
this.opmerking=opmerking;
this.isTrainer=isTrainer;
this.ploeg=ploeg;
}
public PersoonBag()
{
}
public PloegBag getPloeg() {
return ploeg ;
}
public void setPloeg(PloegBag ploeg) {
this.ploeg = ploeg ;
}
// other get/set methods ...
}
Now you can load everything at once using an inner join in the SQL:
String sql = "select * from persoon inner join ploeg where persoon.ploeg_id = ploeg.id";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
List<Persoon> persoonList = new ArrayList<>();
while (rs.next()) {
PloegBag ploeg = new PloegBag();
// populate ploeg with data from rs...
PersoonBag persoon = new PersoonBag();
persoon.setPloeg(ploeg);
// populate persoon with remaining data from rs...
persoonList.add(persoon);
}
(Obviously you can modify the SQL code, e.g. to retrieve specific items from the database, or just generally to improve it, etc.)
Now your JavaFX code looks like:
TableView<PersoonBag> persoonTable = new TableView<>();
TableColumn<PersoonBag, PloegBag> tcPloeg = new TableColumn<>("Ploeg");
tcPloeg.setCellValueFactory(new PropertyValueFactory<>("ploeg"));
// other columns...
To get the cells to display the value you need from the PloegBag, there are two ways. The "quick and dirty" way is just to define a toString() method in the PloegBag class:
public class PloegBag {
// ...
#Override
public String toString() {
return naam ;
}
}
This isn't very satisfactory, though, as you might want to toString() method to do something else for other reasons in your application. The "proper" way is to use a cell factory:
tcPloeg.setCellFactory(tc -> new TableCell<PersoonBag, PloegBag>() {
#Override
public void updateItem(PloegBag ploeg, boolean empty) {
if (empty || ploeg == null) {
setText(null);
} else {
setText(ploeg.getNaam());
}
}
});
1) establish a Connection to your database from your Java-program by using JDBC:
private static Connection getDBConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase?autoReconnect=true&user=myUser&password=myPass");
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error on getDBCOnnection "+e.toString());
}
return connection;
}
2) Query your Items table in a query like this:
SELECT shopName FROM Items WHERE ID = 90
Java:
public static ResultSet runQuery(String query) {
if(conn == null){
conn = getDBConnection();
}
Statement stmt;
ResultSet rs;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
return rs;
} catch (SQLException e) {
System.out.println(e + " " + e.getMessage());
return null;
}
}
3) Read the result
ResultSet rs = runQuery(query);
String result = rs.getString(1);
Hibernate could do it all for you, including queries... just saying... Although steep learning curve if doing it for the first time... You need to model your container object to have these fields, for example person would have:
class Person{
long id;
String name;
String shopName;
...
}
Then in your data service (provider of data) you would query for that, lets say:
SELECT p.id, p.name, s.name
FROM person p, shop s
WHERE p.shopId = s.shopId;
and provide simple rowmapper
#Ovrride
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
Person person = new Person(rs.getInt("personId"), rs.getString("personName"), rs.getString("shopName"));
return person;
}
You end up with list of Persons, which you can operate on within app. As someone mentioned earlier, you would want to do this, beforehand. Every time you need that list you would hit a local cache, instead of going back to DB. You could set a policy to refresh cache if needed.
Related
I want to pass the postgresql column names as dynamically on the execute query in java.I have created table and table name is product which has 4 columns(year, product,no,age).I have established the db connection and trying to pass the columns dynamically. I have created one pogo class which is having getter and setter of columns names.How can I pass the columns name dynamically on execute query.
dbcon.java
import java.sql.*;
import java.sql.Connection;
public class dbcon {
public static void main(String[] args) {
Connection conn =null;
Statement stmt = null;
DatabaseStatus databaseStatus = new DatabaseStatus();
try
{
Class.forName("******");
conn = DriverManager.getConnection("************", "*******", "*******");
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("Select "+databaseStatus.getYear()+","+databaseStatus.getProduct()+","+databaseStatus.getNo()+","+databaseStatus.getAge()+" FROM \"Products\";");
while(rs.next()){
System.out.println(rs.getString("Year").trim());
System.out.println(rs.getString("Product").trim());
System.out.println(rs.getString("No.").trim());
System.out.println(rs.getString("Age").trim());
}
}
catch (Exception e) {
e.printStackTrace();
}finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
datastatus.java
public class DatabaseStatus {
private String No;
private String Year;
private String Product;
private String Age;
public String getNo() {
return No;
}
public void setNo(String no) {
No = no;
}
public String getYear() {
return Year;
}
public void setYear(String year) {
Year = year;
}
public String getProduct() {
return Product;
}
public void setProduct(String product) {
Product = product;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
Age = age;
}
}
table
SELECT "Year", "Product", "No.", "Age"
FROM "Products";
If you really want use the setters.
databaseStatus.setNo("No.");
databaseStatus.setYear( "Year");
databaseStatus.setProduct("Product");
databaseStatus.setAge("Age");
else remove the setters and
public class DatabaseStatus {
private String No = "No.";
private String Year = "Year";
private String Product = "Product";
private String Age = "Age";
public String getNo() {…
}
I have a method getalldetails (query) which will get details from the database. I want to call this method in multiple classes and based on query. It should fetch the data from the database. Query will be passed dynamically. I am trying to do in following way. Please correct me and advise me hwo to use only one method for data retrieval in whole project.
I am facing these issues:
Return type of result set and calling of method and re use of result. Please guide me and help me
For eg: In DatabaseDAO.java class
public class DatabaseDAO {
public static void main(String[] args) {
public ResultSet getalldetails(String query){
ResultSet rs = null;
try{
PreparedStatement stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
}
catch (SQLException e){
e.printStackTrace();
}
return rs;
}
}
Suppose , I have two classes Employee and Product.java. I want to call this method in both classes . Below is my code:
public class Employee {
String query ="Select * from Employee";
ResultSet rs=null;
List<EmployeeDto> emp= new ArrayList<EmployeeDto>();
DatabaseDAO.getalldetails(query);
while (rs .has next)
{
EmployeeDto qd=new EmployeeDto();
qd.setidrs.getInt("id"));
qd.setname(rs.getString("name"));
qd.setrollno(rs.getString("rollno"));
emp.add(qd);
}
}
Similarly, I have Product.java . I want to call same method to retrieval data form DB based on query based.
public class Product {
String query ="Select * from Product";
ResultSet rs=null;
List<ProductDto> emp= new ArrayList<ProductDto>();
DatabaseDAO.getalldetails(query);
while (rs .has next)
{
ProductDto qd=new ProductDto();
pd.setidrs.getInt("prodid"));
pd.setname(rs.getString("prodname"));
pd.setrollno(rs.getString("item"));
prod.add(pd);
}
}
I want to use one method in whole project to retrieve the data from DB . Means I want to do reusability of method. Please help me on this.
You can make it a static method in a class. Say Database. And you can access it anywhere by importing the Database class and calling Database.getalldetails (query)
As an aside, i see in your code, that you have defined getalldetails inside the main method. You should put it outside.
In the Employee class, you place code inside a class, but outside a method/constructor. Add a Constructor or a method and put the code there
Well, This can be an example of your concept.
I call it a DBMain class which has a entry point of bot classes, the Product and the Employee class by the DatabaseDAO class.
First, make an instance of the DatabaseDAO class then initialize the database connection.
DatabaseDAO dbDAO = new DatabaseDAO();
dbDAO.initConnection();
Second, create both Employee and Product class with the DatabaseDAO instance as a parameter.
Employee emp = new Employee(dbDAO);
Product prd = new Product(dbDAO);
Finally, you can retrieve the data from both instance of class by calling methods, getEmployeeList and getProductList each then close the connection owned by the DAO class.
try {
emplist = emp.getEmployeeList();
prdlist = prd.getProductList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
dbDAO.closeConnection();
}
The structure of the classes would be the same,
For example, the getProductList() looks:
public List<ProductDto> getProductList() throws SQLException {
ResultSet rs = null;
List<ProductDto> prd = new ArrayList<ProductDto>();
rs = dataDAO.getalldetails(query);
while (rs.next()) {
ProductDto qd = new ProductDto();
qd.setProdid(rs.getInt("prodid"));
qd.setProdname(rs.getString("prodname"));
qd.setItem(rs.getString("item"));
prd.add(qd);
}
rs.close();
return prd;
}
You can call getalldetails method in the DatabaseDAO instance and make the resultset a list of dto object.
The Employee and Product class:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Employee {
private static final String query = "Select * from Employee";
final DatabaseDAO dataDAO;
Employee(final DatabaseDAO dataDAO) {
this.dataDAO = dataDAO;
}
public List<EmployeeDto> getEmployeeList() throws SQLException {
ResultSet rs = null;
List<EmployeeDto> emp = new ArrayList<EmployeeDto>();
rs = dataDAO.getalldetails(query);
while (rs.next()) {
EmployeeDto qd = new EmployeeDto();
qd.setId(rs.getInt("id"));
qd.setName(rs.getString("name"));
qd.setRollno(rs.getString("rollno"));
emp.add(qd);
}
rs.close();
return emp;
}
}
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Product {
private static final String query = "Select * from Product";
final DatabaseDAO dataDAO;
Product(final DatabaseDAO dataDAO) {
this.dataDAO = dataDAO;
}
public List<ProductDto> getProductList() throws SQLException {
ResultSet rs = null;
List<ProductDto> prd = new ArrayList<ProductDto>();
rs = dataDAO.getalldetails(query);
while (rs.next()) {
ProductDto qd = new ProductDto();
qd.setProdid(rs.getInt("prodid"));
qd.setProdname(rs.getString("prodname"));
qd.setItem(rs.getString("item"));
prd.add(qd);
}
rs.close();
return prd;
}
}
The Dao class - DatabaseDAO, this class has a structure only, you can make your connection object depending on databases.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseDAO {
private Connection con;
public DatabaseDAO()
{
}
public void initConnection()
{
}
public Connection getDBConnection()
{
return con;
}
public void closeConnection()
{
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getalldetails(String query) {
ResultSet rs = null;
try {
PreparedStatement stmt = con.prepareStatement(query);
rs = stmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
The main method class here:
import java.sql.SQLException;
import java.util.List;
public class DBMain {
public static void main(String[] args)
{
DatabaseDAO dbDAO = new DatabaseDAO();
dbDAO.initConnection();
Employee emp = new Employee(dbDAO);
Product prd = new Product(dbDAO);
List<EmployeeDto> emplist = null;
List<ProductDto> prdlist = null;
try {
emplist = emp.getEmployeeList();
prdlist = prd.getProductList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
dbDAO.closeConnection();
}
}
}
Then, the dto classes left, EmpolyeeDto and ProductDto might be as follows:
public class EmployeeDto {
private int id;
private String name;
private String rollno;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollno() {
return rollno;
}
public void setRollno(String rollno) {
this.rollno = rollno;
}
}
public class ProductDto {
private int prodid;
private String prodname;
private String item;
public int getProdid() {
return prodid;
}
public void setProdid(int prodid) {
this.prodid = prodid;
}
public String getProdname() {
return prodname;
}
public void setProdname(String prodname) {
this.prodname = prodname;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
I am trying to show a combobox for each record that is fetched from database,but unfortunatley i can't get any combobox in expected column.
Here is code for my model class:
public class Employee {
private final int id;
private final SimpleStringProperty ename;
private final SimpleStringProperty ecnic;
private final SimpleDoubleProperty ebalance;
private final SimpleDoubleProperty etotalpaid;
private SimpleStringProperty estatus;
public Employee(int id, String ename, String ecnic, Double ebalance,
Double etotalpaid, String estatus) {
super();
this.id = id;
this.ename = new SimpleStringProperty(ename);
this.ecnic = new SimpleStringProperty(ecnic);
this.ebalance = new SimpleDoubleProperty(ebalance);
this.etotalpaid = new SimpleDoubleProperty(etotalpaid);
this.estatus = new SimpleStringProperty(estatus);
}
public String getEstatusproperty() {
return estatus.get();
}
public String getEstatus() {
return estatus.get();
}
public void setEstatus(String estatus) {
this.estatus = new SimpleStringProperty(estatus);
}
public int getId() {
return id;
}
public String getEname() {
return ename.get();
}
public String getEcnic() {
return ecnic.get();
}
public Double getEbalance() {
return ebalance.get();
}
public Double getEtotalpaid() {
return etotalpaid.get();
}
}
Here is code for my method that i call to fetch data from database..
public void attendence() throws SQLException{
employeelist = FXCollections.observableArrayList();
ename.setCellValueFactory(new PropertyValueFactory<Employee,String>("ename"));
ecnic.setCellValueFactory(new PropertyValueFactory<Employee,String>("ecnic"));
ebalance.setCellValueFactory(new PropertyValueFactory<Employee,Double>("ebalance"));
etotalpaid.setCellValueFactory(new PropertyValueFactory<Employee,Double>("etotalpaid"));
estatus.setCellValueFactory(new PropertyValueFactory<Employee,String>("estatus"));
estatus.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), attendenceoptions));
estatus.setOnEditCommit(
new EventHandler<CellEditEvent<Employee, String>>() {
#Override
public void handle(CellEditEvent<Employee, String> t) {
((Employee) t.getTableView().getItems().get(t.getTablePosition().getRow())).setEstatus(t.getNewValue());
};
});
estatus.setEditable(true);
stmt = conn.createStatement();
sql = "select * from employe";
rs = stmt.executeQuery(sql);
while(rs.next()){
employeelist.add(new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDouble(5),rs.getDouble(6),"Present"));
employeetable.setItems(employeelist);
}
stmt.close();
rs.close();
}
}
Added this in method to solve issue.
employeetable.setEditable(true);
This function returns two objects TMBase.customer#40fb1588, TMBase.customer#40fb1ad8, but I need to return these values emy, samera. I need to know what is the problem?
public ArrayList<TMBase.Customer> GetWorkerNameOfCustomerByID( int LineID)
{
ArrayList<TMBase.Customer> CustomerArr = new ArrayList<TMBase.Customer>();
connecttodatabase qq = new connecttodatabase();
qq.dbconnect();
if (qq.con != null)
{
String result = "";
ResultSet rs = null;
try {
CallableStatement cstmt = null;
Statement st = qq.con.createStatement();
cstmt = qq.con.prepareCall("{CALL GetWorkerNameOfCustomerByID(?)}");
cstmt.setInt(1, LineID);
rs = cstmt.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next())
{
TMBase.Customer CustomerObj=new TMBase.Customer();
CustomerObj.setWorkerName(rs.getString("WorkerName"));
CustomerArr.add(CustomerObj);
}
} catch (SQLException e) {
e.printStackTrace();
}
qq.closeConnection();
}
return CustomerArr;
}
Customer class:
package TMBase;
public class Customer {
private int ID;
private int LineId;
private int WorkerId;
private Timestamp DateSubscribe;
private String WorkerName;
public int getID() {
return this.ID;
}
public int setID(int ID){
return this.ID = ID;
}
//////////////////////////////////////////////
public int getLineId() {
return this.LineId;
}
public int setLineId(int LineId){
return this.LineId = LineId;
}
//////////////////////////////////////////////
public int getWorkerId() {
return this.WorkerId;
}
public int setWorkerId(int WorkerId){
return this.WorkerId = WorkerId;
}
///////////////////////////////////////////////
public Timestamp getDateSubscribe() {
return this.DateSubscribe;`enter code here`
}
public Timestamp setDateSubscribe(Timestamp DateSubscribe){
return this.DateSubscribe = DateSubscribe;
}
///////////////////////////////////////////////
public String getWorkerName() {
return this.WorkerName;
}
public String setWorkerName(String WorkerName){
return this.WorkerName = WorkerName;
}
}
you need to override the toString() method of your Customer object.
I'm assuming you are using an ArrayAdapter to display these in your ListView, which calls toString() on each item in the dataset to display on the screen.
By overriding toString(), you can return whatever data you want to be displayed in the ListView for example:
public String toString(){
return getWorkerName();
}
can you please help me rectify the code below, I'm trying to create a populated drop down list in struts 2 in Eclipse as my IDE. This is my first time to use 'STRUTS' as well as 'IDE ECLIPSE'.
To be specific by the SELECT statement I do not know how to write the code that, when a user selects the 'Make' of the car, the database extracts the different 'Models' of that make. But other select items like 'Color', should be optional in that a user can proceed to search for the 'Make' minus choosing an option from them.
Please help I'm new in ActionClass and DataBase. Thanx in advance.
package drive;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.opensymphony.xwork2.ActionSupport;
public class CarSearch extends ActionSupport {
private String model;
private String modification;
private String engine;
private String color;
private String bodyType;
private String minPrice;
private String maxPrice;
private String mileage;
private int minYear;
private int maxYear;
private String make;
public String execute () {
String ret = NONE;
Connection conn = null;
try {
String URL = "jdbc:mysql://localhost/Cars";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(URL, "root", "$jademedia247");
String sql = "SELECT make FROM type WHERE";
sql+=" model = ? AND modification = ? ";
PreparedStatement ps = conn.prepareStatement (sql);
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
while (rs.next()){
make = rs.getString(1);
ret = SUCCESS;
}
} catch (Exception e) {
ret = ERROR;
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
return ret;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getModification() {
return modification;
}
public void setModification (String modification) {
this.modification = modification;
}
public String getEngine() {
return engine;
}
public void setEngine (String engine) {
this.engine = engine;
}
public String getColor() {
return color;
}
public void setColor (String color) {
this.color = color;
}
public String getBodyType() {
return bodyType;
}
public void setBodyType(String bodyType) {
this.bodyType = bodyType;
}
public String getMinPrice() {
return minPrice;
}
public void setMinPrice(String minPrice) {
this.minPrice = minPrice;
}
public String getMaxPrice () {
return maxPrice;
}
public void setMaxPrice (String maxPrice) {
this.maxPrice = maxPrice;
}
public String getMileage () {
return mileage;
}
public void setMileage (String mileage) {
this.mileage = mileage ;
}
public int getMinYear() {
return minYear;
}
public void setMinYear(int minYear) {
this.minYear = minYear;
}
public int getMaxYear() {
return maxYear;
}
public void setMaxYear(int maxYear) {
this.maxYear = maxYear;
}
public String getMake() {
return make;
}
public void setMake(String make){
this.make = make;
}
}
PreparedStatement ps = conn.prepareStatement ("SELECT field_name FROM table_name WHERE model = ? AND modification = ? ");
ps.setString(1, model);
ps.setString(2, modification);
ResultSet rs = ps.executeQuery();
//it will help you