0

I am running the below code inside a new thread that I create by doing:

new Thread(new Runnable() {
    public void run() {
        // CODE BELOW
    }
}).start();

So my runonUI code is never being executed. I am under the impression that I need to run it on the UI thread in order to update the adapter. Also am I updating the adapter correctly?

Log.d(App.app.chats.toString(),"THIS IS THE TEXTS WE SHOULD DISPLAY");

((ArrayAdapter)App.app.chatDisplay.getAdapter()).clear();

for (int i = 0; i < App.app.chats.size(); i++) {
    ((ArrayAdapter)App.app.chatDisplay.getAdapter()).add(App.app.chats.get(i));
}

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Log.d("THIS IS ACTUALLY RUNNING","TEST");
        ((BaseAdapter)App.app.chatDisplay.getAdapter()).notifyDataSetChanged();
    }
});
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    If this runOnUiThread is never been executed it is very likely that this code is not been reached! I can only say more if i see your whole code... – Mike Dec 13 '14 at 03:23
  • As @Mike said, code is never being reached. Maybe you are using the runOnUIThread outside the worker-thread? – Menelaos Kotsollaris Dec 13 '14 at 04:37
  • The line above runs, is there a command I need for that runOnUi to run? – user3089187 Dec 13 '14 at 05:34
  • What is App.app.chatDisplay? How come you don't have an adapter reference in the activity, but instead have an adapter held by the chatDisplay which is held by app class? Just trying to better understand to be able to formulate an answer. – Gunnar Karlsson Dec 13 '14 at 13:43

1 Answers1

0

If I understand your question correctly, You can not modify an ArrayAdapter from a background thread. Both the clear and add method calls internally invoke notifyDataSetChanged. Which means your notifyDataSetChanged invocation is sorta redundant and that thread is crashing before you even get to your runOnUiThread line.

A quick workaround for you would be to add the following before you mutate the adapter.

((ArrayAdapter)App.app.chatDisplay.getAdapter()).setNotifyOnChange(false);

That will disable the internal notifyDataSetChanged invocation. The flag will reset once you manually invoke it yourself. Also note, the ArrayAdapter was never intended to be mutated from a background thread like that. While the above solution should get it working for you, I highly recommended moving those mutate method calls to the UI thread.

Ifrit
  • 6,791
  • 8
  • 50
  • 79
  • Alright, awesome so the clear and add methods were crashing my thread, so I added those to the UI thread, and removed the notification. Thank you! I was stumped. Also thanks for understanding I was pretty sick yesterday and probably not making much sense. – user3089187 Dec 14 '14 at 03:30