CalledFromWrongThreadException - android

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 is not running.it got CalledFromWrongThreadException what is the problem inb the above code.Please give me some suggestions.Thanks in advance

I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.

I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
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();
}
}

Related

How to pass variables to UI thread from worker thread?

Below is the code for simple get request and res variable is not available inside Ui thread. How this can be achieved in android?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
try {
String res = Utils.GetRequest("http://www.google.com");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
Okay, I found out that I haven't declared the res variable as final.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable(){
#Override
public void run(){
try {
final String res = Utils.GetRequest("http://www.google.com");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
You have to create a handler on the Main thread in the OnCreate()
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message inputMessage) {
// handle the passed value here
// for ex. update the UI by getting the data from the inputMessage
}
}
inside your Thread .. call the
Message myMessage = mHandler.obtainMessage();
myMessage.obj = "the value to update the ui";
mHandler.sendMessage(myMessage);

How to Update UI while a task is running in another thread in android?

I have tried updating my user interface using the text view what i have done is a run a while loop indefinitely and left the thread for sleep for one second..
int i;
while(true)
{
Thread.Sleep(1000);
textView.setText(updateTime);
}
Use runOnUiThread and surround with try catch for Thread.sleep(1000)
int i;
while(true)
{
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
textView.setText(updateTime);
}
});
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try this one arnab...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.displayid);
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
bundle = msg.getData();
textView.setText(bundle.getString("mKey"));
}
};
}
public void press(View v) {
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
synchronized (this) {
try {
wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bundle = new Bundle();
message = handler.obtainMessage();
simpleDateFormat = new SimpleDateFormat("hh:mm:ss YYYY/mm/dd", Locale.US);
date = simpleDateFormat.format(new Date());
bundle.putString("mKey", date);
message.setData(bundle);
handler.sendMessage(message);
}
}
}
}).start();
}
Try runOnUiThread:
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(updateTime);
}
});

error on finish AsyncTask

After recieving a pictures from user, putting them in an array, animate() method is called from main, this method contains Asynktask. How can I finish this AsyncTask?
This is my code:
private void animate() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(pics[0]);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
while (true) {
try {
Thread.sleep(500);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(pics[pos]);
pos = (pos + 1);
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}.execute();
}
From your code, I guess what you want is to change the image you show in an ImageView periodically. I'd suggest to change your code to use a Timer:
private Timer mTimer;
private void startCarousel(){
mTimer = new Timer();
TimerTask timerTask = new TimerTask() {
public void run() {
// Your periodic task...
}
};
mTimer.schedule(timerTask, 1000, 500);
}
private void stopCarousel(){
if(mTimer != null){
mTimer.cancel();
mTimer.purge();
}
}

after thread sleep TextView is not printing vlaue

tv value set to value 1 then after 5000 it does not set its value , showdown the app
tv = (TextView) findViewById(R.id.textView1);
Thread time = new Thread(){
public void run(){
try{
tv.setText("Value 1");
sleep(5000);
tv.setText("Value 2");
}
catch ( InterruptedException e){
e.printStackTrace();
}finally{
tv.setText("Value 3");
}
}
};
time.start();
You should call Activity.runOnUiThread() to update the UI from other threads.
Thread t = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Value 1");
}
});
}
};
OR
Use a Handler:
Thread t =new Thread(){
public void run() {
handler.post(new Runnable() {
public void run() {
tv.setText("Value 1");
}
});
}
}};
You have to run the code that deals with UI on the main thread... it's called UIThread... you can do any thing on another threads except handling UI
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
tv.setText....
}
});
You have to run the TextView update method inside the runOnUiThread() method. Your code should look something like this:
Thread time = new Thread() {
public void run() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Value 1");
}
});
sleep(5000);
runOnUiThread(new Runnable() {
#Override
public void run() {
tv.setText("Value 2");
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
tv.setText("Value 3");
}
}
};
time.start();

How to stop the thread

I have searched about kill the Runnable but i could not find the true answer with this code.I have tried boolean and stop() method.Can somebody help me to kill this runnable? Thanks.
Runnable runnable = new Runnable() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.close);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.open);
}
});
}
}
};
new Thread(runnable).start();
you can set your exit condition:
private class MyThread extends Thread {
private boolean volatile exit = false;
#Override
public void run() {
while(!exit) {
}
}
public void stopMyThread() {
exit = true;
}
}
and from your code you call
myThreadInstance.stopMyThread();
when you need to make you run method finish
You are repeating infinitely a one-second-wait. This will never stop. You need to have a boolean flag which will serve as the continue/stop condition and you need to negate its value when the Thread needs to stop.
If you want to stop it from another Thread, then call Thread.interrupt.

Categories

Resources