Pregunta

The title may be a little be confusing or even missleading but im trying to save to disk an object that as a property contains a list of objects (ArrayList).

The thing is this object wont be able to do anything without the list.

I have tried serialization of both the object and the list. When i tried serializing the object alone there was nothing in it, the list was empty. When i tried serializing the list i could access the list, change it but at the cost of many thrown exceptions.

public class AdressBook implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 6399534374362987383L;

    static Reader reader = new KeyboardReader();

    static ArrayList<Contact> AdressBook = new ArrayList<Contact>();

    public AdressBook(){

    }

    public static void AddContact(){
        AdressBook.add(new Contact());
    }

    public static void EditContact(){
        System.out.println("Which contact you desire to edit?");
        Libreta.Display();
        System.out.println("Type in the number of the contact.");
        int i = (reader.readint() - 1);

        System.out.println("Choose the change 1.Name 2.Last Name 3.Nickname 4.Phone number 5.Emails");
        int j = reader.readint();

               switch(j){

        case 1: AdressBook.get(i).setName();
                break;

        case 2: AdressBook.get(i).setLastName();
                break;

        case 3: AdressBook.get(i).setNick();
                break;

        case 4: AdressBook.get(i).AddPhoneNumber();
                break;

        case 5: AdressBook.get(i).AddEmail();
                break;

        default : System.out.println("Not a valid option");

        }

I have to be able to edit the list of the object and being able to somehow save it again. I have been trying many ways but im lacking in knowledge or it just doesnt work for me.

¿Fue útil?

Solución

Your address book variable should not be declared static, as static variables are not serialized. Make it an instance (non-static) variable like this:

public class AddressBook implements Serializable {
...
  ArrayList<Contact> contacts = new ArrayList<Contact>();
...
}

Otros consejos

I think your problem is that your ArrayList is a static field (sometimes called a class field) and serialization take place in an object instance not in class.

So you should replace your static field, and static methods too, for instance equivalents.

(Now, just a comment: you should try using java naming conventions - using lower initials for field and method names - it much easy for java coders understand you... ;-)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top