This discussion is archived
7 Replies Latest reply: Jul 5, 2010 5:40 PM by 843790 RSS

Serialization problem

843790 Newbie
Currently Being Moderated
Hello all!

I need someone to look at a couple of classes and see just where the train wrecks. I'm trying to keep track of users in arraylist contained in a UserList object. Each user has a file that gets created when the user object is first constructed. If it doesn't yet exist, the file is made, and the user is given default values. If file exists already ,it's supposed to just be given updated values (not seen in these 2 classes). I've included a 'test' of how it's supposed to work. When compiled and run, the objects work when the user file doesn't exist yet, but they don't seem to work correctly when the user file does exist already. I've poured over this bit for over 2 weeks, and must concede that I need help with the logic. Any help would be greatly appreciated. Here is the user class. The UserList class I'll post next.

User class: objects saved in the UserList class
import java.io.*;
import java.util.*;
import javax.swing.*;

public class User implements Serializable{
     
//VARIABLES
     private String userName;                               
     private ArrayList<Boolean> lessonsAvailable = new ArrayList<Boolean>(12); 
     private ArrayList<Integer> lessonScores = new ArrayList<Integer>(12);          
     private ArrayList<Boolean> lessonCompletes = new ArrayList<Boolean>(12);     
     private ArrayList<String> settings = new ArrayList<String>();          
     
//CONSTRUCTOR: 
     public User(String name){
          setUserName(name);
          //setupNewUser();
          /*try{
               saveUser();
          }catch(IOException ex){
               ex.printStackTrace();
          }*/
     }

//GETTERS AND SETTERS
     //STRING USERNAME GETTERS AND SETTERS
     public void setUserName(String name){
          userName = name;
     }
     public String getUserName(){
          return userName;
     }

//LESSONSAVAILABLE GETTERS AND SETTERS (OVERLOADED FOR CASES WHERE ONE OBJECT OR ENTIRE ARRAYLIST ARE REQUESTED)
     public void setLessonsAvailable(Boolean buttonEnabled){ 
          lessonsAvailable.add(buttonEnabled);
     }
     public void setLessonsAvailable(int i, Boolean buttonEnabled){
          lessonsAvailable.set(i, buttonEnabled);
     }
     public void setAllLessonsAvailable(ArrayList<Boolean> enabled){
          lessonsAvailable = enabled;
     }
     
     public Boolean getLessonsAvailable(int i){ //FOR WHEN ONE SINGLE ENTRY IS NEEDED
          return lessonsAvailable.get(i);
     }
     public ArrayList<Boolean> getAllLessonsAvailable(){ //FOR WHEN ENTIRE ARRAYLIST IS NEEDED
          return lessonsAvailable;
     }

//LESSONCOMPLETES GETTERS AND SETTERS (OVERLOADED LIKE LESSONSAVAILABLE GETTERS AND SETTERS)
     public void setLessonCompletes(int i, Boolean status){
          lessonCompletes.add(i, status);
     }
     public void setLessonCompletes(ArrayList<Boolean> completed){
          lessonCompletes = completed;
     }
     
     public Boolean getLessonCompletes(int i){ //FOR RETURN OF SINGLE ARRAYLIST ENTRY
          return lessonCompletes.get(i);
     }
     public ArrayList<Boolean> getLessonCompletes(){ //FOR RETURN OF ENTIRE ARRAYLIST
          return lessonCompletes;
     }     

//LESSONSCORES GETTERS AND SETTERS
     public void setLessonScores(int i, int score){  
          lessonScores.add(i, score);
     }
     public void setLessonScores(ArrayList<Integer> scoring){
          lessonScores = scoring;
     }
     
     public int getLessonScores(int i){
          return lessonScores.get(i);
     }
     public ArrayList<Integer> getLessonScores(){
          return lessonScores;
     }

//SETTINGS GETTERS AND SETTERS
     public void setSettings(int i, String setting){
          settings.add(i, setting);
     }
     public void setSettings(ArrayList<String> allSettings){
          settings = allSettings;
     }
     
     public String getSettings(int i){
          return settings.get(i);
     }
     public ArrayList<String> getSettings(){
          return settings;
     }

//SETUPNEWUSER:     
     public void setupNewUser(){
          for(int i = 0; i < 12; i++){
               //System.out.println("initializing" + this.getUserName() + " lesson setup...");
               if(i < 3){
                    lessonsAvailable.add(i, true);
                    //System.out.println("Lesson " + i + " is available!");
               }else{
                    lessonsAvailable.add(i,false);
                    //System.out.println("Lesson " + i + " is NOT available!");
               }
          }
          
          //CODE FOR POPULATING LESSONSCORES
          int j = 0;
          while(j < 13){
               lessonScores.add(j);
               j++;
          }

          //CODE FOR POPULATING LESSONCOMPLETES
          int k = 0;
          while(k < 13){
               lessonCompletes.add(false);
               k++;
          }
          //CODE FOR POPULATING SETTINGS
          
          //NOW SAVE USER'S INFO
          
     }

//SAVEUSER:     
     public void saveUser() throws IOException{
          //THIS METHOD WILL SAVE THE USER'S INFORMATION OVER THE FILE MADE BEFORE USING STRING USERNAME AS 
          //THE NAME OF THE NEW FILE
          try{
               File file = new File("C:/Users/Tristan/Documents/Java/Apps/Metacogs/Users/" + this.getUserName() + ".ser");
               if(file.exists() == false){
                    System.out.println(this.getUserName() + " is a new User! Setting up new User...");
                    file.createNewFile();
                    this.setupNewUser();
                    this.saveUser();
               }else{
                    System.out.println(this.getUserName() + " is already a user. Saving...");
                    FileOutputStream fileStream = new FileOutputStream(file);
                    ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);
                    objectStream.writeObject(this);
                    objectStream.close();
               }
          }catch(IOException ex){
               System.out.println("saveUser() Method did not work correctly");
               ex.printStackTrace();
          }     
     }

//LOADUSER:
     public void loadUser(String name) throws IOException, ClassNotFoundException{
          try{
               //BY THE TIME WE GET TO LOADING A USER, WE SHOULD HAVE AT LEAST ONE CREATED FROM LOGINSCREEN OBJECT
               //ALREADY, SO NO NEED TO CHECK TO SEE IF FILE EXISTS
               File file = new File("C:/Users/Tristan/Documents/Java/Apps/Metacogs/Users/"+ name + ".ser");
               FileInputStream fileIn = new FileInputStream(file);
               ObjectInputStream objectIn = new ObjectInputStream(fileIn);

               //CONVERT SERIALIZED USER FILE BACK TO ACCESSIBLE USER FILE
               User readInUser = (User) objectIn.readObject();
               //SET THE PARAMETERS FOR THIS USER PROFILE
               //HERE, WE'LL CALL THE LESSONTAB CLASS TO ENABLE ONLY THE AVAILABLE LESSONS
               setAllLessonsAvailable(readInUser.getAllLessonsAvailable());
               //HERE, WE'LL CALL THE MASTERY CLASS TO SET LESSON SCORES, AND THEREFOR PROGRESS OF USER
               setLessonScores(readInUser.getLessonScores());
               //THIS WILL ALSO CALL MASTERY TO STORE AND USE LESSONCOMPLETES
               setLessonCompletes(readInUser.getLessonCompletes());
               setSettings(readInUser.getSettings());
                    
          }catch(IOException ex){
               System.out.println("loadUser() method unable to load file");
               ex.printStackTrace();
          }catch(ClassNotFoundException ex){
               System.out.println("in loadUser(): CLASS NOT FOUND");
               ex.printStackTrace();
          }
     }
}
//TODO: 1)write code to populate the settings arraylist<String> 
  • 1. Re: Serialization problem
    843790 Newbie
    Currently Being Moderated
    Here is the second class: UserList
    import java.util.*;
    import java.io.*;
    
    public class UserList implements Serializable{
         Vector<User> list = new Vector<User>();
         UserList ul;     
    //CONSTRUCTOR:
         public UserList(){
              File userListFile = new File("C:/Users/Tristan/Documents/Java/Apps/Metacogs/Users/UserList.ser");
              if(userListFile.exists() == false){
                   try{
                        userListFile.createNewFile();
                   }catch(IOException ex){
                        ex.printStackTrace();
                   }
              }
         }
    
    //MAIN: 
         public static void main(String[] args){
              UserList userL = new UserList();
              User charlesC = new User("Charles Chaplan");
              userL.addUser(charlesC);
              try{
                   charlesC.saveUser();
              }catch(IOException ex){
                   ex.printStackTrace();
              }
              try{
                   userL.saveList();
              }catch(IOException ex){
                   ex.printStackTrace();
              }
              System.out.println(userL.getSingleUser(0).getUserName() + " has following lesson status: ");
              System.out.println(userL.getSingleUser(0).getAllLessonsAvailable().size()+ " lessons are set for user");
              for(int i = 0; i < userL.getSingleUser(0).getAllLessonsAvailable().size(); i++){
                   System.out.println("lesson "+i+" is "+ userL.getSingleUser(0).getLessonsAvailable(i));
              }          
              //User loadUser = new User("Charles Chaplan");
         }
    //GETTERS AND SETTERS
         public void addUser(User user){//ADDS A NEW USER TO THE LIST, THEN SAVES USERLIST
              list.add(user);
              /*try{
                   this.saveList();
              }catch(IOException ex){
                   ex.printStackTrace();
              }*/
         }
    
         //THIS ONE IS OVERLOADED TO EITHER REMOVE GIVEN AN INT FOR INDEX OF ENTRY, OR OBJECT REFERENCE
         public void removeUser(int i){
              list.remove(i);
         }
         public void removeUser(User user){
              list.remove(list.indexOf(user));
         }     
         
         public User getSingleUser(int i){
              return (User) list.get(i);
         }
    
         public Vector<User> getEntireList(){
              return list;
         } 
    
    //SAVELIST: WE'LL CALL THIS METHOD TO SAVE OUR PREPARED LIST, AFTER A USERLIST OBJECT HAS HAD USERS ADDED TO IT
         public void saveList() throws IOException {
              try{
                   File saveFile = new File("C:/Users/Tristan/Documents/Java/Apps/MetaCogs/Users/UserList.ser");
                   FileOutputStream fs = new FileOutputStream(saveFile);
                   ObjectOutputStream os = new ObjectOutputStream(fs);
    
                   os.writeObject(this);
                   os.close();
              }catch(IOException ex){
                   System.out.println("Could not save list to file");
                   ex.printStackTrace();
              }
         }
    
    //LOADUSERLIST:
         public UserList loadUserList() throws IOException{
              try{
                   File saveFile = new File("C:/Users/Tristan/Documents/Java/Apps/MetaCogs/Users/UserList.ser");
                   if(saveFile.exists() == false){
                        saveFile.createNewFile();
                   }
                   FileInputStream fis = new FileInputStream(saveFile);
                   ObjectInputStream ois = new ObjectInputStream(fis);
    
                   ul = (UserList) ois.readObject();
              }catch(IOException ex){
                   System.out.println("Could not load list from file");
                   ex.printStackTrace();
              }catch(Exception ex){
                   System.out.println("Could not load for error besides IO");
                   try{     
                        saveList();
                   }catch(IOException ioex){
                        ioex.printStackTrace();
                   }
              }
              return ul;
         }
    }
  • 2. Re: Serialization problem
    EJP Guru
    Currently Being Moderated
    they don't seem to work correctly when the user file does exist
    Define.
  • 3. Re: Serialization problem
    843790 Newbie
    Currently Being Moderated
    The test is the main() method of UserList. When the User's file exists already, all that the for loop (in main() method) shows is the username, but it does not show that setupNewUser() has initialized the first 12 entries of the lessonsAvailable ArrayList (none of them have been added, it's size is zero). However, if the User's file hasn't been created yet, and needs to be, for some reason, when I query the UserL arrayList for the User Objects values, THAT's when the values have been set.
  • 4. Re: Serialization problem
    EJP Guru
    Currently Being Moderated
    You don't need to call createNewFile() when you are about to create a FileOutputStream. And calling it when you are about to create a FileInputStream is bizarre: all you can do is read an empty file. And you have to catch FileNotFoundException anyway. I would reconsider a lot of this code, it is a lot of huffing and puffing to not much real puyrpose. It's far too much to expect anybody to debug here. Cut it down to a short simple self-contained example (SSSCE - Google it).
  • 5. Re: Serialization problem
    843790 Newbie
    Currently Being Moderated
    I see your point about the createNewFile() call. I wondered about if it was necessary, but the reference books I looked at didn't really shed light on that particular. I also re-wrote saveFile, and just elected to call a lot of the class code (saveList, setUserName) at runtime, and it looks like that has worked.

    To be quite honest, though, I don't really come to the forums a lot. The people who usually answer my posts come off as a little condescending. One thing that could be done is to pretend the forums are in a store, and the people who post questions are customers who have shown up in person. Think of what you would (and would not) say in front of someone actually there. I don't think all the blame should rest on the people who reply to forums, though, the anonymity of the internet hasn't required people to hone their etiquette. Still, being respectful and using positive wording will keep people coming back to the forums.
  • 6. Re: Serialization problem
    EJP Guru
    Currently Being Moderated
    Your second paragraph is irrelevant to this thread unless it is addressed specifically to me, in which case please say so. However these forums aren't in the least like a store. Nobody is paying and nobody is getting paid.
  • 7. Re: Serialization problem
    796085 Newbie
    Currently Being Moderated
    Don't make the mistake of thinking that the people who respond on here are Sun/Oracle employees. 99.9% of them are not.