Search code examples
androidmultithreadingperformancethreadpoolandroid-runonuithread

what to use if i have long updating ui thread in android


I have a project which a activity have more than 1000 buttons. i am updating the background color of these buttons after taking the color information from the database. This whole process is a very big process and took 8 seconds to load my activity. i have implement Asynctask for that but the problem is with this exception because "Only the original thread that created a view hierarchy can touch its views". because my long operation is on that part where i am updating my UI elements

After that i have implemented a thread that runs on UIthread for updating ui elements, this works fine according to its function, this thread update my ui but it stucks my application for 5-6 seconds. and then i thought of implementing a progress dialog for that 5-6 seconds. but if i implement progress dialog on runOnUiThread(new Runnable(){} it doesn't work. because updating ui and progress dialog runs on the same time. so progress dialog flashes for few milliseconds. and the activity still remains the same as it was before. I don't know that to use for updating ui if they took long time to update.

This is my code where i update by ui elements from database.

            for (int i = 0; i < list.size(); i++) {

                Button btn = list.get(i);
                Platform p = db.setplatformncolor(btn.getTag().toString());
                String color = p.getColor();


                if (color.equals("red")) {
                    btn.setBackgroundColor(Color.RED);
                }


                if (color.equals("green")) {

                    btn.setBackgroundColor(Color.rgb(0, 176, 80));

                }

Any help is appreciated. Thanks.!!


Solution

  • the for loop take two long time, try to just put the loop in thread and setBackgroundColor in ui thread.

    new Thread(new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < list.size(); i++) {
    
                final Button btn = list.get(i);
                Platform p = db.setplatformncolor(btn.getTag().toString());
                String color = p.getColor();
    
    
                if (color.equals("red")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btn.setBackgroundColor(Color.RED);
                        }
                    });
                }
    
    
                if (color.equals("green")) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btn.setBackgroundColor(Color.rgb(0, 176, 80));
                        }
                    });
    
                }
            }
        }
    }).start();