Top 9 Android Calledfromwrongthreadexception Trust The Answer

You are looking for information, articles, knowledge about the topic nail salons open on sunday near me android calledfromwrongthreadexception on Google, you do not find the information you need! Here are the best content compiled and compiled by the https://chewathai27.com/to team, along with other related topics such as: android calledfromwrongthreadexception only the original thread that created a view hierarchy can touch its views., Only the original thread that created a view hierarchy can touch its views Xamarin Forms, android view viewrootimpl$calledfromwrongthreadexception, runOnUiThread, runOnUiThread Kotlin, Finish android, New thread ui android, Finish activity android


Prevent CalledFromWrongThreadException
Prevent CalledFromWrongThreadException


multithreading – Android “Only the original thread that created a view hierarchy can touch its views.” – Stack Overflow

  • Article author: stackoverflow.com
  • Reviews from users: 7371 ⭐ Ratings
  • Top rated: 3.3 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about multithreading – Android “Only the original thread that created a view hierarchy can touch its views.” – Stack Overflow ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Yet I’m doing basically the same thing here … …
  • Most searched keywords: Whether you are looking for multithreading – Android “Only the original thread that created a view hierarchy can touch its views.” – Stack Overflow ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Yet I’m doing basically the same thing here …
  • Table of Contents:

33 Answers
33

Not the answer you’re looking for Browse other questions tagged android multithreading or ask your own question

multithreading - Android
multithreading – Android “Only the original thread that created a view hierarchy can touch its views.” – Stack Overflow

Read More

Google Issue Tracker

  • Article author: issuetracker.google.com
  • Reviews from users: 2283 ⭐ Ratings
  • Top rated: 4.3 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about Google Issue Tracker Runtime exception at com.andro.systemui.car.statusbar. … ViewRootImpl$CalledFromWrongThreadException: Only the original thread that … …
  • Most searched keywords: Whether you are looking for Google Issue Tracker Runtime exception at com.andro.systemui.car.statusbar. … ViewRootImpl$CalledFromWrongThreadException: Only the original thread that …
  • Table of Contents:
Google Issue Tracker
Google Issue Tracker

Read More

android-How to solve ‘android android.view.ViewRootImpl$CalledFromWrongThreadException

  • Article author: www.bswen.com
  • Reviews from users: 42216 ⭐ Ratings
  • Top rated: 3.5 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about android-How to solve ‘android android.view.ViewRootImpl$CalledFromWrongThreadException andro-How to solve ‘andro andro.view.ViewRootImpl$CalledFromWrongThreadException. Dec 3, 2019. 1. The purpose of this post. I would demo how to solve … …
  • Most searched keywords: Whether you are looking for android-How to solve ‘android android.view.ViewRootImpl$CalledFromWrongThreadException andro-How to solve ‘andro andro.view.ViewRootImpl$CalledFromWrongThreadException. Dec 3, 2019. 1. The purpose of this post. I would demo how to solve … Java Web Android iOS Python Frameworks Spring Maven programming
  • Table of Contents:

1 The purpose of this post

2 Environments

3 Solution and Code

bswen

android-How to solve 'android android.view.ViewRootImpl$CalledFromWrongThreadException
android-How to solve ‘android android.view.ViewRootImpl$CalledFromWrongThreadException

Read More

[Android] CalledFromWrongThreadException in-depth source code analysis – Katastros

  • Article author: blog.katastros.com
  • Reviews from users: 13776 ⭐ Ratings
  • Top rated: 3.4 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about [Android] CalledFromWrongThreadException in-depth source code analysis – Katastros [Andro] CalledFromWrongThreadException in-depth source code analysis … ViewRootImpl$CalledFromWrongThreadException: Only the original thread that … …
  • Most searched keywords: Whether you are looking for [Android] CalledFromWrongThreadException in-depth source code analysis – Katastros [Andro] CalledFromWrongThreadException in-depth source code analysis … ViewRootImpl$CalledFromWrongThreadException: Only the original thread that …
  • Table of Contents:

Katastros

First conclusion

Problem recovery

Demo restore

Source code restoration

Conclusion

Reference article

[Android] CalledFromWrongThreadException in-depth source code analysis - Katastros
[Android] CalledFromWrongThreadException in-depth source code analysis – Katastros

Read More

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

  • Article author: www.tutorialkart.com
  • Reviews from users: 31090 ⭐ Ratings
  • Top rated: 3.4 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about Only the original thread that created a view hierarchy can touch its views Fix Andro CalledFromWrongThreadException. In this tutorial, we shall learn to fix Andro Exception CalledFromWrongThreadException : Only the original … …
  • Most searched keywords: Whether you are looking for Only the original thread that created a view hierarchy can touch its views Fix Andro CalledFromWrongThreadException. In this tutorial, we shall learn to fix Andro Exception CalledFromWrongThreadException : Only the original …
  • Table of Contents:

Fix Android CalledFromWrongThreadException

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

Read More

798858 – android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java) at org.mozilla.gecko.AboutHomeSection.show

  • Article author: bugzilla.mozilla.org
  • Reviews from users: 40366 ⭐ Ratings
  • Top rated: 4.2 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about 798858 – android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java) at org.mozilla.gecko.AboutHomeSection.show andro.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at andro.view. …
  • Most searched keywords: Whether you are looking for 798858 – android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java) at org.mozilla.gecko.AboutHomeSection.show andro.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at andro.view.
  • Table of Contents:

Quick Search

Categories

Tracking

People

References

Details

Crash Data

Security

User Story

798858 - android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java) at org.mozilla.gecko.AboutHomeSection.show
798858 – android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java) at org.mozilla.gecko.AboutHomeSection.show

Read More

Android Caused By Android View Viewrootimplcalledfromwrongthreadexception

  • Article author: www.faqcode4u.com
  • Reviews from users: 41767 ⭐ Ratings
  • Top rated: 4.1 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about
    Android Caused By Android View Viewrootimplcalledfromwrongthreadexception Im trying to get image from my URL and display in application but it throw error Caused by: andro.view.ViewRootImpl$CalledFromWrongThreadException: Only … …
  • Most searched keywords: Whether you are looking for
    Android Caused By Android View Viewrootimplcalledfromwrongthreadexception Im trying to get image from my URL and display in application but it throw error Caused by: andro.view.ViewRootImpl$CalledFromWrongThreadException: Only … This question already has answers …
  • Table of Contents:

android – Caused by androidviewViewRootImpl$CalledFromWrongThreadException

Answers

More Answers Related Android Caused By Android View Viewrootimplcalledfromwrongthreadexception


                    Android Caused By Android View Viewrootimplcalledfromwrongthreadexception
Android Caused By Android View Viewrootimplcalledfromwrongthreadexception

Read More

How to solve this CalledFromWrongThreadException when doing android espresso test? ~ AndroidBugFix

  • Article author: www.androidbugfix.com
  • Reviews from users: 13487 ⭐ Ratings
  • Top rated: 3.1 ⭐
  • Lowest rated: 1 ⭐
  • Summary of article content: Articles about How to solve this CalledFromWrongThreadException when doing android espresso test? ~ AndroidBugFix andro.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at … …
  • Most searched keywords: Whether you are looking for How to solve this CalledFromWrongThreadException when doing android espresso test? ~ AndroidBugFix andro.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at …
  • Table of Contents:

Saturday June 4 2022

Popular Posts

Labels

How to solve this CalledFromWrongThreadException when doing android espresso test? ~ AndroidBugFix
How to solve this CalledFromWrongThreadException when doing android espresso test? ~ AndroidBugFix

Read More


See more articles in the same category here: https://chewathai27.com/to/blog.

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

I’ve built a simple music player in Android. The view for each song contains a SeekBar, implemented like this:

public class Song extends Activity implements OnClickListener,Runnable { private SeekBar progress; private MediaPlayer mp; // … private ServiceConnection onService = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder rawBinder) { appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer progress.setVisibility(SeekBar.VISIBLE); progress.setProgress(0); mp = appService.getMP(); appService.playSong(title); progress.setMax(mp.getDuration()); new Thread(Song.this).start(); } public void onServiceDisconnected(ComponentName classname) { appService = null; } }; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.song); // … progress = (SeekBar) findViewById(R.id.progress); // … } public void run() { int pos = 0; int total = mp.getDuration(); while (mp != null && pos

android-How to solve ‘android android.view.ViewRootImpl$CalledFromWrongThreadException

1. The purpose of this post

I would demo how to solve this error when using do some UI operations in a thread:

The code(updateUI from a thread inside an activity or fragment):

public class MyActivity extends AppcompatActivity { private class CheckThread extends Thread { @Override public void run () { try { updateUI (); } catch ( Exception ex ) { LogUtils . error ( “” , ex ); } } } public void onCreate (…) { ( new CheckThread ()). start (); } private void updateUI () { myView . setVisibility ( View . VISIBLE ); //show some view in a thread } }

Run the app, we get this error:

E/MyTest: android.view.ViewRootImpl$ CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7753) at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1225) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.view.View.requestLayout(View.java:23093) at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360) at android.view.View.requestLayout(View.java:23093) at android.view.View.setFlags(View.java:14102) at android.view.View.setVisibility(View.java:9992) at com.tom.Fragment.showConfirmButton(Fragment.java:87) at com.tom.Presenter.onGotToken(Presenter.java:188) at com.tom.Presenter.access$ 800 ( Presenter.java:43 ) at com.tom.Presenter$ CheckThread.run ( Presenter.java:168 )

2. Environments

Android Studio 3.x

3. Solution and Code

Because android system do not allow the UI operations to run in the non-UI thread, so you can change the code like this:

public class MyActivity extends AppcompatActivity { private class CheckThread extends Thread { @Override public void run () { try { updateUI (); } catch ( Exception ex ) { LogUtils . error ( “” , ex ); } } } public void onCreate (…) { ( new CheckThread ()). start (); } private void updateUI () { myView . getActivity (). runOnUiThread ( new Runnable () { @Override public void run () { myView . setVisibility ( View . VISIBLE ); } }); } }

Build and run the app, everything works fine.

[Android] CalledFromWrongThreadException in-depth source code analysis

First conclusion

The reason for this problem is that the Dialog is created in a non-UI thread, and the show() method is called in the UI thread

Problem recovery

When using dialog, because of thread problems, when calling the dismiss() method, the following common crash—Only the original thread that created a view hierarchy can touch its views. appears. The stack information is as follows:

threadName:main,threadPriority:5,threadState:RUNNABLE Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7020) at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6035) at android.view.ViewRootImpl.die(ViewRootImpl.java:6020) at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:486) at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:424) at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:126) at android.app.Dialog.dismissDialog(Dialog.java:363) …. Omit part of the stack

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

The first reaction was that UI operations were performed on a non-UI thread.

Demo restore

public class MainActivity extends BaseActivity { private static final String TAG = “MainActivity” ; private ProgressDialog dialog ; @Override protected void the onCreate ( the Bundle savedInstanceState ) { Super . The onCreate ( savedInstanceState ) ; the setContentView ( R & lt . Layout . Activity_main ) ; new Thread ( new Runnable ( ) { @Override public void run ( ) { Looper . prepare ( ) ; //Create Dialog dialog in the child thread = new ProgressDialog ( MainActivity . This ) ; dialog . SetCanceledOnTouchOutside ( true ) ; dialog , “Dialog onCancel thread: ” + getThreadInfo ( ) ) ; } } ) ; dialog . SetOnDismissListener ( new DialogInterface . OnDismissListener ( ) { @Override . SetOnCancelListener ( new DialogInterface . OnCancelListener ( ) { @Override public void onCancel ( DialogInterface dialog ) { Log . D ( ” zhangrr” public void onDismiss ( DialogInterface dialog ) { Log . D ( “zhangrr” , “Dialog onDismiss thread : ” + getThreadInfo ( ) ) ; } } ) ; dialog . setMessage ( “dialog test” ) ; Log . d ( “zhangrr” , “Dialog create thread: ” + getThreadInfo ( ) ) ; Looper . loop ( ) ; } } ) . Start ( ) ; BTN the Button = ( the Button ) the findViewById ( R & lt . ID . Btn_helloworld ) ; BTN . SetOnClickListener ( new new View . OnClickListener to ( ) { @Override public void the onClick ( View V ) { //the UI thread show, then click on a blank area Dismiss Dialog . show ( ) ; Log . d ( “zhangrr” , “Dialog show thread: ” + getThreadInfo ( ) ) ; } } ) ; } private String getThreadInfo ( ) { return “[” + Thread . currentThread ( ) . getId ( ) + “]” + ( ( Looper . myLooper ( ) == Looper . getMainLooper ( ) ) ? “is UI-Thread” : “” ) ; } }

The demo is very simple. When the Activity is created, a ProgressDialog instance is created in the child thread, and show() is called on the UI thread to display the Dialog . Then click on the blank area of ​​the interface to dismiss Dialog, and it crashed directly, throwing CalledFromWrongThreadException .

Let’s take a look at the printed log:

Dialog create thread: [3953] Dialog show thread: [1] is UI-Thread Dialog onCancel thread: [3953] ..crash…As above stack information

If only the thread that created this control can update the content of the control, why doesn’t it crash when the show() method is called, and then it crashes when it dismiss()?

According to the stack information, in-depth source code, find out

threadName:main,threadPriority:5,threadState:RUNNABLE Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7020) at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6035) at android.view.ViewRootImpl.die(ViewRootImpl.java:6020) at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:486) at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:424) at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:126) at android.app.Dialog.dismissDialog(Dialog.java:363) …. Omit part of the stack

Source code restoration

According to the error stack information above, we trace the source code step by step from bottom to top:

/** * Dismiss this dialog, removing it from the screen. This method can be * invoked safely from any thread. Note that you should not override this * method to do cleanup when the dialog is dismissed, instead implement * that in {@link #onStop}. */ @Override public void dismiss ( ) { if ( Looper . MyLooper ( ) == mHandler . GetLooper ( ) ) { dismissDialog ( ) ; } else { mHandler . Post ( mDismissAction ) ; } }

The official explanation is that the dismiss() method can be called in any thread without worrying about thread safety. In other words, the dialog handles the UI operation separately. If the thread currently executing the dismiss operation is inconsistent with the thread to which the mHandler is attached, the dismiss operation will be thrown into the thread queue of the corresponding mHandler for execution . So where does this mHandler come from?

public class Dialog implements DialogInterface , Window . Callback , KeyEvent . Callback , OnCreateContextMenuListener , Window . OnWindowDismissedCallback { private final Handler mHandler = new Handler ( ) ; }

You can see that the mHandler object is private in the Dialog class and will be automatically initialized when new Dialog is made . Therefore, it can be concluded that the mHandler is directly associated with our new Dialog(), which is the thread when the Dialog is created . In other words, the thread that actually executes the dismissDialog() method to destroy the Dialog is also the thread of new Dialog().

void dismissDialog ( ) { if ( mDecor == null || ! mShowing ) { return ; } if ( mWindow . isDestroyed ( ) ) { Log . e ( TAG , “Tried to dismissDialog() but the Dialog’s window was already destroyed!” ) ; return ; } try { mWindowManager . removeViewImmediate ( mDecor ) ; } finally { if ( mActionMode != null ) { mActionMode . finish ( ) ; } mDecor = null ; mWindow . closeAllPanels ( ) ; onStop ( ) ; mShowing = false ; sendDismissMessage ( ) ; } }

You can find the final call

mWindowManager.removeViewImmediate(mDecor);

To destroy the Dialog, continue to follow the removeViewImmediate() method

The initialization of mWindowManager is in the constructor of Dialog:

Dialog ( @NonNull the Context context , @StyleRes int themeResId , Boolean createContextThemeWrapper ) { /* omitted part of the code */ mWindowManager = ( The WindowManager ) context . The getSystemService ( the Context . WINDOW_SERVICE ) ; final Window w = new PhoneWindow ( mContext ) ; mWindow = w ; w . setCallback ( this ) ; w . setOnWindowDismissedCallback ( this ) ; w . setOnWindowSwipeDismissedCallback ( ( ) – > { if ( mCancelable ) { cancel ( ) ; } } ) ; w . setWindowManager ( mWindowManager , null , null ) ; w . setGravity ( Gravity . CENTER ) ; mListenersHandler = new ListenersHandler ( this ) ; }

mWindowManager is passed

context.getSystemService(Context.WINDOW_SERVICE);

Get it, look at the getSystemService() function in Activity:

@Override public Object getSystemService ( @ServiceName @NonNull String name ) { if ( getBaseContext ( ) == null ) { throw new IllegalStateException ( “System services not available to Activities before onCreate()” ) ; } if ( WINDOW_SERVICE . equals ( name ) ) { return mWindowManager ; } else if ( SEARCH_SERVICE . equals ( name ) ) { ensureSearchManager ( ) ; return mSearchManager ; } return super . getSystemService ( name ) ; } final void attach ( Context context , ActivityThread aThread , Instrumentation instr , IBinder token , int ident , Application application , Intent intent , ActivityInfo info , CharSequence title , Activity parent , String id , NonConfigurationInstances lastNonConfigurationInstances , Configuration config , IVoiceInteractor voiceInteractor ) { mWindow . setWindowManager ( ( WindowManager ) context . getSystemService ( Context . WINDOW_SERVICE ) , mToken , mComponent . flattenToString ( ) , ( info . flags & ActivityInfo . FLAG_HARDWARE_ACCELERATED ) != 0 ) ; mWindowManager = mWindow . getWindowManager ( ) ; //…Omit other codes… }

It can be found that the mWindowManager object is passed when the attach() function is called after the Activity is created

mWindow.setWindowManager()

Initialization.

/** * Set the window manager for use by this Window to, for example, * display panels. This is not used for displaying the * Window itself – that must be done by the client. * * @param wm The window manager for adding new windows. */ Public void setWindowManager ( The WindowManager WM , the IBinder APPTOKEN , String appName , Boolean hardwareAccelerated ) { mAppToken = APPTOKEN ; mAppName = appName ; mHardwareAccelerated = hardwareAccelerated || systemProperties . GetBoolean ( PROPERTY_HARDWARE_UI , to false ) ; IF ( WM == null ) { wm = ( WindowManager ) mContext . getSystemService ( Context . WINDOW_SERVICE ) ; } mWindowManager = ( ( WindowManagerImpl ) wm ) . createLocalWindowManager ( this ) ; }

It is found that the object mWindowManager finally comes from the WindowManagerImpl class:

public final class WindowManagerImpl implements WindowManager { private final WindowManagerGlobal mGlobal = WindowManagerGlobal . getInstance ( ) ; private final Context mContext ; private final Window mParentWindow ; public WindowManagerImpl createLocalWindowManager ( the Window parentWindow ) { return new new WindowManagerImpl ( mContext , parentWindow ) ; } @Override public void addView ( @NonNull View View , @NonNull the ViewGroup . LayoutParams for the params ) { applyDefaultToken ( the params ) ; mGlobal . AddView ( View , the params , mContext . GetDisplay ( ) , mParentWindow ) ; } @Override public void removeView ( View view ) { mGlobal . RemoveView ( view , false ) ; } @Override public void removeViewImmediate ( View view ) { mGlobal . RemoveView ( view , true ) ; } }

at last! ! ! Saw the removeViewImmediate() function. Therefore, it can be concluded that in the implementation of the Dialog destruction function dismissDialog () , it is finally called

mWindowManager.removeViewImmediate(mDecor);

To destroy the Dialog, the() method in the WindowManagerImpl instance .

Let’s insert the previous stack information

threadName:main,threadPriority:5,threadState:RUNNABLE Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7020) at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6035) at android.view.ViewRootImpl.die(ViewRootImpl.java:6020) at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:486) at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:424) at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:126) at android.app.Dialog.dismissDialog(Dialog.java:363) …. Omit part of the stack

Now to step 3, the removeViewImmediate() method in the WindowManagerImpl instance actually calls the removeView () function of WindowManagerGlobal .

public void removeView ( View view , boolean immediate ) { if ( view == null ) { throw new IllegalArgumentException ( “view must not be null” ) ; } synchronized ( mLock ) { int index = findViewLocked ( view , true ) ; View curView = mRoots . get ( index ) . getView ( ) ; removeViewLocked ( index , immediate ) ; if ( curView == view ) { return ; } throw new IllegalStateException ( “Calling with view ” + view + ” but the ViewAncestor is attached to ” + curView ) ; } }

Without stopping, we tracked down to step 4.

private void removeViewLocked ( int index , boolean immediate ) { ViewRootImpl root = mRoots . get ( index ) ; View view = root . getView ( ) ; if ( view != null ) { InputMethodManager imm = InputMethodManager . getInstance ( ) ; if ( imm != null ) { imm . windowDismissed ( mViews . get ( index ) . getWindowToken ( ) ) ; } } boolean deferred = root . die ( immediate ) ; if ( view != null ) { view . assignParent ( null ) ; if ( deferred ) { mDyingViews . add ( view ) ; } } }

Pay attention to these two lines of code: the root object is actually an instance of ViewRootImpl, follow its die() method:

ViewRootImpl root = mRoots . Get ( index ) ; boolean deferred = root . Die ( immediate ) ;

Let’s insert the previous stack information

threadName:main,threadPriority:5,threadState:RUNNABLE Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7020) at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6035) at android.view.ViewRootImpl.die(ViewRootImpl.java:6020) at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:486) at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:424) at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:126) at android.app.Dialog.dismissDialog(Dialog.java:363) …. Omit part of the stack

/** * @param immediate True, do now if not in traversal. False, put on queue and do later. * @return True, request has been queued. False, request has been completed. */ boolean die ( boolean immediate ) { //Make sure we do execute immediately if we are in the middle of a traversal or the damage //done by dispatchDetachedFromWindow will cause havoc on return. if ( immediate && ! mIsInTraversal ) { doDie ( ) ; return false ; } }

Finally, the execution reaches the doDie() method of the ViewRootImpl class .

After many mountains and rivers have recovered, it will soon become clear! ! ! hold on

void doDie ( ) { checkThread ( ) ; //omit the code }

Let’s insert the previous stack information

threadName:main,threadPriority:5,threadState:RUNNABLE Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7020) at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6035) at android.view.ViewRootImpl.die(ViewRootImpl.java:6020) at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:486) at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:424) at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:126) at android.app.Dialog.dismissDialog(Dialog.java:363) …. Omit part of the stack

According to the stack information, the checkThread() function in the ViewRootImpl code is known where the exception is finally thrown .

Finally came to the key point

void checkThread ( ) { if ( mThread != Thread . currentThread ( ) ) { throw new CalledFromWrongThreadException ( “Only the original thread that created a view hierarchy can touch its views.” ) ; } }

Preliminary conclusion: According to the introduction at the beginning of the article, when the dialog’s dismiss() is called, the dialog will be automatically thrown into the thread of our new Dialog() for execution, that is

Thread.currentThread

. The reason why this exceptionthrown

Therefore, the culprit of the next problem is how mThread came about! ! !

Find the place where mThread is assigned in ViewRootImpl:

public ViewRootImpl ( Context context , Display display ) { mThread = Thread . currentThread ( ) ; //Omit part of the code }

The question now is, when did ViewRootImpl call this constructor to create an instance?

Back to the fourth subsection, WindowManagerGlobal’s removeView() method

ViewRootImpl root = mRoots . Get ( index ) ; boolean deferred = root . Die ( immediate ) ;

It is found that the root object is taken out from the mRoots object, and mRoots is a

ArrayList

, So we look at the generation of mRoots

public void addView ( View view , ViewGroup . LayoutParams params , Display display , Window parentWindow ) { //…Omit the rest of the code….. ViewRootImpl root ; synchronized ( mLock ) { //…Omit the rest of the code….. root = new ViewRootImpl ( view . getContext ( ) , display ) ; mRoots . add ( root ) ; } }

When will the addView() method be called? Just

WindowManagerImpl.addView()

@Override public void addView ( @NonNull View View , @NonNull the ViewGroup . LayoutParams for the params ) { applyDefaultToken ( the params ) ; mGlobal . AddView ( View , the params , mContext . GetDisplay ( ) , mParentWindow ) ; }

Let’s find the place where the mWindowManager object calls the addView() method in the source code of Dialog. It is really, suddenly looking back, the person is in the dim light:

/** * Start the dialog and display it on screen. The window is placed in the * application layer and opaque. Note that you should not override this * method to do initialization when the dialog is shown, instead implement * that in {@link #onStart}. */ public void show ( ) { //Omit part of the code onStart ( ) ; mDecor = mWindow . getDecorView ( ) ; mWindowManager . addView ( mDecor , l ) ; sendShowMessage ( ) ; }

Seeing this, it is estimated that you can understand it. Calling the show() method of Dialog will pass

mWindowManager.addView(mDecor, l);

Create a ViewRootImpl object,, that is, thethat calls the show() method of Dialog.

When calling the dismiss() method of Dialog, it will first be thrown to the thread of new Dialog for execution, and finally by calling

mWindowManager.removeViewImmediate()

To destroy the View, the doDie() method of the ViewRootImpl object is naturally called at this time. In this method, checkThread() will be checked. At this time, it will check whether the

Let’s insert the previous stack information

threadName:main,threadPriority:5,threadState:RUNNABLE Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7020) at android.view.ViewRootImpl.doDie(ViewRootImpl.java:6035) at android.view.ViewRootImpl.die(ViewRootImpl.java:6020) at android.view.WindowManagerGlobal.removeViewLocked(WindowManagerGlobal.java:486) at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:424) at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:126) at android.app.Dialog.dismissDialog(Dialog.java:363) …. Omit part of the stack

Following the stack information, we have reached the root of the problem step by step, and then briefly summarize:

new Dialog: non-UI thread (Thread.currentThread())

show(): UI main thread (mThread)

cancel(): non-UI thread

dismiss(): non-UI thread

It is now clear that ViewRootImpl does not have checkThread() when the show() method is executed, so there will be no crash . When dismiss() is executed, it is first thrown into the thread of new Dialog for execution, and then ViewRootImpl will checkThread() when the View is actually destroyed to ensure that the thread of addView() can removeView().

In the example, Dialog’s show() is executed in the main thread, and new Dialog() is executed in a non-UI thread , so the CalledFromWrongThreadException is thrown.

Conclusion

Dialog’s dismiss() will first be thrown into the thread of new Dialog() for execution. As long as the creation of the Dialog and the call to the show() method are executed in the same thread, no matter whether it is placed on the UI thread or not. When the show() method is executed, ViewRootImpl does not have checkThread(), so there will be no crash

Reference article

https://my.oschina.net/qixiaobo025/blog/195396

——To all the programmers who are working hard! Come on! !

There are yards traveled the world Uncensored unable to move

1024– dream, never stop!

Love Bug programming does not love

love not love black eye overtime

stubborn but not paranoid

crazy, but not insane

life of rookie

work great God

pregnant treasure, as one hopes sea stars

The pursuit of the ultimate, the goal starts from the top

of the mountain. A group of children

who are curious and dream to change the world. A group of geeks who are chasing the sun and the waves and are changing the world.

You use the most beautiful language to interpret the power of technology.

You lead the times with rapid innovation. Changes

So you have finished reading the android calledfromwrongthreadexception topic article, if you find this article useful, please share it. Thank you very much. See more: only the original thread that created a view hierarchy can touch its views., Only the original thread that created a view hierarchy can touch its views Xamarin Forms, android view viewrootimpl$calledfromwrongthreadexception, runOnUiThread, runOnUiThread Kotlin, Finish android, New thread ui android, Finish activity android

Leave a Comment