VinayChoudhary99
VinayChoudhary99

Reputation: 914

Difference between activity handler and view handler android

I was trying to send a message to activity handler from a Listview's onItemClick() method of OnItemClickListener.

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Handler handler = view.getHandler();
    String data = "MSG DATA";
    Message msg = handler.obtainMessage(MSG_TYPE, data);
    msg.sendToTarget();
}

And I have a handler in activity as

Handler mHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    int msgId = msg.what;
    Log.d(TAG,"GOT msg : " + msgId);
    }
}

But I don't get the message and application crashes.

java.lang.ClassCastException: java.lang.String cannot be cast to android.view.View$AttachInfo$InvalidateInfo
       at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:3175)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5289)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

From documentation for getHandler():

A handler associated with the thread running the View. This handler can be used to pump events in the UI events queue.

So if the view is created in activity, they both should be on same thread. Why am I getting crash? Are these two different handlers?

Upvotes: 0

Views: 3630

Answers (1)

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

Are these two different handlers?

They are different Handlers attached to the same UI thread Looper.

So if the view is created in activity, they both should be on same thread. Why am I getting crash?

When you do handler.obtainMessage(MSG_TYPE, data); it actually sets the target to handler. So, when you call msg.sendToTarget(); it sends the message to View's Handler, not to Activity's one. You are getting this exception because View's Handler doesn't know how to handle that String.

Set your Activity's Handler as a target and you won't get that crash.

Upvotes: 3

Related Questions