As I understand things, in order to save an ArrayList of objects to a file using ObjectOutputStream, the Objects in the ArrayList need to implement Serializable.
I'm trying to save an ArrayList of Locations to a file, so I extend Location into a class that does that (and nothing else). So I have a class that looks like...
import java.io.Serializable;
import android.location.Location;
public class MyLocation extends Location implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7599200646859829149L;
public MyLocation(Location l) {
super(l);
}
}
But now, in my location listener it crashes at
public void onLocationChanged(Location loc) {
locat = (MyLocation)loc;
I suppose it doesn't like the typecasting? I dunno, I'm a little confused. Sorry if this is obvious, I haven't been doing this long.
The serialVersionUID line was generated by Eclipse using "add generated serial version ID"
Update:
Like I said before, I'm trying to read/write an arraylist of Locations to/from a file. When I write my data to a file, I don't get any exceptions, but I do get an exception when I try to read it. Basically I have a class that extends ArrayList (because I needed it to be parseable for Listview purposes...
public class开发者_如何学运维 LocationList extends ArrayList<MyLocation> implements Parcelable {
private static final long serialVersionUID = 1L;
it's a LocationList named waypoints that I write to a file. This seems to work fine (ie it doesn't throw an exception or crash)...
FileOutputStream fos;
try {
fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os;
os = new ObjectOutputStream(fos);
os.writeObject(waypoints); // <-- writeObject doesn't throw an exception.
os.close();
but when I try to read that file, I get an IO exception...
FileInputStream fis;
try {
fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
is.readObject(); // <--this is the line that throws an IO exception
is.close();
This is probably a naive attempt at saving/loading a moderately complicated object. Any advice?
NOTE: I simplified it a bit. Originally the offending line was
waypoints = (LocationList) is.readObject();
but I was worried that I had a similar problem with the casting as above so i took it out temporarily. Anyway, readObject() throws an exception without the typecast there, so I guess that's not my current problem.
Is the location object that is passed to you a MyLocation instance? My guess would be no, since the system is providing it. Just because you extend a class doesn't mean you can cast from the super type. What you really want to do is:
locat = new MyLocation(loc);
精彩评论