I have a little problem: I wanted to test serialization on android (using eclipse) and found an example how to do it. I know I need to implement "Serializable" in the class I want to serialize, I already did that and always get a java.io.NotSerializableException exception. Here's the code:
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;
}
I hope you can help me, I don't know what I did wrong...
Edit: my imports are:
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;
Well, does your serializable object have any refferences to other non-serializable objects? If so the java.io.NotSerializableException
will be thrown because of that. In order to be able to serialize you must have your class implemnent Serializable
AND all dependencies it has be of type Serializable
(i.e. implement Serializable) as well.
The exception message should tell you if such a non-serializable dependency exist:
It should say something like "java.io.NotSerializableException: NonSerializableClassName"
Update: as per Bozho's comment, I didn't notice that in fact your class does not have any non-serializable dependencies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With