My program is a simple chatroom. the values written from the user by the text field in the registration section and creates an account. I have a class called "Account" that takes the same values in the input and it contains the same fields. All accounts need to be saved and loaded for later implementation. I used the code below (this is part of the program code) but there is a problem. I printed the values after loading and found that it was reporting null values. Then after adding a new account to the array list all the values in the list were changed to the added value. For example, I create and save an account with name "a" and email "a", then run the program again. Adding the account with name and email "B" here prints two accounts B. what is the problem?
String email= t4.getText();
String password=t5.getText();
String name=t1.getText();
String family=t2.getText();
String phoneNumber=t3.getText();
try {
FileInputStream f = new FileInputStream("accounts.txt");
ObjectInputStream obj = new ObjectInputStream(f);
int size=obj.readInt();
for (int i = 0; i <size ; i++) {
accounts.add((Account)obj.readObject());
}
} catch (Exception e){
e.printStackTrace();
}
for (int i = 0; i <accounts.size() ; i++) {
System.out.println(accounts.get(i).name+" "+accounts.get(i).email);
}
Account account = new Account(name,family,phoneNumber,email,password);
accounts.add(account);
try{
FileOutputStream f=new FileOutputStream("accounts.txt",false);
ObjectOutputStream obj=new ObjectOutputStream(f);
obj.writeInt(accounts.size());
for (Account a:accounts) {
obj.writeObject(a);
}
} catch (Exception e){
e.printStackTrace();
}
for (int i = 0; i <accounts.size() ; i++) {
System.out.println(accounts.get(i).name+" "+accounts.get(i).email);
}
//class account
class Account implements Serializable {
static String name, family, phoneNumber, email, password;
static ArrayList<Post> posts = new ArrayList();
static ArrayList<Account> following = new ArrayList();
static ArrayList<Account> follower = new ArrayList();
Account(String n, String f, String pn, String e, String ps) {
name = n;
family = f;
phoneNumber = pn;
email = e;
password = ps;
}
void follow(Account user) {
following.add(user);
user.follower.add(this);
}
void post(String data) {
Post post = new Post(data, new Date(), this);
posts.add(post);
for (Account account : follower) {
account.posts.add(post);
}
}
}
All the members of the Account
class are static
, meaning that they belong to the class instead of a specific instance. Make them non-static and you should be good to go.