Reputation: 1157
I have Character and a Monster, and want to simule a battle. To do so, I created two threads, one with the character's attack, and another with the monster's attack. Character and monster has different attack speed, so their threads "wait" time will be different. My method looks like this (I summed up the method):
public void attack(){
//Character's attack thread
Thread characterAttackThread = new Thread(new Runnable() {
@Override
public void run() {
try {
while(character.getHp()>0 && monster.getHp()>0){
int damage = character.getDamage();
monster.setHp(monster.getHp() - damage);
Thread.sleep(character.getSpeed());
}
if(character.getHp()<=0){
updateScreen("Character died"); //shows message to user
}else{
updateScreen("Monster died"); //shows message to user
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
//Monster's attack thread
Thread monsterAttackThread = new Thread(new Runnable() {
@Override
public void run() {
try {
while(character.getHp()>0 && monster.getHp()>0){
int damage = character.getDamage();
monster.setHp(monster.getHp() - damage);
this.wait(character.getSpeed());
}
Thread.sleep(monster.getSpeed());
} catch (Exception e) {
e.printStackTrace();
}
}
});
characterAttackThread.start();
monsterAttackThread.start();
}
But when I reach the updateScreen("Message");
I get the error
Only the original thread that created a view hierarchy can touch its views.
What can I do to get the problem solved?
Thanks in advance!
Upvotes: 0
Views: 719
Reputation: 8478
You cannot modify the android toolkit from any other thread apart from UI thread
This link will give you clarifications :
http://developer.android.com/guide/components/processes-and-threads.html
You may do one of the follow:
Use the following code in your thread:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
Hope this helps
Upvotes: 1