android.view.ViewRootImpl$CalledFromWrongThreadException

android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.

(Only the main thread that created the UI object can modify the UI)

Solution one:

Android is not thread safe. Android has a mechanism to prevent child threads from updating the UI. In Android programming, some time-consuming operations need to be performed in a separate sub-thread outside the main thread, and then the user interface display is updated. However, the problem of directly updating the UI display in a thread other than the main thread is that the system will report this exception, and the work of updating the interface display must be performed in the main thread of the program (that is, the UI thread). So we should hand over the UI update to the main thread to complete, Android provides us with a set of message processing mechanism.

Implementation steps:
  Create an instance mHandler of the Handler class in onCreate(Bundle savedinstancestate){} of Activity, and call the method of updating the interface display in the callback method of the handleMessage(msg) method of this mHandler instance. E.g:

public class ExampleActivity extends Activity {
    
      
    Handler h = null;  
    @override  
    public void onCreate(Bundle savedinstancestate){  
        h = new Handler(){  
            @override  
            public void handleMessage(Message msg){  
                // call update gui method.  
            }  
        };  
    }  
}  

 In other functions, use the send family or post family functions to send or mail messages to this mHandler.
 If this error is still reported after using Handler, try changing handleMessage(msg) to sendMessage(msg).
 

Solution two:

Use activity.runOnUiThread(new Runnable(){}) to create the code for updating the UI in runnable, and then pass this Runnable object to activity.runOnUiThread(runnable) when the UI needs to be updated. In this way, the runnable object can be called in the ui program.

getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });

Guess you like

Origin blog.csdn.net/CHITTY1993/article/details/52325607