Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store an arraylist of custom objects?

Tags:

android

sqlite

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
like image 563
b_yng Avatar asked Dec 09 '10 00:12

b_yng


People also ask

How do you store objects in ArrayList?

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.

Can you have an ArrayList of different objects?

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.

Can ArrayLists store primitive 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.


1 Answers

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();
like image 153
Squonk Avatar answered Sep 21 '22 16:09

Squonk