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

여러개의 버튼에 이미지 효과를 줄 때 갭을 주기 위해, TimerTask를 사용하였다. 메인 스레드가 아닌 서브스레드에서 UI의 상태를 변경하려고 할때 발생하는 오류인데, 이게 모든 휴대폰에서 발생하는 오류는 아니다.  심각한 오류라면 모든 휴대폰에서 오류가 발생해야 정상인데, 그렇지 않다.  안드로이드 운영체제 버전이 낮은 경우에 주로 발생되고 있다.

Show
Fatal Exception: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6556) at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:942) at android.view.ViewGroup.invalidateChild(ViewGroup.java:5081) at android.view.View.invalidateInternal(View.java:12719) at android.view.View.invalidate(View.java:12683) at android.view.View.invalidateParentIfNeeded(View.java:12872) at android.view.View.clearAnimation(View.java:19121) at ddolcat.app.battery.fast.charger.MainActivity.makeFastBlanking(MainActivity.java:834) at ddolcat.app.battery.fast.charger.MainActivity$6.run(MainActivity.java:856) at java.util.Timer$TimerImpl.run(Timer.java:284)ㅁㄴㄹ

■오류가 발생한 코드

public void makeBlanking(Button bar) { bar.clearAnimation(); bar.setAnimation(AnimationUtils.loadAnimation(this, R.anim.bar_fast_fade)); } private void runAnimaion(){ Button sunder_1 = view.findViewById(R.id.sunder_1); Button sunder_2 = view.findViewById(R.id.sunder_2); Timer time1 = new Timer(); time1.schedule(new TimerTask() { @Override public void run() { makeBlanking(sunder_1); } }, 100); Timer time2 = new Timer(); time2.schedule(new TimerTask() { @Override public void run() { makeFastBlanking(sunder_2); } }, 1000); }

■오류를 수정한 코드

public void makeBlanking(final Button bar) { runOnUiThread(new Runnable() { @Override public void run() { bar.clearAnimation(); bar.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.bar_fast_fade)); } }); }

메인스레드에서 처리하면 해결된다. runOnUiThread를 사용하거나 Handler를 사용해서 해결한다.

핸들러 사용시에는 주의가 필요하다. 아래 코드 처럼 Handler를 사용하면 또 다른 오류가 발생한다. Looper가 준비되지 않았다는 오류가 뜨게 된다.

public void makeBlanking(final Button bar) { final Handler mHandler = new Handler(); mHandler.post(new Runnable() { @Override public void run() { bar.clearAnimation(); bar.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.bar_fast_fade)); } }); }UncaughtException: java.lang.RuntimeException: Can't create handler inside thread Thread[Timer-4,5,main] that has not called Looper.prepare() at android.os.Handler.<init>(Handler.java:207) at android.os.Handler.<init>(Handler.java:119) at com.test.Fragment$1$1.run(ChatFragment.java:144) at java.util.TimerThread.mainLoop(Timer.java:562) at java.util.TimerThread.run(Timer.java:512)

메인스레드에서 핸들러가 작업이 진행될 수 있도록 Handler 선언시 Looper.getMainLooper()를 사용하여 메인 루퍼를 가져온다.

public void makeBlanking(final Button bar) { final Handler mHandler = new Handler(Looper.getMainLooper()); mHandler.post(new Runnable() { @Override public void run() { bar.clearAnimation(); bar.setAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.bar_fast_fade)); } }); }

[관련자료]
https://stackoverflow.com/questions/3280141/calledfromwrongthreadexception-only-the-original-thread-that-created-a-view-hie

https://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi

https://itmining.tistory.com/5

https://itmining.tistory.com/6

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

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

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00

762

I've built a simple music player in Android. anycodings_android The view for each song contains a SeekBar, anycodings_android 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<total) { try { Thread.sleep(1000); pos = appService.getSongPosition(); } catch (InterruptedException e) { return; } catch (Exception e) { return; } progress.setProgress(pos); } }

This works fine. Now I want a timer counting anycodings_android the seconds/minutes of the progress of the anycodings_android song. So I put a TextView in the layout, get anycodings_android it with findViewById() in onCreate(), and anycodings_android put this in run() after anycodings_android progress.setProgress(pos):

String time = String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(pos), TimeUnit.MILLISECONDS.toSeconds(pos), TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes( pos)) ); currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);

But that last line gives me the exception:

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

Yet I'm doing basically the same thing here anycodings_android as I'm doing with the SeekBar - creating the anycodings_android view in onCreate, then touching it in run() anycodings_android - and it doesn't give me this complaint.

Total Answers 30

28

Answers 1 : of Android Only the original thread that created a view hierarchy can touch its views.

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

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

Documentation for anycodings_android Activity.runOnUiThread.

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

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

mRahman

1

Answers 2 : of Android Only the original thread that created a view hierarchy can touch its views.

I solved this by putting runOnUiThread( anycodings_android 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();

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

5

Answers 3 : of Android Only the original thread that created a view hierarchy can touch its views.

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.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

3

Answers 4 : of Android Only the original thread that created a view hierarchy can touch its views.

Kotlin coroutines can make your code anycodings_android more concise and readable like this:

MainScope().launch { withContext(Dispatchers.Default) { //TODO("Background processing...") } TODO("Update UI here!") }

Or vice versa:

GlobalScope.launch { //TODO("Background processing...") withContext(Dispatchers.Main) { // TODO("Update UI here!") } TODO("Continue background processing...") }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

3

Answers 5 : of Android Only the original thread that created a view hierarchy can touch its views.

Usually, any action involving the user anycodings_android interface must be done in the main or UI anycodings_android thread, that is the one in which anycodings_android onCreate() and event handling are anycodings_android executed. One way to be sure of that is anycodings_android using runOnUiThread(), another is using anycodings_android Handlers.

ProgressBar.setProgress() has a anycodings_android mechanism for which it will always anycodings_android execute on the main thread, so that's anycodings_android why it worked.

See Painless Threading.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

miraj

6

Answers 6 : of Android Only the original thread that created a view hierarchy can touch its views.

I've been in this situation, but I found anycodings_android a solution with the Handler Object.

In my case, I want to update a anycodings_android ProgressDialog with the observer anycodings_android pattern. My view implements observer and anycodings_android overrides the update method.

So, my main thread create the view and anycodings_android another thread call the update method anycodings_android that update the ProgressDialop and....:

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

It's possible to solve the problem with anycodings_android the Handler Object.

Below, different parts of my code:

public class ViewExecution extends Activity implements Observer{ static final int PROGRESS_DIALOG = 0; ProgressDialog progressDialog; int currentNumber; public void onCreate(Bundle savedInstanceState) { currentNumber = 0; final Button launchPolicyButton = ((Button) this.findViewById(R.id.launchButton)); launchPolicyButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDialog(PROGRESS_DIALOG); } }); } @Override protected Dialog onCreateDialog(int id) { switch(id) { case PROGRESS_DIALOG: progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("Loading"); progressDialog.setCancelable(true); return progressDialog; default: return null; } } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch(id) { case PROGRESS_DIALOG: progressDialog.setProgress(0); } } // Define the Handler that receives messages from the thread and update the progress final Handler handler = new Handler() { public void handleMessage(Message msg) { int current = msg.arg1; progressDialog.setProgress(current); if (current >= 100){ removeDialog (PROGRESS_DIALOG); } } }; // The method called by the observer (the second thread) @Override public void update(Observable obs, Object arg1) { Message msg = handler.obtainMessage(); msg.arg1 = ++currentPluginNumber; handler.sendMessage(msg); } }

This explanation can be found on this anycodings_android page, and you must read the "Example anycodings_android ProgressDialog with a second thread".

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

2

Answers 7 : of Android Only the original thread that created a view hierarchy can touch its views.

You can use Handler to Delete View anycodings_android without disturbing the main UI anycodings_android Thread. Here is example code

new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { //do stuff like remove view etc adapter.remove(selecteditem); } });

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

2

Answers 8 : of Android Only the original thread that created a view hierarchy can touch its views.

Kotlin Answer

We have to use UI Thread for the job anycodings_android with true way. We can use UI Thread in anycodings_android Kotlin, such as:

runOnUiThread(Runnable { //TODO: Your job is here..! })

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

1

Answers 9 : of Android Only the original thread that created a view hierarchy can touch its views.

I see that you have accepted anycodings_android @providence's answer. Just in case, you anycodings_android can also use the handler too! First, do anycodings_android the int fields.

private static final int SHOW_LOG = 1; private static final int HIDE_LOG = 0;

Next, make a handler instance as a anycodings_android field.

//TODO __________[ Handler ]__________ @SuppressLint("HandlerLeak") protected Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // Put code here... // Set a switch statement to toggle it on or off. switch(msg.what) { case SHOW_LOG: { ads.setVisibility(View.VISIBLE); break; } case HIDE_LOG: { ads.setVisibility(View.GONE); break; } } } };

Make a method.

//TODO __________[ Callbacks ]__________ @Override public void showHandler(boolean show) { handler.sendEmptyMessage(show ? SHOW_LOG : HIDE_LOG); }

Finally, put this at onCreate() method.

showHandler(true);

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

2

Answers 10 : of Android Only the original thread that created a view hierarchy can touch its views.

Use this code, and no need to anycodings_android runOnUiThread function:

private Handler handler; private Runnable handlerTask; void StartTimer(){ handler = new Handler(); handlerTask = new Runnable() { @Override public void run() { // do something textView.setText("some text"); handler.postDelayed(handlerTask, 1000); } }; handlerTask.run(); }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

2

Answers 11 : of Android Only the original thread that created a view hierarchy can touch its views.

I had a similar issue, and my solution anycodings_android is ugly, but it works:

void showCode() { hideRegisterMessage(); // Hides view final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { showRegisterMessage(); // Shows view } }, 3000); // After 3 seconds }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

1

Answers 12 : of Android Only the original thread that created a view hierarchy can touch its views.

I was facing a similar problem and none anycodings_android of the methods mentioned above worked anycodings_android for me. In the end, this did the trick anycodings_android for me:

Device.BeginInvokeOnMainThread(() => { myMethod(); });

I found this gem here.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

3

Answers 13 : of Android Only the original thread that created a view hierarchy can touch its views.

I use Handler with anycodings_android Looper.getMainLooper(). It worked fine anycodings_android for me.

Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { // Any UI task, example textView.setText("your text"); } }; handler.sendEmptyMessage(1);

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

1

Answers 14 : of Android Only the original thread that created a view hierarchy can touch its views.

This is explicitly throwing an error. It anycodings_android says whichever thread created a view, anycodings_android only that can touch its views. It is anycodings_android because the created view is inside that anycodings_android thread's space. The view creation (GUI) anycodings_android happens in the UI (main) thread. So, you anycodings_android always use the UI thread to access those anycodings_android methods.

In the above picture, the progress anycodings_android variable is inside the space of the UI anycodings_android thread. So, only the UI thread can anycodings_android access this variable. Here, you're anycodings_android accessing progress via new Thread(), and anycodings_android that's why you got an error.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

6

Answers 15 : of Android Only the original thread that created a view hierarchy can touch its views.

This happened to my when I called for an anycodings_android UI change from a doInBackground from anycodings_android Asynctask instead of using anycodings_android onPostExecute.

Dealing with the UI in onPostExecute anycodings_android solved my problem.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

4

Answers 16 : of Android Only the original thread that created a view hierarchy can touch its views.

I was working with a class that did not anycodings_android contain a reference to the context. So anycodings_android it was not possible for me to use anycodings_android runOnUIThread(); I used view.post(); and anycodings_android it was solved.

timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { final int currentPosition = mediaPlayer.getCurrentPosition(); audioMessage.seekBar.setProgress(currentPosition / 1000); audioMessage.tvPlayDuration.post(new Runnable() { @Override public void run() { audioMessage.tvPlayDuration.setText(ChatDateTimeFormatter.getDuration(currentPosition)); } }); } }, 0, 1000);

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

6

Answers 17 : of Android Only the original thread that created a view hierarchy can touch its views.

When using AsyncTask Update the UI in anycodings_android onPostExecute method

@Override protected void onPostExecute(String s) { // Update UI here }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

5

Answers 18 : of Android Only the original thread that created a view hierarchy can touch its views.

This is the stack trace of mentioned anycodings_android exception

at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6149) at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:843) at android.view.View.requestLayout(View.java:16474) at android.view.View.requestLayout(View.java:16474) at android.view.View.requestLayout(View.java:16474) at android.view.View.requestLayout(View.java:16474) at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352) at android.view.View.requestLayout(View.java:16474) at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:352) at android.view.View.setFlags(View.java:8938) at android.view.View.setVisibility(View.java:6066)

So if you go and dig then you come to anycodings_android know

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

Where mThread is initialize in anycodings_android constructor like below

mThread = Thread.currentThread();

All I mean to say that when we created anycodings_android particular view we created it on UI anycodings_android Thread and later try to modifying in a anycodings_android Worker Thread.

We can verify it via below code snippet

Thread.currentThread().getName()

when we inflate layout and later where anycodings_android you are getting exception.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

1

Answers 19 : of Android Only the original thread that created a view hierarchy can touch its views.

If you do not want to use runOnUiThread anycodings_android API, you can in fact implement AsynTask anycodings_android for the operations that takes some anycodings_android seconds to complete. But in that case, anycodings_android also after processing your work in anycodings_android doinBackground(), you need to return the anycodings_android finished view in onPostExecute(). The anycodings_android Android implementation allows only main anycodings_android UI thread to interact with views.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

3

Answers 20 : of Android Only the original thread that created a view hierarchy can touch its views.

For a one-liner version of the anycodings_android runOnUiThread() approach, you can use a anycodings_android lambda function, i.e.:

runOnUiThread(() -> doStuff(Object, myValue));

where doStuff() can represents some anycodings_android method used to modify the value of some anycodings_android UI Object (setting text, changing anycodings_android colors, etc.).

I find this to be much neater when anycodings_android trying to update several UI objects anycodings_android without the need for a 6 line Runnable anycodings_android definition at each as mentioned in the anycodings_android most upvoted answer, which is by no anycodings_android means incorrect, it just takes up a lot anycodings_android more space and I find to be less anycodings_android readable.

So this:

runOnUiThread(new Runnable() { @Override public void run() { doStuff(myTextView, "myNewText"); } });

can become this:

runOnUiThread(() -> doStuff(myTextView, "myNewText"));

where the definition of doStuff lies anycodings_android elsewhere.

Or if you don't need to be so anycodings_android generalizable, and just need to set the anycodings_android text of a TextView object:

runOnUiThread(() -> myTextView.setText("myNewText"));

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

1

Answers 21 : of Android Only the original thread that created a view hierarchy can touch its views.

If you simply want to invalidate (call anycodings_android repaint/redraw function) from your non anycodings_android UI Thread, use postInvalidate()

myView.postInvalidate();

This will post an invalidate request on anycodings_android the UI-thread.

For more information : anycodings_android what-does-postinvalidate-do

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

4

Answers 22 : of Android Only the original thread that created a view hierarchy can touch its views.

Well, You can do it like this.

https://developer.android.com/reference/android/view/View#post(java.lang.Runnable)

A simple approach

currentTime.post(new Runnable(){ @Override public void run() { currentTime.setText(time); } }

it also provides delay

https://developer.android.com/reference/android/view/View#postDelayed(java.lang.Runnable,%20long)

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

miraj

6

Answers 23 : of Android Only the original thread that created a view hierarchy can touch its views.

For me the issue was that I was calling anycodings_android onProgressUpdate() explicitly from my anycodings_android code. This shouldn't be done. I called anycodings_android publishProgress() instead and that anycodings_android resolved the error.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

3

Answers 24 : of Android Only the original thread that created a view hierarchy can touch its views.

In my case, I have EditText in Adaptor, anycodings_android and it's already in the UI thread. anycodings_android However, when this Activity loads, it's anycodings_android crashes with this error.

My solution is I need to remove anycodings_android <requestFocus /> out from EditText anycodings_android in XML.

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

miraj

5

Answers 25 : of Android Only the original thread that created a view hierarchy can touch its views.

For the people struggling in Kotlin, it anycodings_android works like this:

lateinit var runnable: Runnable //global variable runOnUiThread { //Lambda runnable = Runnable { //do something here runDelayedHandler(5000) } } runnable.run() //you need to keep the handler outside the runnable body to work in kotlin fun runDelayedHandler(timeToWait: Long) { //Keep it running val handler = Handler() handler.postDelayed(runnable, timeToWait) }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

4

Answers 26 : of Android Only the original thread that created a view hierarchy can touch its views.

If you couldn't find a UIThread you can anycodings_android use this way .

yourcurrentcontext mean, you need to anycodings_android parse Current Context

new Thread(new Runnable() { public void run() { while (true) { (Activity) yourcurrentcontext).runOnUiThread(new Runnable() { public void run() { Log.d("Thread Log","I am from UI Thread"); } }); try { Thread.sleep(1000); } catch (Exception ex) { } } } }).start();

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

joy

5

Answers 27 : of Android Only the original thread that created a view hierarchy can touch its views.

If you are within a fragment, then you anycodings_android also need to get the activity object as anycodings_android runOnUIThread is a method on the anycodings_android activity.

An example in Kotlin with some anycodings_android surrounding context to make it clearer - anycodings_android this example is navigating from a camera anycodings_android fragment to a gallery fragment:

// Setup image capture listener which is triggered after photo has been taken imageCapture.takePicture( outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback { override fun onError(exc: ImageCaptureException) { Log.e(TAG, "Photo capture failed: ${exc.message}", exc) } override fun onImageSaved(output: ImageCapture.OutputFileResults) { val savedUri = output.savedUri ?: Uri.fromFile(photoFile) Log.d(TAG, "Photo capture succeeded: $savedUri") //Do whatever work you do when image is saved //Now ask navigator to move to new tab - as this //updates UI do on the UI thread activity?.runOnUiThread( { Navigation.findNavController( requireActivity(), R.id.fragment_container ).navigate(CameraFragmentDirections .actionCameraToGallery(outputDirectory.absolutePath)) })

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

1

Answers 28 : of Android Only the original thread that created a view hierarchy can touch its views.

For anyone using fragment:

(context as Activity).runOnUiThread { //TODO }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

raja

4

Answers 29 : of Android Only the original thread that created a view hierarchy can touch its views.

Solved : Just put this method in anycodings_android doInBackround Class... and pass the anycodings_android message

public void setProgressText(final String progressText){ Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { // Any UI task, example progressDialog.setMessage(progressText); } }; handler.sendEmptyMessage(1); }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

jidam

3

Answers 30 : of Android Only the original thread that created a view hierarchy can touch its views.

In my case, the caller calls too many anycodings_android times in short time will get this error, anycodings_android I simply put elapsed time checking to do anycodings_android nothing if too short, e.g. ignore if anycodings_android function get called less than 0.5 anycodings_android second:

private long mLastClickTime = 0; public boolean foo() { if ( (SystemClock.elapsedRealtime() - mLastClickTime) < 500) { return false; } mLastClickTime = SystemClock.elapsedRealtime(); //... do ui update }

0

2022-08-04T23:35:29+00:00 2022-08-04T23:35:29+00:00Answer Link

miraj