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

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


You have to move the portion of the background task that updates the UI onto the main thread. There is a simple piece of code for this:

runOnUiThread(new Runnable() {    @Override    public void run() {        // Stuff that updates the UI    }});

Documentation for Activity.runOnUiThread.

Just nest this inside the method that is running in the background, and then copy paste the code that implements any updates in the middle of the block. Include only the smallest amount of code possible, otherwise you start to defeat the purpose of the background thread.


I solved this by putting runOnUiThread( new Runnable(){ .. inside run():

thread = new Thread(){        @Override        public void run() {            try {                synchronized (this) {                    wait(5000);                    runOnUiThread(new Runnable() {                        @Override                        public void run() {                            dbloadingInfo.setVisibility(View.VISIBLE);                            bar.setVisibility(View.INVISIBLE);                            loadingText.setVisibility(View.INVISIBLE);                        }                    });                }            } catch (InterruptedException e) {                e.printStackTrace();            }            Intent mainActivity = new Intent(getApplicationContext(),MainActivity.class);            startActivity(mainActivity);        };    };      thread.start();


My solution to this:

private void setText(final TextView text,final String value){    runOnUiThread(new Runnable() {        @Override        public void run() {            text.setText(value);        }    });}

Call this method on a background thread.