I'm trying to retrieve data from my Model class into textfield via GET, although nullpointexception is throwing an error
The code in the View class is =
public View_EditCustomer(Model_Customer cust) {
customer = cust;
txtname.setText(customer.GetFName());
txtSecondName.setText(customer.GetLName());
initComponents();
}
and in another View class it is =
private void btnSelectActionPerformed(java.awt.event.ActionEvent evt) {
ListSelectionModel rowSM = jTable1.getSelectionModel();
int row = rowSM.getMinSelectionIndex();
int Appointment_ID = (Integer)resultModel.getValueAt(row, 0);
Model_Customer cust = null;
try{
cust = Controller_ManageCustomer.GetCustomer(Appointment_ID);
new View_EditCustomer(cust).setVisible(true);
}catch(Exception ex){
JOptionPane.showMessageDialog(this,ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
}
}
Model_Customer code parts =
public static Model_Customer QueryID(int Appointment_ID) throws Exception
{
try{
Statement stmt = Model_Customer.conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM appointment WHERE appointmentid="+Appointment_ID+" LIMIT 1;");
if(rs.next())
return new Model_Customer(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8),rs.getString(9),rs.getString(10),rs.getString(11),rs.getString(12));
}catch(Exception e){
throw new Exception(e.getMessage());
}
return null;
}
private Model_Customer(int Appointment_ID, String FName, String LName, String Registration, String Make, String Model, String Engine, String Year, String Mileage, String Type, String Date, String Time)
{
this._Appointment_ID=Appointment_ID;
this._Type=Type;
this._Time=Time;
this._Date=Date;
this._FName=FName;
this._LName=LName;
this._Make=Make;
this._Model=Model;
this._Engine=Engine;
this._Year=Year;
this._Mileage=Mileage;
this._Registration=Registration;
this._inSync=true;
}
public int GetID()
{
return this._Appointment_ID;
}
public String GetFName()
{
return _FName;
}
public String GetLName()
{
return _LName;
}
public String GetRegistration()
{
return _Registration;
}
public String GetMake()
{
return _Make;
}
public String GetModel()
{
return _Model;
}
public String GetEngine()
{
return _Engine;
}
public String GetYear()
{
return _Year;
}
public String GetMileage()
{
return _Mileage;
}
public String GetType()
{
return _Type;
}
public String GetDate()
{
return _Date;
}
public String GetTime()
{
return _Time;
}
In debugging Model_Customer cust is actually populated by data and it actually goes to the end to txtname.setText(customer.GetFName()); goes to Model_Customer GetFName and should retrieve the name but throws an exception (int)0. Would really appreciate your help!!
Shouldn't initComponents(); be called before using TextViews ?
public View_EditCustomer(Model_Customer cust) {
initComponents();
customer = cust;
txtname.setText(customer.GetFName());
txtSecondName.setText(customer.GetLName());
}
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 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);
It seems that I don't understand inheritance.
I have these classes : PicaAsset, VideoAsset that inherit from a class names Assets.
This is the Assets class declaration :
public class Assets {
protected int book=0;
protected int fromChapter=0;
protected int toChapter=0;
protected int fromVerse=0;
protected int toVerse=0;
protected String creator=null;
protected String discription=null;
protected String source=null;
protected String title=null;
protected String duration=null;
protected String url=null;
public Assets(int book, int fromChapter, int toChapter, int fromVerse,
int toVerse, String creator, String discription, String source,
String title, String duration, String url) {
this.book = book;
this.fromChapter = fromChapter;
this.toChapter = toChapter;
this.fromVerse = fromVerse;
this.toVerse = toVerse;
this.creator = creator;
this.discription = discription;
this.source = source;
this.title = title;
this.duration = duration;
this.url = url;
}
public Assets() {
}
public int getBook() {
return book;
}
public void setBook(int book) {
this.book = book;
}
public int getFromChapter() {
return fromChapter;
}
public void setFromChapter(int fromChapter) {
this.fromChapter = fromChapter;
}
public int getToChapter() {
return toChapter;
}
public void setToChapter(int toChapter) {
this.toChapter = toChapter;
}
public int getFromVerse() {
return fromVerse;
}
public void setFromVerse(int fromVerse) {
this.fromVerse = fromVerse;
}
public int getToVerse() {
return toVerse;
}
public void setToVerse(int toVerse) {
this.toVerse = toVerse;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
PicAsset :
public class PicAsset extends Assets implements IsSerializable {
private int picId=0;
public PicAsset(){
}
public PicAsset(int picId, int book, int fromChapter, int toChapter,
int fromVerse, int toVerse, String creator, String discription,
String source, String title, String duration, String url) {
super( book, fromChapter, toChapter,
fromVerse, toVerse, creator, discription,
source, title, duration, url);
this.picId = picId;
}
public int getIdpic() {
return picId;
}
public void setIdpic(int idpic) {
this.picId = idpic;
}
}
Now I use an RPC call to use methods declared in the server side to get info from my datbase, as you can see the method return a List of PicAsset , List.
rpcService.getPicture((books.getSelectedIndex()+1), (chapters.getSelectedIndex()+1), new AsyncCallback<List<PicAsset>>(){
public void onFailure(Throwable caught) {
Window.alert("Can't connect to database" + books.getSelectedIndex() + chapters.getSelectedIndex());
}
public void onSuccess(List<PicAsset> result) {
int listSize = result.size();
int i;
int flag = 0;
assetPicPanel.clear();
Label frameTitle = new Label("Pictures");
for(i=0;i<listSize;i++)
{
if(flag == 0)
{
assetPicPanel.add(frameTitle);
flag = 1;
}
HorizontalPanel vPanelPic = new HorizontalPanel();
System.out.print("heeeeey" +" " + result.get(i).getFromChapter());
Grid g = result.get(i).AssetGrid(result.get(i));
vPanelPic.add(g);
assetPicPanel.add(vPanelPic);
}
}
});
Now when I print the ..get().getFromChapter() on the server side it brings the right values.
But when I print the values that have been returned to the RPC call I get the default constructor values... and not what have to be sent back.
Here also the getPicture implementation on the server side :
public List<PicAsset> getPicture(int book, int chapter) throws Exception
{
System.out.print("getPicture ok " + book +"," + chapter);
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet result = null;
List<PicAsset> relevantAssets = new ArrayList<PicAsset>();
PicAsset relAsset;
try {
conn = getConnection();
pstmt = conn.prepareStatement("SELECT * FROM picasset WHERE book = ? AND fromChapter <= ? AND toChapter >= ?");
//System.out.print("connection" + conn);
pstmt.setInt(1, book);
pstmt.setInt(2, chapter);
pstmt.setInt(3, chapter);
result = pstmt.executeQuery();
// System.out.print(result);
while (result.next()) {
//System.out.print("in while");
relAsset = new PicAsset(result.getInt("picId"),result.getInt("book"), result.getInt("fromChapter"), result.getInt("toChapter"),result.getInt("fromVerse"),result.getInt("toVerse"),result.getString("creator"),result.getString("discription"),result.getString("source"),result.getString("title"),result.getString("duration"),result.getString("url"));
relevantAssets.add(relAsset);
}
}
catch (SQLException sqle)
{
sqle.printStackTrace();
}
finally
{
// Cleanup
result.close();
pstmt.close();
conn.close();
}
System.out.print("In MySql get Chapter " + relevantAssets.get(0).getFromChapter() + " " + relevantAssets.get(0).getIdpic());
return relevantAssets;
}
Within GWT RPC it would be much better to use raw arrays rather than collection interfaces - return from your method PicAsset[] instead of List. This will allow you (a) solve your problem and (b) escape unnecessary classes to be compiled into client code.
See "Raw Types" section at gwtproject.org
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