I am trying to pass a collection of custom objects to a service in android.
try {
FileParser parser = new FileParserImpl();
Collection<SensorReading<Long, Float>> collection = parser.parse(fileContents);
Intent intent = new Intent(FileBrowserActivity.this, DataService.class);
intent.putExtra(PARAM_SENSOR_DATA, (Serializable)collection); //exception here.
startService(intent);
catch (Exception e) { //e = null,
Log.e(TAG, "We go an exception", e);
}
I get the exception at line marked in the code and the corresponding catch block gets the value as null. To get the message I do a force step into
at the line where I get exception and it take me to the class ClassCastException
where I see this message in debug mode :
java.util.hashmap$values cannot be cast to java.io.serializable
. I followed the suggestion given here
Also passing the object as intent.putExtra(PARAM_SENSOR_DATA, collection) gives compilation error with message that cannot resolve method
SensorReading
is an interface as shown below:
public interface SensorReading<X, Y> {
String getSensorIdentifier();
List<Pair<X, Y>> getReadings();
void addReading(Pair<X, Y> reading);
}
and SensorReadings is the implementation:
public class SensorReadings implements SensorReading<Long, Float>, Serializable {
private static final long serialVersionUID = -2518143671167959230L;
String location;
String sensorName;
public SensorReadings(String location, String sensorName) {
//constructor
}
List<Pair<Long, Float>> timeStampReadingTuple;
public void addReading(Pair<Long, Float> pair) {
timeStampReadingTuple.add(pair);
}
public List<Pair<Long, Float>> getReadings() {
return timeStampReadingTuple;
}
@Override
public String getSensorIdentifier() {
return sensorName + "@ " + location;
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
location = (String) in.readObject();
sensorName = (String) in.readObject();
int size = (int) in.readObject();
timeStampReadingTuple = Lists.newArrayListWithCapacity(size);
for(int i=0; i<size; ++i) {
long timeStamp = (long) in.readObject();
float reading = (float) in.readObject();
timeStampReadingTuple.add(new Pair<Long, Float>(timeStamp, reading));
}
}
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeObject(location);
out.writeObject(sensorName);
out.writeObject(timeStampReadingTuple.size());
for(Pair<Long, Float> pair : timeStampReadingTuple) {
out.writeObject(pair.first);
out.writeObject(pair.second);
}
}
}