CalledFromWrongThreadException

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ThraedDemo objDemo = new ThraedDemo(); Thread objThread = new Thread() { @Override public void run() { objDemo.firstMethod(); } }; objThread.start(); } class ThraedDemo { private void firstMethod() { Thread objThread = new Thread() { @Override public void run() { try { ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]); Thread.sleep(10000); Log.v("Thread","1111111111111111sleep"); } catch (InterruptedException ex) { System.out.println("interuped exception" + ex.getMessage()); } secondMethod(); } private void secondMethod() { Thread objThread = new Thread() { @Override public void run() { try { ((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]); n++; Thread.sleep(10000); Log.v("Thread","22222222222 sleep"); } catch (InterruptedException ex) { System.out.println("interuped exception" + ex.getMessage()); } firstMethod(); } }; objThread.start(); } }; objThread.start(); } } 

I use the above code, but it does not work. He got a CalledFromWrongThreadException , which is the problem in the above code. Please give me some suggestions. thanks in advance

+7
android
Aug 05 '10 at 9:52
source share
2 answers

I think that you cannot view modifications from a thread other than the user interface thread, so either create handlers in oncreate and publish your thread to it, or use AsyncTask or runOnUIThread to send parts of the code directly to the user interface thread.

+8
Aug 05 2018-10-10T00:
source share

I edited your second function code, I see that your code is a loop forever, because firstMethod calls secondMethod, and secondMethod calls a new firstMethod to start, and then the loop is forever. I deleted it and moved the ImageView code update to the UI thread, could you try the following:

 class ThraedDemo { private void firstMethod() { Thread objThread = new Thread() { @Override public void run() { try { runOnUiThread(new Runnable() { public void run(){ ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]); } }); Thread.sleep(10000); Log.v("Thread","1111111111111111sleep"); } catch (InterruptedException ex) { System.out.println("interuped exception" + ex.getMessage()); } secondMethod(); } }; objThread.start(); } private void secondMethod() { Thread objThread2 = new Thread() { @Override public void run() { try { runOnUiThread(new Runnable() { public void run(){ ((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]); } }); n++; Thread.sleep(10000); Log.v("Thread","22222222222 sleep"); } catch (InterruptedException ex) { System.out.println("interuped exception" + ex.getMessage()); } } }; objThread2.start(); } } 
0
Dec 24 '15 at 3:54
source share



All Articles