ArrayAdapter notifyDataSetChanged not being executed on UI thread

1.1k views Asked by At

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();
    }
});
1

There are 1 answers

1
Ifrit On BEST ANSWER

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.