Tôi có một vấn đề nhỏ: Tôi muốn thử nghiệm serialization trên android (sử dụng nhật thực) và tìm thấy một ví dụ làm thế nào để làm điều đó. Tôi biết tôi cần phải thực hiện "Serializable" trong lớp tôi muốn serialize, tôi đã làm điều đó và luôn luôn nhận được một ngoại lệ java.io.NotSerializableException. Dưới đây là các mã:java.io.NotSerializableException ngay cả khi tôi thực hiện "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;
}
Tôi hy vọng bạn có thể giúp tôi, tôi không biết những gì tôi đã làm sai ...
Edit: nhập khẩu của tôi là:
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;
Nhìn vào các kiện hàng của Android, đó có thể là những gì bạn thực sự muốn sử dụng. – blindstuff
như đã trả lời/nhận xét dưới đây, gọi 'Button (null)' đang hoạt động như mong đợi: không có Ngoại lệ và nhận giá trị đúng trong 'res'. Phải là môi trường ... –
Bạn thử nghiệm điều này như thế nào? Bạn có sử dụng bộ mô phỏng, bạn có triển khai thiết bị thực tế không? Bạn đang sử dụng phiên bản trình mô phỏng/Android nào? Có sự khác biệt giữa các hóa thân Android khác nhau (như Cyanogen vs Stock Android vv). –