How Can I Store An Arraylist Of Custom Objects?
Solution 1:
I use a class in a Weather app I'm developing...
publicclassRegionListextendsArrayList<Region> {} // Region implements Serializeable
To save I use code like this...
FileOutputStreamoutStream=newFileOutputStream(Weather.WeatherDir + "/RegionList.dat");
ObjectOutputStreamobjectOutStream=newObjectOutputStream(outStream);
objectOutStream.writeInt(uk_weather_regions.size()); // Save size firstfor(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...
FileInputStreaminStream=newFileInputStream(f);
ObjectInputStreamobjectInStream=newObjectInputStream(inStream);
intcount= objectInStream.readInt(); // Get the number of regionsRegionListrl=newRegionList();
for (int c=0; c < count; c++)
rl.add((Region) objectInStream.readObject());
objectInStream.close();
Solution 2:
You're in luck, all of your class' members are already serialzble so your first step is to say that Lecture is Serializable.
publicclassLectureimplementsSerializable {
publicString title;
publicString startTime;
publicString endTime;
publicString day;
publicboolean classEnabled;
publicLecture(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.
privatevoidsaveState() {
finalFilecache_dir=this.getCacheDir();
finalFilesuspend_f=newFile(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);
FileOutputStreamfos=null;
ObjectOutputStreamoos=null;
booleankeep=true;
try {
fos = newFileOutputStream(suspend_f);
oos = newObjectOutputStream(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.
Post a Comment for "How Can I Store An Arraylist Of Custom Objects?"