maxib7
maxib7

Reputation: 1960

Failing to write/read file with a list of objects

I'm trying to save a list of objects to a file but whenever I try to read from the file it always fails. Can someone tell me what I'm doing wrong

Writing to it

public void writeToFile(List<EventsClass> list)
{
    String filename = "events.srl";
    ObjectOutput out = null;

    try
    {
        out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
        out.writeObject(list);
        out.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

I checked and the argument list always contains a list of objects

Reading from it

public List<EventsClass> readFromFile()
{
    ObjectInputStream input;
    String filename = "events.srl";

    try
    {
        input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
        List<EventsClass> list = (List<EventsClass>) input.readObject();
        input.close();
        return list;
    }
    catch (IOException | ClassNotFoundException e)
    {
        e.printStackTrace();
        return null;
    }
}

it always fails to read file and returns null

Here's EventsClass

public class EventsClass
{
    private String eventName;
    private String eventClass;
    private String eventDate;
    private int eventMonth;
    private int eventDay;

    public EventsClass(String eventClass, String eventName, String eventDate, int eventMonth, int eventDay)
    {
        this.eventClass = eventClass;
        this.eventName = eventName;
        this.eventDate = eventDate;
        this.eventMonth = eventMonth;
        this.eventDay = eventDay;
    }

    public void putEventData(String mClass, String name, String date, int month, int day)
    {
        this.eventClass = mClass;
        this.eventName = name;
        this.eventDate = date;
        this.eventMonth = month;
        this.eventDay = day;
    }

    public String getEventClass()
    {
        return eventClass;
    }

    public String getEventName()
    {
        return eventName;
    }

    public String getEventDate()
    {
        return eventDate;
    }

    public int getEventMonth()
    {
        return eventMonth;
    }

    public int getEventDay()
    {
        return eventDay;
    }
}

Upvotes: 1

Views: 40

Answers (1)

ahodder
ahodder

Reputation: 11439

Ya, EventsClass needs to be serializable to be written to storage. If you have it implement java.io.Serializable, all should work well for you. Here is a decent tutorial you understand more of what is going on with java serialization.

Upvotes: 2

Related Questions