简体   繁体   中英

How can I store an arraylist of custom objects?

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

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();

You're in luck, all of your class' members are already serialzble so your first step is to say that Lecture is Serializable.

public class Lecture implements Serializable {

    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;
    }

Next, you need to make a default constructor since serialization seems to require that. The last thing is you need to write your object out to a file. I usually use something like the following. Note this is for saving a game state so you might not want to use the cache directory.

private void saveState() {
    final File cache_dir = this.getCacheDir(); 
    final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);

    FileOutputStream   fos  = null;
    ObjectOutputStream oos  = null;
    boolean            keep = true;

    try {
        fos = new FileOutputStream(suspend_f);
        oos = new ObjectOutputStream(fos);

        oos.writeObject(this.gameState);
    }
    catch (Exception e) {
        keep = false;
        Log.e("MyAppName", "failed to suspend", e);
    }
    finally {
        try {
            if (oos != null)   oos.close();
            if (fos != null)   fos.close();
            if (keep == false) suspend_f.delete();
        }
        catch (Exception e) { /* do nothing */ }
    }
}

Reading the data back is pretty symmetric to the write so I have left that out for this answer. Also, there are still a lot of caveats to Serialized objects so I suggest you do some Google searches and read up on Java serialization in general.

You can use:

System.Runtime.Serialization

You can see an example here: Serialization in C#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM