0

I'm writing a pretty simple program GUI program that emulates a cell phone. The "cell phone" has four main buttons: phone, contacts, message, and apps. I've coded all the GUI and hit a snag while working on the Contact class, which is the backbone of the entire program!

The Contact class is very straightforward, it has two instance variables of type String which are 'name' and 'number'. I want to build an ArrayList of type Contact, allow for contacts to be added, and then create methods to append to and read in from a serialized file.

At this point I'm very stuck on how to create methods to add objects to the arrayList, and then create methods to append to and read in from a serialized file.

Here is the Contact class:

public class Contact
{
    public String name, number;

Contact()
{}

Contact (String theName, String theNumber)
{
    this.name = theName;
    this.number = theNumber;
}

public void setName(String aName)
{
    this.name = aName;
}

public void setNumber(String aNumber)
{
    this.number =aNumber;
}

public String getName()
{
    return name;
}

public String getNumber()
{
    return number;
}

public String toString()
{
    return name + ": " + number;
}

public boolean equals(Contact other)
{
   if (name.equals(other.getName())  && number.equals(other.getNumber()))
   {
      return( true );
   }
   else
   {
      return( false );
   }
}
}

Thanks for the quick responses. I've corrected the equals method and moved the ArrayList to it's own class. I also cleared up the error on the read method (Java 7 issue). The current issue I'm running into is on these lines:

out.writeObject(contact);

and

Contact contact = (Contact)in.readObject();

Since I'm trying to write to and read from an ArrayList, shouldn't the methods reflect that?

import java.util.*;
import java.io.*;

class ContactsCollection implements Serializable
{
    public static final long serialVersionUID = 42L;

ArrayList <Contact> contactList = new ArrayList<Contact>();

public void write()
{
    try 
    {
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("contactList.dat"));
        out.writeObject(contact);
    } 
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

public void read()
{
    try
    {
         ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
         Contact contact = (Contact)in.readObject();
    } 
    catch (IOException e)
    {
        e.printStackTrace();
    }
    catch (ClassNotFoundException e)
    {
        e.printStackTrace();
    }
}
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
user2380220
  • 29
  • 3
  • 8
  • 1
    `name` and `number` shouldn't be `static` variables of `Contact` (unless all of your contacts share the same name and number). – jlordo May 14 '13 at 05:57
  • Also, your `equals()` implementation will cause some trouble. Read this: [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jlordo May 14 '13 at 06:01

3 Answers3

2

Appending to the list is as easy as list.add(contact).

Writing to serialization:

try {
    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(file));
    out.writeObject(contact);
} catch(IOException e) {
    e.printStackTrace();
}

Reading:

try {
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    Contact contact = (Contact)in.readObject();
} catch(IOException | ClassNotFoundException e ) {
    e.printStackTrace();
}
Mordechai
  • 15,437
  • 2
  • 41
  • 82
0

I am afraid that I really understand what you are trying to achieve but I can see two problems in your code:

  1. You have created your Contact class with static attributes, which means all the objects will share the same value of name & number. It seems to be problematic and i will advice you to create non-static attributes when there seems to be no need to share them.

public static String name, number;

Second problem in your class is that you have put the arraylist of contacts also in it. And you have made the class seriablizable. It means everytime you serialize your contact object, your arraylist will also be serialized along with it, which i assume is not desired. You should create another class and name it such as ContactsCollection and simply create a Arraylist in it, you may chose to have a static arraylist here.

In your GUI, if you are creating and object, then create an instance of Contact. And then simply add it your ContactsCollection.contactList(). You may add methods to serialize also in your ContactsColleciton class. You may chose to have a single method in ContactsCollection with argument as Contact object. First you add the object in the list and then serialize it.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
  • Thank you for the quick response. I've moved the ArrayList to it's own class: – user2380220 May 14 '13 at 06:17
  • Does it help you to achieve the desired result? – Juned Ahsan May 14 '13 at 06:24
  • I've updated my original post with some information about errors on the read method's catch block. If I recall correctly, I think there needs to be a declaration in the method such as public void read () throws ___ Exception. Once I can get that to compile my last hurdle will be starting out the file (so that each time the program runs the GUI will read in and display the contacts). – user2380220 May 14 '13 at 06:31
  • Are you using Java 7 because catching multiple exceptions is a feature of Java 7 only. If you are using previous Java version then you need to put separate catch block for both the exceptions. – Juned Ahsan May 14 '13 at 06:34
  • I accepted the answer but I do not have enough reputation to upvote. Could you take a look at the edits I made to the original post? I want to make sure that the read and write methods are written correctly for array lists. Once I can get those figured out I think I will be able to add it all to my GUI! – user2380220 May 14 '13 at 06:49
  • Still there is a problem. You want to serialize your Contact objects so you need to make that class serializable instead of ContacsCollection. Serializable means that the object can be written to a stream. Hope it helps! – Juned Ahsan May 14 '13 at 06:59
0

It would be too long to post as a comment, hence I post this as an answer.Apart from the already answered points, I want to add a few of my observations here.

There are certain mistakes(if they are unintended) in your code:

You are declaring name and number both as static. What it does is that all the instances of your class Contact will share the same name and number. I presume all the contacts having same name and number is something very unheard and unintended.

public static String name, number;

So correct it to

public String name, number;

Though it's more of a warning, but you should provide a serialVersionUID to your Serializable class . The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded.

public static final long serialVersionUID = 42L;

Your definition of equals() will create issues.You are using == to check the equality of two String which in turn will only check for equal references. Better approach would be to use the overridden equals() of String which compares the contents.

if (name.equals(other.getName())  && number.equals(other.getNumber()))
{
    return true;
}
else
{
   return false;
}

Once you override the equals() for the Contact class, override its hashCode() as well.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • I haven't learned about that or hashCode yet. I've added the serialVersionUID line in the ContactsCollection class, please let me if you see any issues with it. – user2380220 May 14 '13 at 06:35