Tuesday, 17 March 2015

Android Only the original thread that created a view hierarchy can touch its views.

CalledFromWrongThreadException:Only the original thread that created a view hierarchy can touch its views

use the below code for this error



 private void addMessages(final MessageClass m)
 {

  Handler threadHandle = new Handler(Looper.getMainLooper());
  threadHandle .post(new Runnable()
  {

   @Override
   public void run()
   {
    Chat.listMessages.add(m);
                            //listMessages is an array variable declared in the class Chat
    Chat.adapter.notifyDataSetChanged();
                          //adapter is a Listview Adapter declared in the class Chat
   }
  });
 }

Happy Coding:)