I have created an arraylist that is made up of custom objects. Basically the user will create a class and every time a class is created, a new Lecture (my custom object) is added to the arraylist. I need to save the generated arraylist so the user's classes will be saved even when the app is restarted.
From my understanding, I have to make my class serializable. But how exactly do I do that? And then once its serialized what do I do?
public class Lecture{
public String title;
public String startTime;
public String endTime;
public String day;
public boolean classEnabled;
public Lecture(String title, String startTime, String endTime, String day, boolean enable){
this.title = title;
this.startTime = startTime;
this.endTime = endTime;
this.day = day;
this.classEnabled = enable;
}
//Getters and setters below
To add an object to the ArrayList, we call the add() method on the ArrayList, passing a pointer to the object we want to store. This code adds pointers to three String objects to the ArrayList... list. add( "Easy" ); // Add three strings to the ArrayList list.
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types.
ArrayList cannot hold primitive data types such as int, double, char, and long. With the introduction to wrapped class in java that was created to hold primitive data values.
I use a class in a Weather app I'm developing...
public class RegionList extends ArrayList<Region> {} // Region implements Serializeable
To save I use code like this...
FileOutputStream outStream = new FileOutputStream(Weather.WeatherDir + "/RegionList.dat");
ObjectOutputStream objectOutStream = new ObjectOutputStream(outStream);
objectOutStream.writeInt(uk_weather_regions.size()); // Save size first
for(Region r:uk_weather_regions)
objectOutStream.writeObject(r);
objectOutStream.close();
NOTE: Before I write the Region objects, I write an int to save the 'size' of the list.
When I read back I do this...
FileInputStream inStream = new FileInputStream(f);
ObjectInputStream objectInStream = new ObjectInputStream(inStream);
int count = objectInStream.readInt(); // Get the number of regions
RegionList rl = new RegionList();
for (int c=0; c < count; c++)
rl.add((Region) objectInStream.readObject());
objectInStream.close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With