我正在尝试将一组自定义对象传递给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);
}
我在代码中标记的行处获得异常,相应的catch块将值取为null。为了得到消息,我在我得到异常的行处force step into
,它带我到类ClassCastException
,我在调试模式中看到此消息:
java.util.hashmap$values cannot be cast to java.io.serializable
。我遵循了给出here
同样将对象作为intent.putExtra(PARAM_SENSOR_DATA,collection)传递给出编译错误,并显示cannot resolve method
SensorReading
是一个界面,如下所示:
public interface SensorReading<X, Y> {
String getSensorIdentifier();
List<Pair<X, Y>> getReadings();
void addReading(Pair<X, Y> reading);
}
和SensorReadings是实现:
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);
}
}
}
答案 0 :(得分:1)
我认为问题在于......
抛出ClassCastException以指示代码已尝试将对象强制转换为不是实例的子类。您正在尝试将Collection转换为Serializable,但Collection本身并未实现Serializable。
DataService(您希望通过Intent启动的服务)是一个内部类,您可能希望将该集合存储在父类的临时属性中,并使用在服务中检索它,如
ParentClass.this.collection