Solution for Android.view.viewroot$calledfromwrongthreadexception Exception * Update time: 2011-07-21

Source: Internet
Author: User
Under the Android platform, when multithreaded programming, it is often necessary to do some processing in a separate thread outside the main threads, and then update the user interface display. However, the problem with directly updating the page in a thread other than the main thread is that the system will report this exception, android.view.viewroot$calledfromwrongthreadexception:only the original thread That's created a view hierarchy can touch their views. (Only the thread that originally created this view hierachy can modify its view.) )。

That is, you must perform the work of updating the interface in the main thread of the program (that is, the UI thread). You can use one of the following methods to resolve:

Solution 1: Create an instance of the handler class in Activity.oncreate (Bundle savedinstancestate) and invoke the function shown in the update interface in the handler callback function of this handlemessage instance. For example:

  

public class Exampleactivity extends activity {
	Handler h = null;
	@override public
	void OnCreate (Bundle savedinstancestate) {
		h = new Handler () {
			@override public
			Void Handlemessage (msg) {
				//Call Update GUI method.}
			}
		;
}


In other functions, send or post a message to this h using the Send family or the post family function.


Solution 2: Using Activity.runonuithread (runnable)

Create the updated UI code in runnable, and then pass the Runnable object to Activity.runonuithread (Runnable) When the UI needs to be updated. This allows runnable to be invoked in the UI program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.