Here is my class which is a gui consisting of two tabs, my profile and edit profile. I am having a problem at the 'myProfileTabStateChanged' method when the index value changes to 1. When tab index is 0, 'myProfile()' method executes successfully, but when index is 1, 'editProfile()' is giving too many errors. The purpose of editprofile() is simply to extract the values from a bean class and set it to the textfields appropriately. What am I doing wrong? Please note the bean class variables are being populated correctly using setter methods, but in this class I am unable to retrieve the values using the getters? Perhaps it is retrieving but problem lies in being unable to set it to textfield.
public class MainMenu extends javax.swing.JFrame {
Academic ac = new Academic();
academicBean bn = new academicBean();
/**
* Creates new form MainMenu
*/
public MainMenu() {
initComponents();
// myProfile();
// editProfile();
}
public void myProfile() {
ac.retrieveAcademic();
nameLabel.setText(""+ac.title+" "+ac.forename+" "+ac.surname);
roleLabel.setText("Role: " + ac.role);
roomLabel.setText("Room: " + ac.room);
pageLabel.setText("Page: " + ac.page);
hoursLabel.setText("Hours: " + ac.hours);
phoneLabel.setText("Phone: " + ac.phone);
mobileLabel.setText("Mobile: " + ac.mobile);
emailLabel.setText("Email: " + ac.email);
imageLabel.setIcon(ac.format);
}
public void editProfile() {
ac.retrieveAcademic();
idLabel.setText("Academic Id: "+bn.getAcademicId());
txt_title.setSelectedItem(bn.getTitle().toString());
txt_fn.setText(bn.getForename().toString());
txt_ln.setText(bn.getSurname().toString());
combo_role.setSelectedItem(bn.getRole().toString());
txt_room.setText(bn.getRoom().toString());
txt_page.setText(bn.getPage().toString());
txt_hours.setText(bn.getHours().toString());
txt_phone.setText(bn.getPhone().toString());
txt_mobile.setText(bn.getMobile().toString());
txt_email.setText(bn.getEmail().toString());
}
private void myProfileTabStateChanged(javax.swing.event.ChangeEvent evt) {
JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
int index = sourceTabbedPane.getSelectedIndex();
if (index == 0) {
myProfile();
}
else if (index == 1) {
editProfile();
}
}
//Class Academic
public class Academic extends javax.swing.JFrame {
String filename = null;
int s = 0;
byte[] person_image = null;
ImageIcon format = null;
LoginBean l = new LoginBean();
Connection con = javaconnect.ConnectDB();
academicBean bean = new academicBean();
PreparedStatement pst = null;
ResultSet rs = null;
int id;
String title;
String titleValue;
String forename;
String surname;
String role;
String roleValue;
String room;
String page;
String hours;
String phone;
String mobile;
String email;
byte[] imagedata = null;
public Academic() {
initComponents();
}
#SuppressWarnings("unchecked")
public void retrieveAcademic() {
try {
pst = con
.prepareStatement("SELECT * FROM AcademicInfo where Email=? and Password=?");
pst.setString(1, l.getUsername());
pst.setString(2, l.getPassword());
rs = pst.executeQuery();
while (rs.next()) {
id = (rs.getInt(1));
bean.setAcademicId(id);
title = (rs.getString(2));
bean.setTitle(title);
forename = (rs.getString(3));
bean.setForename(forename);
surname = (rs.getString(4));
bean.setSurname(surname);
role = (rs.getString(5));
bean.setRole(role);
room = (rs.getString(6));
bean.setRoom(room);
page = (rs.getString(7));
bean.setPage(page);
hours = (rs.getString(8));
bean.setHours(hours);
phone = (rs.getString(9));
bean.setPhone(phone);
mobile = (rs.getString(10));
bean.setMobile(mobile);
email = (rs.getString(11));
bean.setEmail(email);
imagedata = (rs.getBytes("Image"));
format = new ImageIcon(imagedata);
} // end while
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Academic.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pst != null) {
pst.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Academic.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
// Bean Class
public class AcademicBean {
private int academicid;
private String title;
private String forename;
private String surname;
private String role;
private String room;
private String page;
private String hours;
private String phone;
private String mobile;
private String email;
private byte [] image;
private String pass;
//Setters
public void setAcademicId (int academicid) {
this.academicid = academicid;
}
public void setTitle(String title) {
this.title = title;
}
public void setForename(String forename) {
this.forename = forename;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setRole(String role) {
this.role = role;
}
public void setRoom(String room) {
this.room = room;
}
public void setPage(String page) {
this.page = page;
}
public void setHours(String hours) {
this.hours = hours;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public void setEmail(String email) {
this.email = email;
}
public void setImage (byte [] image) {
this.image = image;
}
public void setPassword (String pass) {
this.pass= pass;
}
//Gettters
public String getPassword () {
return pass;
}
public int getAcademicId() {
return academicid;
}
public byte [] getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getForename() {
return forename;
}
public String getSurname() {
return surname;
}
public String getRole() {
return role;
}
public String getRoom() {
return room;
}
public String getPage() {
return page;
}
public String getHours() {
return hours;
}
public String getPhone() {
return phone;
}
public String getMobile() {
return mobile;
}
public String getEmail() {
return email;
}
}
//Stacktrace
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.sqlite.PrepStmt.(PrepStmt.java:37)
at org.sqlite.Conn.prepareStatement(Conn.java:231)
at org.sqlite.Conn.prepareStatement(Conn.java:224)
at org.sqlite.Conn.prepareStatement(Conn.java:213)
at eecsCRM.Academic.retrieveAcademic(Academic.java:68)
at eecsCRM.MainMenu.editProfile(MainMenu.java:50)
at eecsCRM.MainMenu.myProfileTabStateChanged(MainMenu.java:569)
at eecsCRM.MainMenu.access$300(MainMenu.java:13)
at eecsCRM.MainMenu$4.stateChanged(MainMenu.java:194)
at javax.swing.JTabbedPane.fireStateChanged(JTabbedPane.java:400)
at javax.swing.JTabbedPane$ModelListener.stateChanged(JTabbedPane.java:253)
at javax.swing.DefaultSingleSelectionModel.fireStateChanged(DefaultSingleSelectionModel.java:116)
at javax.swing.DefaultSingleSelectionModel.setSelectedIndex(DefaultSingleSelectionModel.java:50)
at javax.swing.JTabbedPane.setSelectedIndexImpl(JTabbedPane.java:599)
at javax.swing.JTabbedPane.setSelectedIndex(JTabbedPane.java:574)
at javax.swing.plaf.basic.BasicTabbedPaneUI$Handler.mousePressed(BasicTabbedPaneUI.java:3628)
at javax.swing.plaf.synth.SynthTabbedPaneUI$1.mousePressed(SynthTabbedPaneUI.java:279)
at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:262)
at java.awt.Component.processMouseEvent(Component.java:6264)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4235)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Just a wild a***'d guess: You appear to have at least two completely unrelated academicBean objects (note that the class should be named AcademicBean), one in Academic, and one in MainMenu. I have a suspicion that they should be one and the same.
Perhaps MainMenu should have:
academicBean bn = ac.getAcademicBean();
and Academic have:
public academicBean getAcademicBean() {
return bean;
}
so that MainMenu can extract Academic's bean making the bean variables refer to one and the same bean object.
Related
I'm getting a "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0" and I don't even know what is wrong.
I have 4 classes. I get data from two MySQL databases in the first (ConnectionClass) and the second one is a main class from which I run and print the result but for some reason it doesn't work. The third and fourth are normal classes.
The first database is called account which has a few columns and a foreign key(f_id) from the second database f.
My Connection class:
package tryout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class ConnectionClass {
Connection connection;
public void connect() {
String url = "jdbc:mysql://localhost:3306/mydemo";
String username = "root";
String password = "12345";
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<F> getAllFs() {
connect();
ArrayList<F> l = new ArrayList<F>();
String sql="SELECT * FROM f";
try {
Statement s = connection.createStatement();
ResultSet rSet = s.executeQuery(sql);
while(rSet.next()) {
int j=0;
l.get(j).setF_id(rSet.getInt("f_id"));
l.get(j).setF_name(rSet.getString("f_name"));
j++;
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return l;
}
public ArrayList<Account> getAllAccounts() {
connect();
ArrayList<Account> liste = new ArrayList<Account>();
String sql="SELECT * FROM account";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
int i=0;
liste.get(i).setUsername(rs.getString("username"));
liste.get(i).setPassword(rs.getString("password"));
liste.get(i).setFullname(rs.getString("fullname"));
liste.get(i).setEmail(rs.getString("email"));
liste.get(i).setWebsite(rs.getString("website"));
liste.get(i).setAge(rs.getInt("age"));
liste.get(i).setF((F) rs.getObject("f_id"));
i++;
}
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return liste;
}
}
My main class:
package tryout;
import java.util.ArrayList;
public class MAIN {
public static void main(String[] args) {
ConnectionClass class1 = new ConnectionClass();
ArrayList<Account> list = new ArrayList<Account>();
list = class1.getAllAccounts();
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i).getUsername()+" "+list.get(i).getPassword());
}
}
}
Account.java:
package tryout;
public class Account {
private String username;
private String password;
private String fullname;
private String email;
private String website;
private int age;
private F f;
public Account() {
super();
}
public Account(String username, String password, String fullname, String email, String website, int age, F f) {
super();
this.username = username;
this.password = password;
this.fullname = fullname;
this.email = email;
this.website = website;
this.age = age;
this.f = f;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public F getF() {
return f;
}
public void setF(F f) {
this.f = f;
}
}
F.java:
package tryout;
public class F {
private int f_id;
private String f_name;
public F() {
super();
}
public F(int f_id, String f_name) {
super();
this.f_id = f_id;
this.f_name = f_name;
}
public int getF_id() {
return f_id;
}
public void setF_id(int f_id) {
this.f_id = f_id;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
}
Here are my databases:
I tried changing getAllAccounts to this:
public ArrayList<Account> getAllAccounts() {
connect();
ArrayList<Account> liste = new ArrayList<Account>();
ArrayList<F> l2 = new ArrayList<F>();
//l2 = getAllFs();
String sql="SELECT * FROM account";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(sql);
while(rs.next()) {
Account acc = new Account();
acc.setAge(rs.getInt("age"));
acc.setEmail(rs.getString("email"));
acc.setUsername(rs.getString("username"));
acc.setPassword(rs.getString("password"));
acc.setFullname(rs.getString("fullname"));
}
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return liste;
}
and when i run it in the main class nothing shows. The error is gone but nothing is printed in the console.
The problem is with the following lines:
ArrayList<F> l = new ArrayList<F>();
String sql="SELECT * FROM f";
try {
Statement s = connection.createStatement();
ResultSet rSet = s.executeQuery(sql);
while(rSet.next()) {
int j=0;
l.get(j).setF_id(rSet.getInt("f_id"));
l.get(j).setF_name(rSet.getString("f_name"));
j++;
}
The list has no element but you are using l.get(j).
In order to understand this problem better, run the following code and you will get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> l = new ArrayList<String>();
System.out.println(l.get(0));
}
}
Keeping aside the problem, you are initializing j inside while loop which means the incremented value is lost with every iteration. In order to solve the problem, replace
while(rSet.next()) {
int j=0;
l.get(j).setF_id(rSet.getInt("f_id"));
l.get(j).setF_name(rSet.getString("f_name"));
j++;
}
with
while(rSet.next()) {
l.add(rSet.getInt("f_id"));
l.add(rSet.getString("f_name"));
}
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);
I am trying to read an API link which contains data of JSON format. this is what i am trying to read and display on the phone:
[[],{"index":"2","name":"jim","email":"jim#outlook.com","contact":"0122511336","username":"jim","password":"jim","photo":"student.jpg","status":"Active"}]
The program supposed to authenticate the username and password inputs and this dipsplay the content of the above from URL.
Below is the codes and so far what I have done. Please someone help me to get this through.
package org.json.me;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Login extends MIDlet implements CommandListener {
private String name;
private String email;
private int contact;
private String username;
private String password;
private String status;
private final String JSONformat = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email=email;
}
public int getContact() {
return contact;
}
public void setContact (int contact) {
this.contact=contact;
}
public String getUsername () {
return username;
}
public void setUsername (String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword (String Password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status=status;
}
public String toString() {
return getName()+""+getEmail()+""+getContact()+""+getUsername()+""+getPassword()+""+getStatus();
}
public String fromJSON(String jsonString) {
try {
JSONObject json = new JSONObject(jsonString);
setName(json.getString("name"));
setEmail(json.getString("email"));
setContact(json.getInt("contact"));
setUsername(json.getString("username"));
setPassword(json.getString("password"));
setStatus(json.getString("status"));
}
catch (JSONException e) {
e.printStackTrace();
}
return JSONformat;
}
TextField UserName = null;
TextField Password = null;
Form authForm, mainscreen;
TextBox t = null;
StringBuffer b = new StringBuffer();
private Display myDisplay = null;
private Command okCommand = new Command("OK", Command.OK, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 2);
private Command backCommand = new Command("Back", Command.BACK, 2);
private Alert alert = null;
public Login() {
myDisplay = Display.getDisplay(this);
UserName = new TextField("Username", "", 10, TextField.ANY);
Password = new TextField("Password", "", 10, TextField.ANY);
authForm = new Form("Identification");
mainscreen = new Form("Logging IN");
mainscreen.append("Logging in....");
mainscreen.addCommand(backCommand);
authForm.append(UserName);
authForm.append(Password);
authForm.addCommand(okCommand);
authForm.addCommand(exitCommand);
authForm.setCommandListener(this);
myDisplay.setCurrent(authForm);
}
public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command c, Displayable d) {
if ((c == okCommand) && (d == authForm)) {
if (UserName.getString().equals("") || Password.getString().equals("")) {
alert = new Alert("Error", "You should enter Username and Password", null,AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
myDisplay.setCurrent(alert);
}
else {
//myDisplay.setCurrent(mainscreen);
login(UserName.getString(), Password.getString());
}
}
if ((c == backCommand) && (d == mainscreen)) {
myDisplay.setCurrent(authForm);
}
if ((c == exitCommand) && (d == authForm)) {
notifyDestroyed();
}
}
public void login(String UserName, String PassWord) {
HttpConnection connection = null;
DataInputStream in = null;
String base = "http://sunday-tech.com/chunghua/api/login.php";
String url = base + "?username=" + UserName + "&password=" + PassWord;
OutputStream out = null;
try
{
connection = (HttpConnection) Connector.open(url);
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("IF-Modified-Since", "2 Oct 2002 15:10:15 GMT");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Length", "" + (UserName.length() + PassWord.length()));
connection.setRequestProperty("UserName", UserName);
connection.setRequestProperty("PassWord", PassWord);
out = connection.openDataOutputStream();
out.flush();
in = connection.openDataInputStream();
int ch;
while ((ch = in.read()) != -1) {
b.append((char) ch);
//System.out.println((char)ch);
}
mainscreen.append(fromJSON(b.toString()));
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (connection != null) {
connection.close();
}
}
catch (Exception x) {
}
myDisplay.setCurrent(mainscreen);
}
}
Change your setter methods to also change the TextField values. For example
public void setUsername (String username) {
this.username = username;
this.UserName.setString(username);
}
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
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());
}