Tuesday 2 September 2014

Java Serializer

In Computer Science, serialisation is a process of translating data structures or objects into a byte stream that can be stored (in a file or memory buffer), or can be transmitted across a network link, and the byte stream can be re-read and re-constructed into the same clone.  Serialisation is a way to prevent the byte ordering (endianness), memory layout problem.

In Java, the java.io.serializable implement the serialisation. You can write a Java class to implement the Serializable interface.

class IsSerializable implements Serializable  
{  
    private String plug = "Plugin to Java!";  
    public IsSerializable()  
    {  
        try  
        {  
            FileOutputStream out = new FileOutputStream("/mnt/sdcard/yes-out.txt");  
            ObjectOutputStream oos = new ObjectOutputStream(out);  
            oos.writeObject(this);  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }  
    }  

}  

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        IsSerializable is = new IsSerializable();  
        ...
}

If you run this code, there is an error message:

java.io.NotSerializableException: com.example.xxxxx.MainActivity.

The reason is that you can't get the whole class to be serialised.

Solution:
If we replace oos.writeObject(this); with oos.writeObject(plug);  the problem is fixed.

No comments:

Post a Comment