I'm quite new to java and unsure how to fix this java.io.NotSerializableException
error.
I'm trying to use an add button on the GUI to add an object to an array list Then write that object to a file so I am able to read it back.
Here is the code I'm using for the Branch
class which implement Java Serializable
:
import java.io.Serializable;
public class Branch implements Serializable{
private String branch_name;
private String branch_address;
public Branch(String Bname, String Baddress) {
this.branch_name = Bname;
this.branch_address = Baddress;
public String getbranch_name(){
return branch_name;
}
public String getbranch_address(){
return branch_address;
}
public void show_branch_details() {
System.out.println( " The branch name is : " + getbranch_name()
+ " branch address :"+ getbranch_address()
}
}
}
Here is the code for the add button:
ArrayList<Branch> BranchList = new ArrayList<Branch>();
JButton AddBranch = new JButton("ADD BRANCH");
AddBranch.setBounds(10, 35, 161, 23);
AddBranch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Bname = branchNameField.getText();
String Baddress = branchAddressField.getText();
Branch A = new Branch(Bname, Baddress);
BranchList.add(A);
for (int i = 0; i < BranchList.size(); i++) {
displayInfo.append(BranchList.get(i).getbranch_name() +);
}
System.out.println("The ArrayList has " + BranchList.size());
for (int i = 0; i < BranchList.size(); i++) {
System.out.println(BranchList.get(i).getbranch_name());
}
try {
FileOutputStream fos = new FileOutputStream("branch.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//oos.writeObject(BranchList);
for (int b = 0; b < BranchList.size(); b++) {
oos.writeObject(BranchList.get(b));
}
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream("branch.dat");
ObjectInputStream ois = new ObjectInputStream(fis);
//BranchList = (ArrayList<Branch>)ois.readObject();
Branch obj = null;
while ((obj = (Branch) ois.readObject()) != null) {
System.out.println("Name:" + obj.getbranch_name() + ", Address:"
+ obj.getbranch_address());
}
ois.close();
} catch (IOException ex) {
System.out.println(" IOE ERROR");
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
System.out.println("class ERROR");
ex.printStackTrace();
}
}
});