Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Object from Service to Activity (Can't marshal non-Parcelable)

I'm trying to send data from my activity to a service and receive some information back, but i'm getting:

java.lang.RuntimeException: Can't marshal non-Parcelable objects across processes.

The code from activity looks like this:

Message msg = Message.obtain(null, 1);
    msg.obj=1;
    msg.replyTo=new Messenger(new PlanRequestIncomingHandler());
    try {
        msgService.send(msg);
    } catch (RemoteException e) {
        Log.i(tag, "Can not send msg to service");
        e.printStackTrace();
    }

When I set msg.obj = something I get java.lang.RuntimeException, can somebody help me?

like image 364
cmg_george Avatar asked Jul 06 '11 12:07

cmg_george


1 Answers

You can pass Parcelable type objects via Messenger. Or else if you want to pass primitive data types use Bundle wrapper as below.

In Service End:

//Create a bundle object and put your data in it
Bundle bundle = new Bundle();
bundle.putInt("key", 1);

Message msg = Message.obtain(null, 123);
msg.obj = bundle;
msg.replyTo = new Messenger(new PlanRequestIncomingHandler());
try {
    msgService.send(msg);
} catch (RemoteException e) {
    Log.i(tag, "Can't send msg to service");
    e.printStackTrace();
}

In Activity End:

switch(msg.what) {
    case 123:
        if(msg.obj != null) {
            Bundle bundle = (Bundle) msg.obj;
            System.out.println("Got integer "+ bundle.getInt("key"));
        }
    break;
}

cheers :-)

like image 115
Mohan Avatar answered Oct 01 '22 04:10

Mohan