Verhelst
Verhelst

Reputation: 1503

Solve NotSerializableException

I'm fairly new to Java, and I cannot seem to solve this NotSerializableException that I receive. I'm writing an object to the sdcard of the user and next I need to read it back.

This is my code:

@Override
protected void createAndAttachView(int id, FrameLayout frame) {

    //Read the panel from the memory
    PanelWrapper pnl = (PanelWrapper) readObjectFromMemory(B4AHelper.getDirDefaultExternal(), "layout.frame");

    //Add the view
    frame.addView(pnl.getObject());

    //Broadcast an intent to the user.
    intent = new IntentWrapper();
    intent.Initialize("createAndAttachView", "");
    intent.PutExtra("id", id);
    intent.PutExtra("message", "View Attached");
    sendBroadcast(intent.getObject());

    //Log - debugging
    Log.i("B4A", "View attached!");
}

I'm using readObjectFromMemory and writeObjectFromMemory from here and this is the error:

Error Message: anywheresoftware.b4a.BALayout


Error Message: Read an exception; java.io.NotSerializableException: anywheresoftware.b4a.BALayout

Caused by: java.lang.NullPointerException
    at com.rootsoft.standout.MostBasicWindow.createAndAttachView(MostBasicWindow.java:53)
    at com.rootsoft.standout.StandOutWindow$Window.<init>(StandOutWindow.java:2213)
    at com.rootsoft.standout.StandOutWindow.show(StandOutWindow.java:1416)
    at com.rootsoft.standout.StandOutWindow.onStartCommand(StandOutWindow.java:716)
    at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
    ... 10 more

I'd like if is it possible to explain as good as possible as I'm fairly new and this might help other people too.

Upvotes: 0

Views: 1285

Answers (1)

Adam Monos
Adam Monos

Reputation: 4297

Here you can read about serialization in java in common.

http://java.sun.com/developer/technicalArticles/Programming/serialization/

In a nutshell, a serializable object has a static long field named serialVersionUID generated from the member fields and methods of the class. It is used to check if class's definitions match.

For example you have a Serializeable object, you write it into a file as byte[] and you want to read it back later. If in the meantime you changed some fields or methods in your class (eg. the class definition in the file, and the class definition currently in use aren't the same anymore), than java can discover these differences from the invalid UID and it will know, that although they might be the same type, they are not compatible.

Ofcourse you can assign a default UID as well, or you can leave it blank if you know that such a scenario won't happen for sure.

As for getting rid of your exception, you just have to implement the Serializable interface in your class in question (in your case anywheresoftware.b4a.BALayout).

Upvotes: 2

Related Questions