Tengo un pequeño problema: Quería probar la serialización en android (usando eclipse) y encontré un ejemplo de cómo hacerlo. Sé que necesito implementar "Serializable" en la clase que quiero serializar, ya lo hice y siempre recibo una excepción java.io.NotSerializableException. Aquí está el código:java.io.NotSerializableException incluso si implemento "Serializable"
public void Button(View view) throws IOException, ClassNotFoundException {
ser test = new ser();
test.x = 204;
test.y = 2843;
test.speed = 12;
test.direction = 1343;
test.a = 493;
test.b = 2323;
test.c = 29489;
test.d = 394;
byte[] arr = serialize(test);
ser res = (ser) deserialize(arr);
}
public static byte[] serialize(Object o) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(o); //This is where the Exception occurs
out.close();
// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
return buf;
} catch(IOException ioe) {
Log.e("serializeObject", "error", ioe); //"ioe" says java.io.NotSerializableException exception
return null;
}
}
public static Object deserialize(byte[] b) {
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
Object object = in.readObject();
in.close();
return object;
} catch(ClassNotFoundException cnfe) {
Log.e("deserializeObject", "class not found error", cnfe);
return null;
} catch(IOException ioe) {
Log.e("deserializeObject", "io error", ioe);
return null;
}
}
class ser implements Serializable {
float x, y, speed, direction, a, b, c, d;
}
espero que me puedan ayudar, no sé lo que hice mal ...
Editar: mis importaciones son:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
Mire en Android Parcelables, es probablemente lo que realmente quiere usar. – blindstuff
como respondido/comentado a continuación, al llamar 'Button (null)' funciona como se esperaba: sin excepción y obteniendo los valores correctos en 'res'. Debe ser el medio ambiente ... –
¿Cómo lo estás probando? ¿Utiliza el amulador? ¿Se despliega en un dispositivo real? ¿Qué versión de emulador/Android estás usando? Existen diferencias entre las diferentes encarnaciones de Android (como Cyanogen vs Stock Android, etc.). –