problema serializzazione con SortedSet, Array, un Serializable
-
01-10-2019 - |
Domanda
ho questo prima del processo:
protected void onPostExecute(SortedSet<RatedMessage> result) {
List<Object> list=Arrays.asList(result.toArray());
lancon.putExtra("results", list.toArray()); // as serializable
}
poi nell'altra parte ho
Object o=this.getIntent().getSerializableExtra("results");
//at this point the o holds the correct value (checked by debugger)
RatedMessage[] rm = (RatedMessage[]) o;// this line hangs out w ClassCastException
resultSet = new TreeSet<RatedMessage>(new Comp());
Collections.addAll(resultSet, rm);
Perché ho la ClassCastException?
Soluzione
Alla fine ho preso a lavorare in questo modo:
Serializable s = this.getIntent().getSerializableExtra("results");
Object[] o = (Object[]) s;
if (o != null) {
resultSet = new TreeSet<RatedMessage>(new Comp());
for (int i = 0; i < o.length; i++) {
if (o[i] instanceof RatedMessage) {
resultSet.add((RatedMessage) o[i]);
}
}
}
Altri suggerimenti
Mi dispiace; Ho trascurato l'uso della chiamata toArray()
no-arg.
Si prega di notare che c'è sovraccarico metodo toArray(T[])
che accetta una matrice come argomento.
Utilizzando questo modulo, è possibile controllare il tipo di componente della matrice, e funzionerà come previsto.
protected void onPostExecute(SortedSet<RatedMessage> result) {
lancon.putExtra("results", result.toArray(new RatedMessage[result.size()]));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow