Android: exception passing an anonymous class as an Intent parameter

An exception:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = MyClass$2)

Code (simplified):

i.putExtra("myparam", generateA(context, "foo"));
...
private A generateA(final Context context, String foo) {
    return new A() {

        @Override
        public void test() {
            System.out.println("test");
        }
    };
}

Interface:

public interface A extends Serializable {

    public void test();

}

What am I doing wrong? What I pass is Serializable.

+3
source share
1 answer

If I understand well, the intention fails because your anonymous class cannot be serialized due to its handler?

Is it possible to implement your handler in the target activity? The bahaviour class should contain only a behavior function with a handler provided by the target action:

private transient Handler h;

//Called by the activity in the onCreate
void setHandler(Handler h){
   this.h = h;
}

//Called by the activity to start the behaviour function
void startBehaviour (){
  //...
  //The activity handler will call startHandlerBehaviour itself
  h.sendMessage();
}

//Called by the activity in the Handler to execute in the good context
void startHandlerBehaviour() {
  //...
}
0
source

All Articles