Loading from a database to a jlist brings errors - java

I have created a database and every entry from the JList will be added to a table in the database. This work perfectly, but my next task is to get whatever is in the database to load to the JList. I have a function created within the button but it brings up errors. I'm struggling with how to fix this so I hope somebody can resolve it.
Thanks
Here is my code:
JButton btnDb1 = new JButton("J");
btnDb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
ResultSet rs = st.executeQuery("SELECT * FROM patient");
while (rs.next()) {
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid);
patient.setName(rs.getString("patientname"));
patient.setAddress(rs.getString("patientaddress"));
patient.setPhoneNum(rs.getString("patientphone"));
patient.setID(rs.getInt("patientid"));
MainDentist.model.addElement(patient);
}
} catch (Exception e) {
System.out.println(" Error ");
}
}
});
btnDb1.setBounds(200, 393, 120, 23);
contentPane.add(btnDb1);
Here is my patient class:
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}

Let me rephrase the actionlistener – posting code in comments isn't really helpfull :)
First I would put the code from your actionPerformed method somewhere else, best would be even to create some class that handles the whole reading and maybe writing of the database. That way you don't mix reading the database with pushing buttons (maybe you want to create another button that reads the database, too. Then you don't have to write all the code again). Anyway, this is an example:
JButton btnDb1 = new JButton("J");
btnDb1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
readDatabase();
}
});
public void onActionPerformed(){
try {
// I don't know where you have that part of code, but you didn't create any statement variable. So here an example DB-connection:
String url = "jdbc:mysql://localhost/myDatabase";
Connection connection = DriverManager.getConnection(url, "username", "password");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM patient");
while (rs.next()) {
// read the columns one by one, that way it may be easier to detect errors if one column is wrong
String name = rs.getString("patientname");
String address = rs.getString("patientaddress");
String phone = rs.getString("patientphone");
int id = rs.getInt("patientid");
// now that you have all values, create the patient and add it to the model
// if you have all parameters for the constructor, you don't need to use the setters to set the name and address …
MainDentist.model.addElement(new Patient(name, address, phone, id));
}
} catch (Exception e) {
// as JB Nizet suggested, it is easier to detect errors, when you print the whole stack trace (it will tell you in which line the exception gets thrown
e.printStackTrace();
}
}
This still may not work right away, if you get errors, edit your post and tell us what goes wrong. BTW: I noticed that you have your variables name, address and all this in the patient set to public. This isn't wrong but it is recommended to use getter and setters (as you do) and make the variables private. That way you can control how the variables get accessed from outside.

Related

How to give a JList an ID and name?

I have a simple database with 2 columns (ID, Firstname). Now I display each Firstname from my table as an List Item. That works so far. What I want to do is connect my ID from my db table with the firstname cause if i click on a list item the data will be shown in a textfield.
I've created a helper class that has the Name and ID as fields.
public class ListDataHelper {
private int id;
private String name;
public ListDataHelper(int id, String description) {
this.id = id;
this.name = description;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String toString() {
return name;
}
}
My main class looks like this and it works so far.
private void getAllAccounts(){
listAccounts.removeAll();
try{
String sql="select * from accounts";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
DefaultListModel DLM = new DefaultListModel();
while(rs.next()){
DLM.addElement(new ListDataHelper(rs.getInt("ID"), rs.getString("FirstName")));
}
listAccounts.setModel(DLM);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
}
catch(Exception e) {
}
}
}
But I'm stuck at the point when I want to retrieve data. I don't know how to use my created helper class or how to get the ID from the selectedValue.
private void getAllData() {
String data =listAccounts.getSelectedValue();
String sql="select * from accounts where ID=?";
try{
pst=conn.prepareStatement(sql);
pst.setString(1, data);
rs=pst.executeQuery();
while(rs.next()){
String add1 =rs.getString("ID");
txtID.setText(add1);
String add2 =rs.getString("FirstName");
txtFirstName.setText(add2);
String add3 =rs.getString("LastName");
txtLastName.setText(add3);
String add4 =rs.getString("Cheque");
txtCheque.setText(add4);
String add5 =rs.getString("Savings");
txtSavings.setText(add5);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
}
catch(Exception e) {
}
}
}
When I compile the code I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
ccibank.ListDataHelper cannot be cast to java.lang.String
Thanks already in advance! :)
As always, everything would be simpler by reading the documentation.
As you can see immediately if you click the link (or if you just read the warnings emitted by the compiler), DefaultListModel is a generic class, just like a Collection. So you're supposed to specify the type of objects that you put in such a model. You're not putting Strings inside. You're putting instances of ListDataHelper. So it should be declared as
DefaultListModel<ListDataHelper>
If you browse to the JList documentation, you'll see that it's also a generic type: it contains the elements of the same type as its list model. So it should be declared as
JList<ListDataHelper>
Now, what do you get when you call getSelectedValue() on a JList? Again, read the documentation: You get an object of the generic type E. In this case, the generic tpe E is ListDataHelper. This makes perfect sense, doesn't it? If you store objects of type ListDataHelperin the list, the selected value is not a String. It's a ListDataHelper.
So the code should be:
ListDataHelper selectedAccount = listAccounts.getSelectedValue();
Another thing that strikes me is that, even though your code doesn't compile, you haven't posted the compilation error(s) in your question. Why is that? The compilation errors indicate what is wrong, and where. Reading the error is the first thing you should do when you have an error. Don't ignore errors. Reading (the errors, the documentation), is extremely important whe programming.

How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));

Getting Data in JList via JDBC - The missing link

I've been stuck at a seemingly simple problem for hours and I just can't find the solution. I'm trying to implement a very simple Forum in Java and I'm trying to load the entrys at the moment.
My forum is a JList that is filled with JPanels and that accepts entries via the JLists DefaultListModel and the addMessage method. So if I add an entry without the database it looks like this:
MessageList m = new MessageList();
m.addMessage("NAME AUTOR", "<html><body style='width: 675px;'>Lorem ipsum dolor sit amet.", "22.01.13", "SOA");
The messageList class looks like this:
public class MessageList extends JList{
DefaultListModel messageModel = new DefaultListModel();
MessageRenderer messageRenderer = new MessageRenderer();
public MessageList( ){
this.setCellRenderer(messageRenderer);
this.setModel(messageModel);
}
public void addMessage(String author, String text, String date, String tag){
messageModel.addElement(new Message(author, text, date, tag));
}
}
I've also written the Code for getting an ArrayList (called allBtr) with the Message Objects (called ConBeitrag) from the database:
ArrayList<ConBeitrag> allBtr = new ArrayList<ConBeitrag>();
ConBeitrag conBtr = new ConBeitrag();
try {
allBtr = conBtr.getAllBtr();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The message objects look like this:
public class ConBeitrag {
private int beitragid;
private int projektid;
private int mitarbeiterid;
private String beitragText;
private String erstellt_am;
private String geaendert_am;
private String schlagwort1;
private String schlagwort2;
private MdBeitrag mdBtr = new MdBeitrag();
public ConBeitrag (){
}
public ConBeitrag(int beitragid, int projektid, int mitarbeiterid, String beitragText, String erstellt_am, String geaendert_am){
this.beitragid = beitragid;
this.projektid = projektid;
this.mitarbeiterid = mitarbeiterid;
this.erstellt_am = erstellt_am;
this.geaendert_am = geaendert_am;
this.beitragText = beitragText;
this.schlagwort1 = schlagwort1;
this.schlagwort2 = schlagwort2;
}
public ArrayList<ConBeitrag> getAllBtr() throws SQLException{
MdBtrInterface modInt;
modInt = new MdBeitrag();
ArrayList<ConBeitrag> AlBtr = modInt.getAllBtr();
for(ConBeitrag object: AlBtr){
System.out.println(object.beitragText);
}
return AlBtr;
}
}
Now what would be the smartest way to get the ArrayList into a form that I can pass into the addMessage method? I've kind of approached this from the GUI end, then from the database end, and now I'm stuck in the middle.
Overwritten toString() method:
#Override
public String toString() {
return mitarbeiterid + beitragstext + erstellt_am + schlagwort1 + schlagwort2;
}
"The messages are stored inside the ArrayList as Objects if that helps. So if I run "System.out.println(allBtr);" it gives me "[ConBeitrag#48f4104f, ConBeitrag#f5ad7f4, ConBeitrag#1517dc0c]"
You need to override the toString method in your ConGeitrag class. Something like this.
public class ConBeitrag {
...
#Override
public String toString(){
return author + ", " + text + ", " + date + ", " + tag;
}
}
You can make the return any format you want. Test this one out and make changes as desired to the format.
Try this out as a Helper method (after you've overridden the toString)
public JList createJList(ResultSet rs){
DefaultListModel model = new DefaultListModel();
while (rs.next()){
String author = rs.getString("author"); // Just an example. You may
String text = rs.getString("text"); // need to retrieve your
String date = rs.getString("date"); // data differently
String tag = rs.getString("tag");
Message message = new Message(author, text, date, tag);
model.addElement(message);
}
JList list = new JList(model);
return list;
}
I don't really see a need for a Custom JList for this situation.
Test run: output : 3testtestnullnull. Besides the formatting, it works fine
public class ConBeitragTest {
public static void main(String[] args) {
ConBeitrag con = new ConBeitrag(1, 2, 3, "test", "test", "test");
System.out.println(con);
}
}
class ConBeitrag {
private int beitragid;
private int projektid;
private int mitarbeiterid;
private String beitragText;
private String erstellt_am;
private String geaendert_am;
private String schlagwort1;
private String schlagwort2;
public ConBeitrag() {
}
public ConBeitrag(int beitragid, int projektid, int mitarbeiterid, String beitragText, String erstellt_am, String geaendert_am) {
this.beitragid = beitragid;
this.projektid = projektid;
this.mitarbeiterid = mitarbeiterid;
this.erstellt_am = erstellt_am;
this.geaendert_am = geaendert_am;
this.beitragText = beitragText;
this.schlagwort1 = schlagwort1; // This is null
this.schlagwort2 = schlagwort2; // This is null
}
#Override
public String toString() {
return mitarbeiterid + beitragText + erstellt_am + schlagwort1 + schlagwort2;
}
}

modelling a customer class in java for a database application

I'm working on a java swing application which handles Customer management for a shop.
I'm trying to build it based on the mvc pattern, but actually i'm somewhat unexperienced in it.
Basically, theres a View with some Textfields for Customer Creation and of course the class called Customer. If the form is submitted an object of Customer is created and saved to the database.
Now, my problem was setting up a view to show all Customers in a JTable. Actually, not the view itself was the problem, but refreshing the view, when a new customer was added or a customer was changed.
Therefore i created a new class called "Customers" which had an arraylist with all customers in it and everytime a customer was created, it was added to this arraylist.
When the mainframe of my application started, an object of "Customers" was created, fetching all customers from my database, putting it in the arraylist just for the jtable.
the jtable was added to the object of customers as a listener and had an interface called CustomerListener implemented, which set a new model everytime the arraylist of customers changed.
mh okay, now i really have problems explaining what my problem is but, basically i thought this class "customers" was redundant, so i just added the arraylist and stuff to my "normal" "Customer" class:
package v1a;
import java.sql.ResultSet;
import java.util.ArrayList;
public class Customer {
public static final String KUNDENNUMMER = "Kundennummer";
public static final String ANREDE = "Anrede";
public static final String NACHNAME = "Nachname";
public static final String VORNAME = "Vorname";
public static final String PLZ = "PLZ";
public static final String ORT = "Ort";
public static final String STRASSE = "Strasse";
public static final String LAND = "Land";
public static final String TELEFON = "Telefon";
public static final String MOBIL = "Mobil";
public static final String EMAIL = "Email";
public static final String[] CUSTOMER_FIELDS = { KUNDENNUMMER, ANREDE, NACHNAME, VORNAME, PLZ, ORT, STRASSE, LAND, TELEFON, MOBIL, EMAIL };
private String kn, anrede, nachname, vorname, plz, ort, strasse, land, telefon, mobil = "", email = "";
private ArrayList<Customer> customers = new ArrayList<Customer>();
private ArrayList<ICustomerModelListener> listeners = new ArrayList<ICustomerModelListener>();
public Customer() {
getAllFromDatabase();
}
public Customer(String[] str) {
this.kn = str[0];
this.anrede = str[1];
this.nachname = str[2];
this.vorname = str[3];
this.plz = str[4];
this.ort = str[5];
this.strasse = str[6];
this.land = str[7];
this.telefon = str[8];
this.mobil = str[9];
this.email = str[10];
}
public void getAllFromDatabase(){
SQL.getInstance();
ArrayList<Customer> arrlist = new ArrayList<Customer>();
ResultSet rs = SQL.select("SELECT kundennummer, anrede, name, vorname, strasse, plz, ort, land, telefon, mobil, email FROM kunden");
try {
while(rs.next()){
String[] values = new String[Customer.CUSTOMER_FIELDS.length];
values[0] = String.valueOf(rs.getInt("kundennummer"));
values[1] = rs.getString("anrede");
values[2] = rs.getString("name");
values[3] = rs.getString("vorname");
values[4] = rs.getString("strasse");
values[5] = String.valueOf(rs.getInt("plz"));
values[6] = rs.getString("ort");
values[7] = rs.getString("land");
values[8] = rs.getString("telefon");
values[9] = rs.getString("mobil");
values[10] = rs.getString("email");
Customer c = new Customer(values);
arrlist.add(c);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
SQL.cleanup();
this.customers = arrlist;
for(ICustomerModelListener l : listeners){
l.CustomerChanged();
}
}
public ArrayList<Customer> getAll(){
return customers;
}
public void addCustomer(Customer customer){
customers.add(customer);
for(ICustomerModelListener l : listeners){
l.CustomerChanged();
}
}
public void addListener(ICustomerModelListener listener){
listeners.add(listener);
}
public static boolean knExists(int kn){
boolean bool = false;
SQL.getInstance();
ResultSet rs = SQL.select("SELECT kundennummer FROM kunden WHERE kundennummer = "+kn);
try {
while(rs.next()){
bool = true;
}
} catch (Exception e){
System.out.println(e.getMessage());
}
SQL.cleanup();
return bool;
}
public static int getFreeKn(){
SQL.getInstance();
ResultSet rs = SQL.select("SELECT kundennummer FROM kunden ORDER BY kundennummer DESC LIMIT 1");
int kn = 0;
try {
while(rs.next()){
kn = rs.getInt("kundennummer");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
kn++;
SQL.cleanup();
return kn;
}
public static Customer getByKn(int kn){
if(knExists(kn)){
SQL.getInstance();
ResultSet rs = SQL.select("SELECT * FROM kunden WHERE kundennummer = "+kn);
String[] values = new String[CUSTOMER_FIELDS.length];
try {
while(rs.next()){
values[0] = String.valueOf(rs.getInt("kundennummer"));
values[1] = rs.getString("anrede");
values[2] = rs.getString("name");
values[3] = rs.getString("vorname");
values[4] = String.valueOf(rs.getInt("plz"));
values[5] = rs.getString("ort");
values[6] = rs.getString("strasse");
values[7] = rs.getString("land");
values[8] = rs.getString("telefon");
values[9] = rs.getString("mobil");
values[10] = rs.getString("email");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
Customer customer = new Customer(values);
SQL.cleanup();
return customer;
} else {
return null;
}
}
public boolean save() {
SQL.getInstance();
boolean bool = SQL.saveUser(this.kn, this.anrede, this.nachname, this.vorname, this.plz, this.ort, this.strasse, this.land, this.telefon, this.mobil, this.email);
SQL.cleanup();
return bool;
}
public String getValue(String s){
switch (s){
case KUNDENNUMMER:
return this.kn;
case ANREDE:
return this.anrede;
case NACHNAME:
return this.nachname;
case VORNAME:
return this.vorname;
case PLZ:
return this.plz;
case ORT:
return this.ort;
case STRASSE:
return this.strasse;
case LAND:
return this.land;
case TELEFON:
return this.telefon;
case MOBIL:
return this.mobil;
case EMAIL:
return this.email;
default :
return "";
}
}
}
NOW to my question:
is this the right way of modelling such a class regarding mvc pattern?
maybe my first approach was "cleaner" because i had something like a "container" which had all customers in it and the "real" customer class.
The current approach would drive me mad. You have a Customer class with 2 completely distinct behaviors:
When using the default constructor, you are actually storing the contents of the whole database in memory (well, at least of the customer table). So in this case a Customer instance actually represents the whole list of customers
When using the constructor with parameters, a Customer object now represents one Customer
In short, whenever you encounter a Customer instance in your code, you know absolutely nothing.
Further, storing the whole database in memory might be a bit overkill (although probably doable for a limited amount of customers). However, if you will be using this approach for more tables, you will quickly run out-of-memory. Consider only retrieving the data you actually need (for example in a JTable only a certain numbers of customers are visible at the same time, so no need to fetch them all).
And then their is the problem of mixing the business logic with the database logic. I would suggest to clearly separate your Customer class from the actual database access. You never know you will switch databases in the future (or opt for something different then a database). You do not want to rewrite your whole application at that point, just the data-access layer
No, Customer should have no database code in it and should not have an ArrayList<Customer> as these should be handled by other classes. It needs to be pure and needs to simply encapsulate the essence of a Customer, and that's it.
You need to refactor and subdivide some more.

How to change the value of a 'public static string

Here is my code:
public static String currentStudent = "";
public void login() {
boolean studentLoggedOn = false;
Student student = new Student();
PC_Dialog dialog = new PC_Dialog("Enter Login Information", "Student ID, Password-", "OK");
dialog.choice();
String studentID = dialog.getField(1);
String password = dialog.getField(2);
student = (Student) projectSystem.studentFile.retrieve(studentID);
if (studentID != null) {
if (password.equals(student.password)) {
currentStudent = studentID;
studentLoggedOn = true;
studentRun();
}
}
if (!studentLoggedOn) {
JOptionPane.showMessageDialog(null, "Either the user name or the password were incorrect");
login();
}
}
After all of that, the "currentStudent = studentID;" doesn't seem to have any effect on the currentStudent String?
Your question is incomplete, but if I had to guess, I'd say you have a reference to currentStudent somewhere else in your code. Since strings are not mutable and the assignment operator also does not mutate objects, this reference would not change.
For example:
String one = "some string";
String two = one;
one = "another";
System.out.println(one);
System.out.println(two);
Will output
another
some string
Try reading up on Java references and string assignment.
Per the question author's request here's an example that accomplishes what I think he wants.
public class Session {
private String currentUserId = null;
public void setCurrentUserId( String id ) {
currentUserId = id;
}
public String getCurrentUserId() {
return currentUserId;
}
// Other session related information
//...
}
And use the Session class as follows.
public class MyApp {
private Session currentSession;
public MyApp() {
currentSession = new Session();
}
public void login() {
//...
if ( studentID != null ) {
if ( password.equals(student.password) ) {
currentSession.setCurrentUserId(studentID);
//...
}
}
//...
}
public void someOtherMethod() {
System.out.println(currentSession.getCurrentUserId());
}
}
Either currentStudent = studentID does not get executed, or StudentID is something you are not expecting (empty string?). Either fire up a debugger or just insert a print statement(s) to see what happens:
if (studentID != null) {
if (password.equals(student.password)) {
currentStudent = studentID;
System.out.println ("StudentID is " + studentID);
System.out.println ("CurrentID is " + currentStudent); // being paranoid here :-))
studentLoggedOn = true;
studentRun();
}
}
If you verify this shows as you'd expected, you can dig further
According to this site (question and answer on #20):
http://www.javacertifications.net/javacert/scjp1.5Mock.jsp
you cannot change the value of as static String variable within a local method because of its immutable property.
Java 1.5

Categories

Resources