gpt4 book ai didi

java.util.hashmap$values 无法在 android putExtra 方法中转换为 java.io.serialized

转载 作者:行者123 更新时间:2023-12-01 11:04:13 25 4
gpt4 key购买 nike

我正在尝试将自定义对象的集合传递给 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 block 获取值为 null。为了获取该消息,我在出现异常的行执行了强制单步执行,它会将我带到类ClassCastException,我在 Debug模式下看到此消息:java.util.hashmap$values 无法转换为 java.io.serialized。我遵循了here给出的建议

还将对象作为intent.putExtra(PARAM_SENSOR_DATA, collection)传递会给出编译错误,并显示消息无法解析方法

SensorReading是一个如下所示的接口(interface):

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

最佳答案

我认为问题在于......

抛出 ClassCastException 表示代码试图将一个对象转换为它不是实例的子类。您正在尝试将 Collection 强制转换为可序列化,但 Collection 本身并未实现可序列化。

如果 DataService(您想要通过 Intent 启动的服务)是一个内部类,您可能希望将集合存储在父类的临时属性中,并在服务中使用检索它,例如

 ParentClass.this.collection

关于java.util.hashmap$values 无法在 android putExtra 方法中转换为 java.io.serialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33109825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com